Add entry to run tests2 tests
[tinycc.git] / tccgen.c
blob1919c3cbdaa0bdcccd55bc8f3549a551cce2f7b7
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 int64_t v1, v2;
66 int sym;
67 } **p; int n; /* list of case ranges */
68 int def_sym; /* default symbol */
69 } *cur_switch; /* current switch */
71 /* ------------------------------------------------------------------------- */
73 static void gen_cast(CType *type);
74 static inline CType *pointed_type(CType *type);
75 static int is_compatible_types(CType *type1, CType *type2);
76 static int parse_btype(CType *type, AttributeDef *ad);
77 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
78 static void parse_expr_type(CType *type);
79 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
80 static void block(int *bsym, int *csym, int is_expr);
81 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
82 static int decl0(int l, int is_for_loop_init);
83 static void expr_eq(void);
84 static void expr_lor_const(void);
85 static void unary_type(CType *type);
86 static void vla_runtime_type_size(CType *type, int *a);
87 static void vla_sp_restore(void);
88 static void vla_sp_restore_root(void);
89 static int is_compatible_parameter_types(CType *type1, CType *type2);
90 static void expr_type(CType *type);
91 static inline int64_t expr_const64(void);
92 ST_FUNC void vpush64(int ty, unsigned long long v);
93 ST_FUNC void vpush(CType *type);
94 ST_FUNC int gvtst(int inv, int t);
95 ST_FUNC int is_btype_size(int bt);
96 static void gen_inline_functions(TCCState *s);
98 ST_INLN int is_float(int t)
100 int bt;
101 bt = t & VT_BTYPE;
102 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
105 /* we use our own 'finite' function to avoid potential problems with
106 non standard math libs */
107 /* XXX: endianness dependent */
108 ST_FUNC int ieee_finite(double d)
110 int p[4];
111 memcpy(p, &d, sizeof(double));
112 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
115 ST_FUNC void test_lvalue(void)
117 if (!(vtop->r & VT_LVAL))
118 expect("lvalue");
121 ST_FUNC void check_vstack(void)
123 if (pvtop != vtop)
124 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
127 /* ------------------------------------------------------------------------- */
128 /* vstack debugging aid */
130 #if 0
131 void pv (const char *lbl, int a, int b)
133 int i;
134 for (i = a; i < a + b; ++i) {
135 SValue *p = &vtop[-i];
136 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
137 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
140 #endif
142 /* ------------------------------------------------------------------------- */
143 ST_FUNC void tccgen_start(TCCState *s1)
145 cur_text_section = NULL;
146 funcname = "";
147 anon_sym = SYM_FIRST_ANOM;
148 section_sym = 0;
149 const_wanted = 0;
150 nocode_wanted = 1;
152 /* define some often used types */
153 int_type.t = VT_INT;
154 char_pointer_type.t = VT_BYTE;
155 mk_pointer(&char_pointer_type);
156 #if PTR_SIZE == 4
157 size_type.t = VT_INT;
158 #else
159 size_type.t = VT_LLONG;
160 #endif
161 func_old_type.t = VT_FUNC;
162 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
164 if (s1->do_debug) {
165 char buf[512];
167 /* file info: full path + filename */
168 section_sym = put_elf_sym(symtab_section, 0, 0,
169 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
170 text_section->sh_num, NULL);
171 getcwd(buf, sizeof(buf));
172 #ifdef _WIN32
173 normalize_slashes(buf);
174 #endif
175 pstrcat(buf, sizeof(buf), "/");
176 put_stabs_r(buf, N_SO, 0, 0,
177 text_section->data_offset, text_section, section_sym);
178 put_stabs_r(file->filename, N_SO, 0, 0,
179 text_section->data_offset, text_section, section_sym);
181 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
182 symbols can be safely used */
183 put_elf_sym(symtab_section, 0, 0,
184 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
185 SHN_ABS, file->filename);
187 #ifdef TCC_TARGET_ARM
188 arm_init(s1);
189 #endif
192 ST_FUNC void tccgen_end(TCCState *s1)
194 gen_inline_functions(s1);
195 check_vstack();
196 /* end of translation unit info */
197 if (s1->do_debug) {
198 put_stabs_r(NULL, N_SO, 0, 0,
199 text_section->data_offset, text_section, section_sym);
203 /* ------------------------------------------------------------------------- */
204 /* update sym->c so that it points to an external symbol in section
205 'section' with value 'value' */
207 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
208 addr_t value, unsigned long size,
209 int can_add_underscore)
211 int sym_type, sym_bind, sh_num, info, other;
212 ElfW(Sym) *esym;
213 const char *name;
214 char buf1[256];
216 #ifdef CONFIG_TCC_BCHECK
217 char buf[32];
218 #endif
220 if (section == NULL)
221 sh_num = SHN_UNDEF;
222 else if (section == SECTION_ABS)
223 sh_num = SHN_ABS;
224 else
225 sh_num = section->sh_num;
227 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
228 sym_type = STT_FUNC;
229 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
230 sym_type = STT_NOTYPE;
231 } else {
232 sym_type = STT_OBJECT;
235 if (sym->type.t & VT_STATIC)
236 sym_bind = STB_LOCAL;
237 else {
238 if (sym->type.t & VT_WEAK)
239 sym_bind = STB_WEAK;
240 else
241 sym_bind = STB_GLOBAL;
244 if (!sym->c) {
245 name = get_tok_str(sym->v, NULL);
246 #ifdef CONFIG_TCC_BCHECK
247 if (tcc_state->do_bounds_check) {
248 /* XXX: avoid doing that for statics ? */
249 /* if bound checking is activated, we change some function
250 names by adding the "__bound" prefix */
251 switch(sym->v) {
252 #ifdef TCC_TARGET_PE
253 /* XXX: we rely only on malloc hooks */
254 case TOK_malloc:
255 case TOK_free:
256 case TOK_realloc:
257 case TOK_memalign:
258 case TOK_calloc:
259 #endif
260 case TOK_memcpy:
261 case TOK_memmove:
262 case TOK_memset:
263 case TOK_strlen:
264 case TOK_strcpy:
265 case TOK_alloca:
266 strcpy(buf, "__bound_");
267 strcat(buf, name);
268 name = buf;
269 break;
272 #endif
273 other = 0;
275 #ifdef TCC_TARGET_PE
276 if (sym->type.t & VT_EXPORT)
277 other |= ST_PE_EXPORT;
278 if (sym_type == STT_FUNC && sym->type.ref) {
279 Sym *ref = sym->type.ref;
280 if (ref->a.func_export)
281 other |= ST_PE_EXPORT;
282 if (ref->a.func_call == FUNC_STDCALL && can_add_underscore) {
283 sprintf(buf1, "_%s@%d", name, ref->a.func_args * PTR_SIZE);
284 name = buf1;
285 other |= ST_PE_STDCALL;
286 can_add_underscore = 0;
288 } else {
289 if (find_elf_sym(tcc_state->dynsymtab_section, name))
290 other |= ST_PE_IMPORT;
291 if (sym->type.t & VT_IMPORT)
292 other |= ST_PE_IMPORT;
294 #else
295 if (! (sym->type.t & VT_STATIC))
296 other = (sym->type.t & VT_VIS_MASK) >> VT_VIS_SHIFT;
297 #endif
298 if (tcc_state->leading_underscore && can_add_underscore) {
299 buf1[0] = '_';
300 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
301 name = buf1;
303 if (sym->asm_label) {
304 name = get_tok_str(sym->asm_label, NULL);
306 info = ELFW(ST_INFO)(sym_bind, sym_type);
307 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
308 } else {
309 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
310 esym->st_value = value;
311 esym->st_size = size;
312 esym->st_shndx = sh_num;
316 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
317 addr_t value, unsigned long size)
319 put_extern_sym2(sym, section, value, size, 1);
322 /* add a new relocation entry to symbol 'sym' in section 's' */
323 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
324 addr_t addend)
326 int c = 0;
328 if (nocode_wanted && s == cur_text_section)
329 return;
331 if (sym) {
332 if (0 == sym->c)
333 put_extern_sym(sym, NULL, 0, 0);
334 c = sym->c;
337 /* now we can add ELF relocation info */
338 put_elf_reloca(symtab_section, s, offset, type, c, addend);
341 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
343 greloca(s, sym, offset, type, 0);
346 /* ------------------------------------------------------------------------- */
347 /* symbol allocator */
348 static Sym *__sym_malloc(void)
350 Sym *sym_pool, *sym, *last_sym;
351 int i;
353 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
354 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
356 last_sym = sym_free_first;
357 sym = sym_pool;
358 for(i = 0; i < SYM_POOL_NB; i++) {
359 sym->next = last_sym;
360 last_sym = sym;
361 sym++;
363 sym_free_first = last_sym;
364 return last_sym;
367 static inline Sym *sym_malloc(void)
369 Sym *sym;
370 #ifndef SYM_DEBUG
371 sym = sym_free_first;
372 if (!sym)
373 sym = __sym_malloc();
374 sym_free_first = sym->next;
375 return sym;
376 #else
377 sym = tcc_malloc(sizeof(Sym));
378 return sym;
379 #endif
382 ST_INLN void sym_free(Sym *sym)
384 #ifndef SYM_DEBUG
385 sym->next = sym_free_first;
386 sym_free_first = sym;
387 #else
388 tcc_free(sym);
389 #endif
392 /* push, without hashing */
393 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
395 Sym *s;
397 s = sym_malloc();
398 s->scope = 0;
399 s->v = v;
400 s->type.t = t;
401 s->type.ref = NULL;
402 #ifdef _WIN64
403 s->d = NULL;
404 #endif
405 s->c = c;
406 s->next = NULL;
407 /* add in stack */
408 s->prev = *ps;
409 *ps = s;
410 return s;
413 /* find a symbol and return its associated structure. 's' is the top
414 of the symbol stack */
415 ST_FUNC Sym *sym_find2(Sym *s, int v)
417 while (s) {
418 if (s->v == v)
419 return s;
420 else if (s->v == -1)
421 return NULL;
422 s = s->prev;
424 return NULL;
427 /* structure lookup */
428 ST_INLN Sym *struct_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_struct;
436 /* find an identifier */
437 ST_INLN Sym *sym_find(int v)
439 v -= TOK_IDENT;
440 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
441 return NULL;
442 return table_ident[v]->sym_identifier;
445 /* push a given symbol on the symbol stack */
446 ST_FUNC Sym *sym_push(int v, CType *type, int r, long c)
448 Sym *s, **ps;
449 TokenSym *ts;
451 if (local_stack)
452 ps = &local_stack;
453 else
454 ps = &global_stack;
455 s = sym_push2(ps, v, type->t, c);
456 s->type.ref = type->ref;
457 s->r = r;
458 /* don't record fields or anonymous symbols */
459 /* XXX: simplify */
460 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
461 /* record symbol in token array */
462 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
463 if (v & SYM_STRUCT)
464 ps = &ts->sym_struct;
465 else
466 ps = &ts->sym_identifier;
467 s->prev_tok = *ps;
468 *ps = s;
469 s->scope = local_scope;
470 if (s->prev_tok && s->prev_tok->scope == s->scope)
471 tcc_error("redeclaration of '%s'",
472 get_tok_str(v & ~SYM_STRUCT, NULL));
474 return s;
477 /* push a global identifier */
478 ST_FUNC Sym *global_identifier_push(int v, int t, long c)
480 Sym *s, **ps;
481 s = sym_push2(&global_stack, v, t, c);
482 /* don't record anonymous symbol */
483 if (v < SYM_FIRST_ANOM) {
484 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
485 /* modify the top most local identifier, so that
486 sym_identifier will point to 's' when popped */
487 while (*ps != NULL)
488 ps = &(*ps)->prev_tok;
489 s->prev_tok = NULL;
490 *ps = s;
492 return s;
495 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
496 pop them yet from the list, but do remove them from the token array. */
497 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
499 Sym *s, *ss, **ps;
500 TokenSym *ts;
501 int v;
503 s = *ptop;
504 while(s != b) {
505 ss = s->prev;
506 v = s->v;
507 /* remove symbol in token array */
508 /* XXX: simplify */
509 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
510 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
511 if (v & SYM_STRUCT)
512 ps = &ts->sym_struct;
513 else
514 ps = &ts->sym_identifier;
515 *ps = s->prev_tok;
517 if (!keep)
518 sym_free(s);
519 s = ss;
521 if (!keep)
522 *ptop = b;
525 static void weaken_symbol(Sym *sym)
527 sym->type.t |= VT_WEAK;
528 if (sym->c > 0) {
529 int esym_type;
530 ElfW(Sym) *esym;
532 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
533 esym_type = ELFW(ST_TYPE)(esym->st_info);
534 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
538 static void apply_visibility(Sym *sym, CType *type)
540 int vis = sym->type.t & VT_VIS_MASK;
541 int vis2 = type->t & VT_VIS_MASK;
542 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
543 vis = vis2;
544 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
546 else
547 vis = (vis < vis2) ? vis : vis2;
548 sym->type.t &= ~VT_VIS_MASK;
549 sym->type.t |= vis;
551 if (sym->c > 0) {
552 ElfW(Sym) *esym;
554 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
555 vis >>= VT_VIS_SHIFT;
556 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
560 /* ------------------------------------------------------------------------- */
562 static void vsetc(CType *type, int r, CValue *vc)
564 int v;
566 if (vtop >= vstack + (VSTACK_SIZE - 1))
567 tcc_error("memory full (vstack)");
568 /* cannot let cpu flags if other instruction are generated. Also
569 avoid leaving VT_JMP anywhere except on the top of the stack
570 because it would complicate the code generator.
572 Don't do this when nocode_wanted. vtop might come from
573 !nocode_wanted regions (see 88_codeopt.c) and transforming
574 it to a register without actually generating code is wrong
575 as their value might still be used for real. All values
576 we push under nocode_wanted will eventually be popped
577 again, so that the VT_CMP/VT_JMP value will be in vtop
578 when code is unsuppressed again.
580 Same logic below in vswap(); */
581 if (vtop >= vstack && !nocode_wanted) {
582 v = vtop->r & VT_VALMASK;
583 if (v == VT_CMP || (v & ~1) == VT_JMP)
584 gv(RC_INT);
587 vtop++;
588 vtop->type = *type;
589 vtop->r = r;
590 vtop->r2 = VT_CONST;
591 vtop->c = *vc;
592 vtop->sym = NULL;
595 ST_FUNC void vswap(void)
597 SValue tmp;
598 /* cannot vswap cpu flags. See comment at vsetc() above */
599 if (vtop >= vstack && !nocode_wanted) {
600 int v = vtop->r & VT_VALMASK;
601 if (v == VT_CMP || (v & ~1) == VT_JMP)
602 gv(RC_INT);
604 tmp = vtop[0];
605 vtop[0] = vtop[-1];
606 vtop[-1] = tmp;
609 /* pop stack value */
610 ST_FUNC void vpop(void)
612 int v;
613 v = vtop->r & VT_VALMASK;
614 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
615 /* for x86, we need to pop the FP stack */
616 if (v == TREG_ST0) {
617 o(0xd8dd); /* fstp %st(0) */
618 } else
619 #endif
620 if (v == VT_JMP || v == VT_JMPI) {
621 /* need to put correct jump if && or || without test */
622 gsym(vtop->c.i);
624 vtop--;
627 /* push constant of type "type" with useless value */
628 ST_FUNC void vpush(CType *type)
630 CValue cval;
631 vsetc(type, VT_CONST, &cval);
634 /* push integer constant */
635 ST_FUNC void vpushi(int v)
637 CValue cval;
638 cval.i = v;
639 vsetc(&int_type, VT_CONST, &cval);
642 /* push a pointer sized constant */
643 static void vpushs(addr_t v)
645 CValue cval;
646 cval.i = v;
647 vsetc(&size_type, VT_CONST, &cval);
650 /* push arbitrary 64bit constant */
651 ST_FUNC void vpush64(int ty, unsigned long long v)
653 CValue cval;
654 CType ctype;
655 ctype.t = ty;
656 ctype.ref = NULL;
657 cval.i = v;
658 vsetc(&ctype, VT_CONST, &cval);
661 /* push long long constant */
662 static inline void vpushll(long long v)
664 vpush64(VT_LLONG, v);
667 ST_FUNC void vset(CType *type, int r, long v)
669 CValue cval;
671 cval.i = v;
672 vsetc(type, r, &cval);
675 static void vseti(int r, int v)
677 CType type;
678 type.t = VT_INT;
679 type.ref = 0;
680 vset(&type, r, v);
683 ST_FUNC void vpushv(SValue *v)
685 if (vtop >= vstack + (VSTACK_SIZE - 1))
686 tcc_error("memory full (vstack)");
687 vtop++;
688 *vtop = *v;
691 static void vdup(void)
693 vpushv(vtop);
696 /* rotate n first stack elements to the bottom
697 I1 ... In -> I2 ... In I1 [top is right]
699 ST_FUNC void vrotb(int n)
701 int i;
702 SValue tmp;
704 tmp = vtop[-n + 1];
705 for(i=-n+1;i!=0;i++)
706 vtop[i] = vtop[i+1];
707 vtop[0] = tmp;
710 /* rotate the n elements before entry e towards the top
711 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
713 ST_FUNC void vrote(SValue *e, int n)
715 int i;
716 SValue tmp;
718 tmp = *e;
719 for(i = 0;i < n - 1; i++)
720 e[-i] = e[-i - 1];
721 e[-n + 1] = tmp;
724 /* rotate n first stack elements to the top
725 I1 ... In -> In I1 ... I(n-1) [top is right]
727 ST_FUNC void vrott(int n)
729 vrote(vtop, n);
732 /* push a symbol value of TYPE */
733 static inline void vpushsym(CType *type, Sym *sym)
735 CValue cval;
736 cval.i = 0;
737 vsetc(type, VT_CONST | VT_SYM, &cval);
738 vtop->sym = sym;
741 /* Return a static symbol pointing to a section */
742 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
744 int v;
745 Sym *sym;
747 v = anon_sym++;
748 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
749 sym->type.ref = type->ref;
750 sym->r = VT_CONST | VT_SYM;
751 put_extern_sym(sym, sec, offset, size);
752 return sym;
755 /* push a reference to a section offset by adding a dummy symbol */
756 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
758 vpushsym(type, get_sym_ref(type, sec, offset, size));
761 /* define a new external reference to a symbol 'v' of type 'u' */
762 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
764 Sym *s;
766 s = sym_find(v);
767 if (!s) {
768 /* push forward reference */
769 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
770 s->type.ref = type->ref;
771 s->r = r | VT_CONST | VT_SYM;
773 return s;
776 /* define a new external reference to a symbol 'v' */
777 static Sym *external_sym(int v, CType *type, int r)
779 Sym *s;
781 s = sym_find(v);
782 if (!s) {
783 /* push forward reference */
784 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
785 s->type.t |= VT_EXTERN;
786 } else if (s->type.ref == func_old_type.ref) {
787 s->type.ref = type->ref;
788 s->r = r | VT_CONST | VT_SYM;
789 s->type.t |= VT_EXTERN;
790 } else if (!is_compatible_types(&s->type, type)) {
791 tcc_error("incompatible types for redefinition of '%s'",
792 get_tok_str(v, NULL));
794 /* Merge some storage attributes. */
795 if (type->t & VT_WEAK)
796 weaken_symbol(s);
798 if (type->t & VT_VIS_MASK)
799 apply_visibility(s, type);
801 return s;
804 /* push a reference to global symbol v */
805 ST_FUNC void vpush_global_sym(CType *type, int v)
807 vpushsym(type, external_global_sym(v, type, 0));
810 /* save registers up to (vtop - n) stack entry */
811 ST_FUNC void save_regs(int n)
813 SValue *p, *p1;
814 for(p = vstack, p1 = vtop - n; p <= p1; p++)
815 save_reg(p->r);
818 /* save r to the memory stack, and mark it as being free */
819 ST_FUNC void save_reg(int r)
821 save_reg_upstack(r, 0);
824 /* save r to the memory stack, and mark it as being free,
825 if seen up to (vtop - n) stack entry */
826 ST_FUNC void save_reg_upstack(int r, int n)
828 int l, saved, size, align;
829 SValue *p, *p1, sv;
830 CType *type;
832 if ((r &= VT_VALMASK) >= VT_CONST)
833 return;
834 if (nocode_wanted)
835 return;
837 /* modify all stack values */
838 saved = 0;
839 l = 0;
840 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
841 if ((p->r & VT_VALMASK) == r ||
842 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
843 /* must save value on stack if not already done */
844 if (!saved) {
845 /* NOTE: must reload 'r' because r might be equal to r2 */
846 r = p->r & VT_VALMASK;
847 /* store register in the stack */
848 type = &p->type;
849 if ((p->r & VT_LVAL) ||
850 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
851 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
852 type = &char_pointer_type;
853 #else
854 type = &int_type;
855 #endif
856 if ((type->t & VT_BTYPE) == VT_FLOAT) {
857 /* cast to DOUBLE to avoid precision loss */
858 type->t = (type->t & ~VT_BTYPE) | VT_DOUBLE;
860 size = type_size(type, &align);
861 loc = (loc - size) & -align;
862 sv.type.t = type->t;
863 sv.r = VT_LOCAL | VT_LVAL;
864 sv.c.i = loc;
865 store(r, &sv);
866 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
867 /* x86 specific: need to pop fp register ST0 if saved */
868 if (r == TREG_ST0) {
869 o(0xd8dd); /* fstp %st(0) */
871 #endif
872 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
873 /* special long long case */
874 if ((type->t & VT_BTYPE) == VT_LLONG) {
875 sv.c.i += 4;
876 store(p->r2, &sv);
878 #endif
879 l = loc;
880 saved = 1;
882 /* mark that stack entry as being saved on the stack */
883 if (p->r & VT_LVAL) {
884 /* also clear the bounded flag because the
885 relocation address of the function was stored in
886 p->c.i */
887 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
888 } else {
889 p->r = lvalue_type(p->type.t) | VT_LOCAL;
891 p->r2 = VT_CONST;
892 p->c.i = l;
897 #ifdef TCC_TARGET_ARM
898 /* find a register of class 'rc2' with at most one reference on stack.
899 * If none, call get_reg(rc) */
900 ST_FUNC int get_reg_ex(int rc, int rc2)
902 int r;
903 SValue *p;
905 for(r=0;r<NB_REGS;r++) {
906 if (reg_classes[r] & rc2) {
907 int n;
908 n=0;
909 for(p = vstack; p <= vtop; p++) {
910 if ((p->r & VT_VALMASK) == r ||
911 (p->r2 & VT_VALMASK) == r)
912 n++;
914 if (n <= 1)
915 return r;
918 return get_reg(rc);
920 #endif
922 /* find a free register of class 'rc'. If none, save one register */
923 ST_FUNC int get_reg(int rc)
925 int r;
926 SValue *p;
928 /* find a free register */
929 for(r=0;r<NB_REGS;r++) {
930 if (reg_classes[r] & rc) {
931 if (nocode_wanted)
932 return r;
933 for(p=vstack;p<=vtop;p++) {
934 if ((p->r & VT_VALMASK) == r ||
935 (p->r2 & VT_VALMASK) == r)
936 goto notfound;
938 return r;
940 notfound: ;
943 /* no register left : free the first one on the stack (VERY
944 IMPORTANT to start from the bottom to ensure that we don't
945 spill registers used in gen_opi()) */
946 for(p=vstack;p<=vtop;p++) {
947 /* look at second register (if long long) */
948 r = p->r2 & VT_VALMASK;
949 if (r < VT_CONST && (reg_classes[r] & rc))
950 goto save_found;
951 r = p->r & VT_VALMASK;
952 if (r < VT_CONST && (reg_classes[r] & rc)) {
953 save_found:
954 save_reg(r);
955 return r;
958 /* Should never comes here */
959 return -1;
962 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
963 if needed */
964 static void move_reg(int r, int s, int t)
966 SValue sv;
968 if (r != s) {
969 save_reg(r);
970 sv.type.t = t;
971 sv.type.ref = NULL;
972 sv.r = s;
973 sv.c.i = 0;
974 load(r, &sv);
978 /* get address of vtop (vtop MUST BE an lvalue) */
979 ST_FUNC void gaddrof(void)
981 if (vtop->r & VT_REF)
982 gv(RC_INT);
983 vtop->r &= ~VT_LVAL;
984 /* tricky: if saved lvalue, then we can go back to lvalue */
985 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
986 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
991 #ifdef CONFIG_TCC_BCHECK
992 /* generate lvalue bound code */
993 static void gbound(void)
995 int lval_type;
996 CType type1;
998 vtop->r &= ~VT_MUSTBOUND;
999 /* if lvalue, then use checking code before dereferencing */
1000 if (vtop->r & VT_LVAL) {
1001 /* if not VT_BOUNDED value, then make one */
1002 if (!(vtop->r & VT_BOUNDED)) {
1003 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1004 /* must save type because we must set it to int to get pointer */
1005 type1 = vtop->type;
1006 vtop->type.t = VT_PTR;
1007 gaddrof();
1008 vpushi(0);
1009 gen_bounded_ptr_add();
1010 vtop->r |= lval_type;
1011 vtop->type = type1;
1013 /* then check for dereferencing */
1014 gen_bounded_ptr_deref();
1017 #endif
1019 /* store vtop a register belonging to class 'rc'. lvalues are
1020 converted to values. Cannot be used if cannot be converted to
1021 register value (such as structures). */
1022 ST_FUNC int gv(int rc)
1024 int r, bit_pos, bit_size, size, align, i;
1025 int rc2;
1027 /* NOTE: get_reg can modify vstack[] */
1028 if (vtop->type.t & VT_BITFIELD) {
1029 CType type;
1030 int bits = 32;
1031 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
1032 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
1033 /* remove bit field info to avoid loops */
1034 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
1035 /* cast to int to propagate signedness in following ops */
1036 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1037 type.t = VT_LLONG;
1038 bits = 64;
1039 } else
1040 type.t = VT_INT;
1041 if((vtop->type.t & VT_UNSIGNED) ||
1042 (vtop->type.t & VT_BTYPE) == VT_BOOL)
1043 type.t |= VT_UNSIGNED;
1044 gen_cast(&type);
1045 /* generate shifts */
1046 vpushi(bits - (bit_pos + bit_size));
1047 gen_op(TOK_SHL);
1048 vpushi(bits - bit_size);
1049 /* NOTE: transformed to SHR if unsigned */
1050 gen_op(TOK_SAR);
1051 r = gv(rc);
1052 } else {
1053 if (is_float(vtop->type.t) &&
1054 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1055 Sym *sym;
1056 int *ptr;
1057 unsigned long offset;
1058 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
1059 CValue check;
1060 #endif
1062 /* XXX: unify with initializers handling ? */
1063 /* CPUs usually cannot use float constants, so we store them
1064 generically in data segment */
1065 size = type_size(&vtop->type, &align);
1066 offset = (data_section->data_offset + align - 1) & -align;
1067 data_section->data_offset = offset;
1068 /* XXX: not portable yet */
1069 #if defined(__i386__) || defined(__x86_64__)
1070 /* Zero pad x87 tenbyte long doubles */
1071 if (size == LDOUBLE_SIZE) {
1072 vtop->c.tab[2] &= 0xffff;
1073 #if LDOUBLE_SIZE == 16
1074 vtop->c.tab[3] = 0;
1075 #endif
1077 #endif
1078 ptr = section_ptr_add(data_section, size);
1079 size = size >> 2;
1080 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
1081 check.d = 1;
1082 if(check.tab[0])
1083 for(i=0;i<size;i++)
1084 ptr[i] = vtop->c.tab[size-1-i];
1085 else
1086 #endif
1087 for(i=0;i<size;i++)
1088 ptr[i] = vtop->c.tab[i];
1089 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
1090 vtop->r |= VT_LVAL | VT_SYM;
1091 vtop->sym = sym;
1092 vtop->c.i = 0;
1094 #ifdef CONFIG_TCC_BCHECK
1095 if (vtop->r & VT_MUSTBOUND)
1096 gbound();
1097 #endif
1099 r = vtop->r & VT_VALMASK;
1100 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1101 #ifndef TCC_TARGET_ARM64
1102 if (rc == RC_IRET)
1103 rc2 = RC_LRET;
1104 #ifdef TCC_TARGET_X86_64
1105 else if (rc == RC_FRET)
1106 rc2 = RC_QRET;
1107 #endif
1108 #endif
1110 /* need to reload if:
1111 - constant
1112 - lvalue (need to dereference pointer)
1113 - already a register, but not in the right class */
1114 if (r >= VT_CONST
1115 || (vtop->r & VT_LVAL)
1116 || !(reg_classes[r] & rc)
1117 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1118 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1119 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1120 #else
1121 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1122 #endif
1125 r = get_reg(rc);
1126 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1127 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1128 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1129 #else
1130 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1131 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1132 unsigned long long ll;
1133 #endif
1134 int r2, original_type;
1135 original_type = vtop->type.t;
1136 /* two register type load : expand to two words
1137 temporarily */
1138 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1139 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1140 /* load constant */
1141 ll = vtop->c.i;
1142 vtop->c.i = ll; /* first word */
1143 load(r, vtop);
1144 vtop->r = r; /* save register value */
1145 vpushi(ll >> 32); /* second word */
1146 } else
1147 #endif
1148 if (vtop->r & VT_LVAL) {
1149 /* We do not want to modifier the long long
1150 pointer here, so the safest (and less
1151 efficient) is to save all the other registers
1152 in the stack. XXX: totally inefficient. */
1153 #if 0
1154 save_regs(1);
1155 #else
1156 /* lvalue_save: save only if used further down the stack */
1157 save_reg_upstack(vtop->r, 1);
1158 #endif
1159 /* load from memory */
1160 vtop->type.t = load_type;
1161 load(r, vtop);
1162 vdup();
1163 vtop[-1].r = r; /* save register value */
1164 /* increment pointer to get second word */
1165 vtop->type.t = addr_type;
1166 gaddrof();
1167 vpushi(load_size);
1168 gen_op('+');
1169 vtop->r |= VT_LVAL;
1170 vtop->type.t = load_type;
1171 } else {
1172 /* move registers */
1173 load(r, vtop);
1174 vdup();
1175 vtop[-1].r = r; /* save register value */
1176 vtop->r = vtop[-1].r2;
1178 /* Allocate second register. Here we rely on the fact that
1179 get_reg() tries first to free r2 of an SValue. */
1180 r2 = get_reg(rc2);
1181 load(r2, vtop);
1182 vpop();
1183 /* write second register */
1184 vtop->r2 = r2;
1185 vtop->type.t = original_type;
1186 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1187 int t1, t;
1188 /* lvalue of scalar type : need to use lvalue type
1189 because of possible cast */
1190 t = vtop->type.t;
1191 t1 = t;
1192 /* compute memory access type */
1193 if (vtop->r & VT_REF)
1194 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1195 t = VT_PTR;
1196 #else
1197 t = VT_INT;
1198 #endif
1199 else if (vtop->r & VT_LVAL_BYTE)
1200 t = VT_BYTE;
1201 else if (vtop->r & VT_LVAL_SHORT)
1202 t = VT_SHORT;
1203 if (vtop->r & VT_LVAL_UNSIGNED)
1204 t |= VT_UNSIGNED;
1205 vtop->type.t = t;
1206 load(r, vtop);
1207 /* restore wanted type */
1208 vtop->type.t = t1;
1209 } else {
1210 /* one register type load */
1211 load(r, vtop);
1214 vtop->r = r;
1215 #ifdef TCC_TARGET_C67
1216 /* uses register pairs for doubles */
1217 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1218 vtop->r2 = r+1;
1219 #endif
1221 return r;
1224 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1225 ST_FUNC void gv2(int rc1, int rc2)
1227 int v;
1229 /* generate more generic register first. But VT_JMP or VT_CMP
1230 values must be generated first in all cases to avoid possible
1231 reload errors */
1232 v = vtop[0].r & VT_VALMASK;
1233 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1234 vswap();
1235 gv(rc1);
1236 vswap();
1237 gv(rc2);
1238 /* test if reload is needed for first register */
1239 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1240 vswap();
1241 gv(rc1);
1242 vswap();
1244 } else {
1245 gv(rc2);
1246 vswap();
1247 gv(rc1);
1248 vswap();
1249 /* test if reload is needed for first register */
1250 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1251 gv(rc2);
1256 #ifndef TCC_TARGET_ARM64
1257 /* wrapper around RC_FRET to return a register by type */
1258 static int rc_fret(int t)
1260 #ifdef TCC_TARGET_X86_64
1261 if (t == VT_LDOUBLE) {
1262 return RC_ST0;
1264 #endif
1265 return RC_FRET;
1267 #endif
1269 /* wrapper around REG_FRET to return a register by type */
1270 static int reg_fret(int t)
1272 #ifdef TCC_TARGET_X86_64
1273 if (t == VT_LDOUBLE) {
1274 return TREG_ST0;
1276 #endif
1277 return REG_FRET;
1280 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1281 /* expand 64bit on stack in two ints */
1282 static void lexpand(void)
1284 int u, v;
1285 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1286 v = vtop->r & (VT_VALMASK | VT_LVAL);
1287 if (v == VT_CONST) {
1288 vdup();
1289 vtop[0].c.i >>= 32;
1290 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1291 vdup();
1292 vtop[0].c.i += 4;
1293 } else {
1294 gv(RC_INT);
1295 vdup();
1296 vtop[0].r = vtop[-1].r2;
1297 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1299 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1301 #endif
1303 #ifdef TCC_TARGET_ARM
1304 /* expand long long on stack */
1305 ST_FUNC void lexpand_nr(void)
1307 int u,v;
1309 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1310 vdup();
1311 vtop->r2 = VT_CONST;
1312 vtop->type.t = VT_INT | u;
1313 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1314 if (v == VT_CONST) {
1315 vtop[-1].c.i = vtop->c.i;
1316 vtop->c.i = vtop->c.i >> 32;
1317 vtop->r = VT_CONST;
1318 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1319 vtop->c.i += 4;
1320 vtop->r = vtop[-1].r;
1321 } else if (v > VT_CONST) {
1322 vtop--;
1323 lexpand();
1324 } else
1325 vtop->r = vtop[-1].r2;
1326 vtop[-1].r2 = VT_CONST;
1327 vtop[-1].type.t = VT_INT | u;
1329 #endif
1331 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1332 /* build a long long from two ints */
1333 static void lbuild(int t)
1335 gv2(RC_INT, RC_INT);
1336 vtop[-1].r2 = vtop[0].r;
1337 vtop[-1].type.t = t;
1338 vpop();
1340 #endif
1342 /* convert stack entry to register and duplicate its value in another
1343 register */
1344 static void gv_dup(void)
1346 int rc, t, r, r1;
1347 SValue sv;
1349 t = vtop->type.t;
1350 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1351 if ((t & VT_BTYPE) == VT_LLONG) {
1352 lexpand();
1353 gv_dup();
1354 vswap();
1355 vrotb(3);
1356 gv_dup();
1357 vrotb(4);
1358 /* stack: H L L1 H1 */
1359 lbuild(t);
1360 vrotb(3);
1361 vrotb(3);
1362 vswap();
1363 lbuild(t);
1364 vswap();
1365 } else
1366 #endif
1368 /* duplicate value */
1369 rc = RC_INT;
1370 sv.type.t = VT_INT;
1371 if (is_float(t)) {
1372 rc = RC_FLOAT;
1373 #ifdef TCC_TARGET_X86_64
1374 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1375 rc = RC_ST0;
1377 #endif
1378 sv.type.t = t;
1380 r = gv(rc);
1381 r1 = get_reg(rc);
1382 sv.r = r;
1383 sv.c.i = 0;
1384 load(r1, &sv); /* move r to r1 */
1385 vdup();
1386 /* duplicates value */
1387 if (r != r1)
1388 vtop->r = r1;
1392 /* Generate value test
1394 * Generate a test for any value (jump, comparison and integers) */
1395 ST_FUNC int gvtst(int inv, int t)
1397 int v = vtop->r & VT_VALMASK;
1398 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1399 vpushi(0);
1400 gen_op(TOK_NE);
1402 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1403 /* constant jmp optimization */
1404 if ((vtop->c.i != 0) != inv)
1405 t = gjmp(t);
1406 vtop--;
1407 return t;
1409 return gtst(inv, t);
1412 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1413 /* generate CPU independent (unsigned) long long operations */
1414 static void gen_opl(int op)
1416 int t, a, b, op1, c, i;
1417 int func;
1418 unsigned short reg_iret = REG_IRET;
1419 unsigned short reg_lret = REG_LRET;
1420 SValue tmp;
1422 switch(op) {
1423 case '/':
1424 case TOK_PDIV:
1425 func = TOK___divdi3;
1426 goto gen_func;
1427 case TOK_UDIV:
1428 func = TOK___udivdi3;
1429 goto gen_func;
1430 case '%':
1431 func = TOK___moddi3;
1432 goto gen_mod_func;
1433 case TOK_UMOD:
1434 func = TOK___umoddi3;
1435 gen_mod_func:
1436 #ifdef TCC_ARM_EABI
1437 reg_iret = TREG_R2;
1438 reg_lret = TREG_R3;
1439 #endif
1440 gen_func:
1441 /* call generic long long function */
1442 vpush_global_sym(&func_old_type, func);
1443 vrott(3);
1444 gfunc_call(2);
1445 vpushi(0);
1446 vtop->r = reg_iret;
1447 vtop->r2 = reg_lret;
1448 break;
1449 case '^':
1450 case '&':
1451 case '|':
1452 case '*':
1453 case '+':
1454 case '-':
1455 //pv("gen_opl A",0,2);
1456 t = vtop->type.t;
1457 vswap();
1458 lexpand();
1459 vrotb(3);
1460 lexpand();
1461 /* stack: L1 H1 L2 H2 */
1462 tmp = vtop[0];
1463 vtop[0] = vtop[-3];
1464 vtop[-3] = tmp;
1465 tmp = vtop[-2];
1466 vtop[-2] = vtop[-3];
1467 vtop[-3] = tmp;
1468 vswap();
1469 /* stack: H1 H2 L1 L2 */
1470 //pv("gen_opl B",0,4);
1471 if (op == '*') {
1472 vpushv(vtop - 1);
1473 vpushv(vtop - 1);
1474 gen_op(TOK_UMULL);
1475 lexpand();
1476 /* stack: H1 H2 L1 L2 ML MH */
1477 for(i=0;i<4;i++)
1478 vrotb(6);
1479 /* stack: ML MH H1 H2 L1 L2 */
1480 tmp = vtop[0];
1481 vtop[0] = vtop[-2];
1482 vtop[-2] = tmp;
1483 /* stack: ML MH H1 L2 H2 L1 */
1484 gen_op('*');
1485 vrotb(3);
1486 vrotb(3);
1487 gen_op('*');
1488 /* stack: ML MH M1 M2 */
1489 gen_op('+');
1490 gen_op('+');
1491 } else if (op == '+' || op == '-') {
1492 /* XXX: add non carry method too (for MIPS or alpha) */
1493 if (op == '+')
1494 op1 = TOK_ADDC1;
1495 else
1496 op1 = TOK_SUBC1;
1497 gen_op(op1);
1498 /* stack: H1 H2 (L1 op L2) */
1499 vrotb(3);
1500 vrotb(3);
1501 gen_op(op1 + 1); /* TOK_xxxC2 */
1502 } else {
1503 gen_op(op);
1504 /* stack: H1 H2 (L1 op L2) */
1505 vrotb(3);
1506 vrotb(3);
1507 /* stack: (L1 op L2) H1 H2 */
1508 gen_op(op);
1509 /* stack: (L1 op L2) (H1 op H2) */
1511 /* stack: L H */
1512 lbuild(t);
1513 break;
1514 case TOK_SAR:
1515 case TOK_SHR:
1516 case TOK_SHL:
1517 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1518 t = vtop[-1].type.t;
1519 vswap();
1520 lexpand();
1521 vrotb(3);
1522 /* stack: L H shift */
1523 c = (int)vtop->c.i;
1524 /* constant: simpler */
1525 /* NOTE: all comments are for SHL. the other cases are
1526 done by swaping words */
1527 vpop();
1528 if (op != TOK_SHL)
1529 vswap();
1530 if (c >= 32) {
1531 /* stack: L H */
1532 vpop();
1533 if (c > 32) {
1534 vpushi(c - 32);
1535 gen_op(op);
1537 if (op != TOK_SAR) {
1538 vpushi(0);
1539 } else {
1540 gv_dup();
1541 vpushi(31);
1542 gen_op(TOK_SAR);
1544 vswap();
1545 } else {
1546 vswap();
1547 gv_dup();
1548 /* stack: H L L */
1549 vpushi(c);
1550 gen_op(op);
1551 vswap();
1552 vpushi(32 - c);
1553 if (op == TOK_SHL)
1554 gen_op(TOK_SHR);
1555 else
1556 gen_op(TOK_SHL);
1557 vrotb(3);
1558 /* stack: L L H */
1559 vpushi(c);
1560 if (op == TOK_SHL)
1561 gen_op(TOK_SHL);
1562 else
1563 gen_op(TOK_SHR);
1564 gen_op('|');
1566 if (op != TOK_SHL)
1567 vswap();
1568 lbuild(t);
1569 } else {
1570 /* XXX: should provide a faster fallback on x86 ? */
1571 switch(op) {
1572 case TOK_SAR:
1573 func = TOK___ashrdi3;
1574 goto gen_func;
1575 case TOK_SHR:
1576 func = TOK___lshrdi3;
1577 goto gen_func;
1578 case TOK_SHL:
1579 func = TOK___ashldi3;
1580 goto gen_func;
1583 break;
1584 default:
1585 /* compare operations */
1586 t = vtop->type.t;
1587 vswap();
1588 lexpand();
1589 vrotb(3);
1590 lexpand();
1591 /* stack: L1 H1 L2 H2 */
1592 tmp = vtop[-1];
1593 vtop[-1] = vtop[-2];
1594 vtop[-2] = tmp;
1595 /* stack: L1 L2 H1 H2 */
1596 /* compare high */
1597 op1 = op;
1598 /* when values are equal, we need to compare low words. since
1599 the jump is inverted, we invert the test too. */
1600 if (op1 == TOK_LT)
1601 op1 = TOK_LE;
1602 else if (op1 == TOK_GT)
1603 op1 = TOK_GE;
1604 else if (op1 == TOK_ULT)
1605 op1 = TOK_ULE;
1606 else if (op1 == TOK_UGT)
1607 op1 = TOK_UGE;
1608 a = 0;
1609 b = 0;
1610 gen_op(op1);
1611 if (op == TOK_NE) {
1612 b = gvtst(0, 0);
1613 } else {
1614 a = gvtst(1, 0);
1615 if (op != TOK_EQ) {
1616 /* generate non equal test */
1617 vpushi(TOK_NE);
1618 vtop->r = VT_CMP;
1619 b = gvtst(0, 0);
1622 /* compare low. Always unsigned */
1623 op1 = op;
1624 if (op1 == TOK_LT)
1625 op1 = TOK_ULT;
1626 else if (op1 == TOK_LE)
1627 op1 = TOK_ULE;
1628 else if (op1 == TOK_GT)
1629 op1 = TOK_UGT;
1630 else if (op1 == TOK_GE)
1631 op1 = TOK_UGE;
1632 gen_op(op1);
1633 a = gvtst(1, a);
1634 gsym(b);
1635 vseti(VT_JMPI, a);
1636 break;
1639 #endif
1641 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1643 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1644 return (a ^ b) >> 63 ? -x : x;
1647 static int gen_opic_lt(uint64_t a, uint64_t b)
1649 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1652 /* handle integer constant optimizations and various machine
1653 independent opt */
1654 static void gen_opic(int op)
1656 SValue *v1 = vtop - 1;
1657 SValue *v2 = vtop;
1658 int t1 = v1->type.t & VT_BTYPE;
1659 int t2 = v2->type.t & VT_BTYPE;
1660 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1661 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1662 uint64_t l1 = c1 ? v1->c.i : 0;
1663 uint64_t l2 = c2 ? v2->c.i : 0;
1664 int shm = (t1 == VT_LLONG) ? 63 : 31;
1666 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1667 l1 = ((uint32_t)l1 |
1668 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1669 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1670 l2 = ((uint32_t)l2 |
1671 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1673 if (c1 && c2) {
1674 switch(op) {
1675 case '+': l1 += l2; break;
1676 case '-': l1 -= l2; break;
1677 case '&': l1 &= l2; break;
1678 case '^': l1 ^= l2; break;
1679 case '|': l1 |= l2; break;
1680 case '*': l1 *= l2; break;
1682 case TOK_PDIV:
1683 case '/':
1684 case '%':
1685 case TOK_UDIV:
1686 case TOK_UMOD:
1687 /* if division by zero, generate explicit division */
1688 if (l2 == 0) {
1689 if (const_wanted)
1690 tcc_error("division by zero in constant");
1691 goto general_case;
1693 switch(op) {
1694 default: l1 = gen_opic_sdiv(l1, l2); break;
1695 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1696 case TOK_UDIV: l1 = l1 / l2; break;
1697 case TOK_UMOD: l1 = l1 % l2; break;
1699 break;
1700 case TOK_SHL: l1 <<= (l2 & shm); break;
1701 case TOK_SHR: l1 >>= (l2 & shm); break;
1702 case TOK_SAR:
1703 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1704 break;
1705 /* tests */
1706 case TOK_ULT: l1 = l1 < l2; break;
1707 case TOK_UGE: l1 = l1 >= l2; break;
1708 case TOK_EQ: l1 = l1 == l2; break;
1709 case TOK_NE: l1 = l1 != l2; break;
1710 case TOK_ULE: l1 = l1 <= l2; break;
1711 case TOK_UGT: l1 = l1 > l2; break;
1712 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1713 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1714 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1715 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1716 /* logical */
1717 case TOK_LAND: l1 = l1 && l2; break;
1718 case TOK_LOR: l1 = l1 || l2; break;
1719 default:
1720 goto general_case;
1722 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1723 l1 = ((uint32_t)l1 |
1724 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1725 v1->c.i = l1;
1726 vtop--;
1727 } else {
1728 /* if commutative ops, put c2 as constant */
1729 if (c1 && (op == '+' || op == '&' || op == '^' ||
1730 op == '|' || op == '*')) {
1731 vswap();
1732 c2 = c1; //c = c1, c1 = c2, c2 = c;
1733 l2 = l1; //l = l1, l1 = l2, l2 = l;
1735 if (!const_wanted &&
1736 c1 && ((l1 == 0 &&
1737 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1738 (l1 == -1 && op == TOK_SAR))) {
1739 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1740 vtop--;
1741 } else if (!const_wanted &&
1742 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1743 (l2 == -1 && op == '|') ||
1744 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1745 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1746 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1747 if (l2 == 1)
1748 vtop->c.i = 0;
1749 vswap();
1750 vtop--;
1751 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1752 op == TOK_PDIV) &&
1753 l2 == 1) ||
1754 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1755 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1756 l2 == 0) ||
1757 (op == '&' &&
1758 l2 == -1))) {
1759 /* filter out NOP operations like x*1, x-0, x&-1... */
1760 vtop--;
1761 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1762 /* try to use shifts instead of muls or divs */
1763 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1764 int n = -1;
1765 while (l2) {
1766 l2 >>= 1;
1767 n++;
1769 vtop->c.i = n;
1770 if (op == '*')
1771 op = TOK_SHL;
1772 else if (op == TOK_PDIV)
1773 op = TOK_SAR;
1774 else
1775 op = TOK_SHR;
1777 goto general_case;
1778 } else if (c2 && (op == '+' || op == '-') &&
1779 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1780 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1781 /* symbol + constant case */
1782 if (op == '-')
1783 l2 = -l2;
1784 l2 += vtop[-1].c.i;
1785 /* The backends can't always deal with addends to symbols
1786 larger than +-1<<31. Don't construct such. */
1787 if ((int)l2 != l2)
1788 goto general_case;
1789 vtop--;
1790 vtop->c.i = l2;
1791 } else {
1792 general_case:
1793 /* call low level op generator */
1794 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1795 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1796 gen_opl(op);
1797 else
1798 gen_opi(op);
1803 /* generate a floating point operation with constant propagation */
1804 static void gen_opif(int op)
1806 int c1, c2;
1807 SValue *v1, *v2;
1808 long double f1, f2;
1810 v1 = vtop - 1;
1811 v2 = vtop;
1812 /* currently, we cannot do computations with forward symbols */
1813 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1814 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1815 if (c1 && c2) {
1816 if (v1->type.t == VT_FLOAT) {
1817 f1 = v1->c.f;
1818 f2 = v2->c.f;
1819 } else if (v1->type.t == VT_DOUBLE) {
1820 f1 = v1->c.d;
1821 f2 = v2->c.d;
1822 } else {
1823 f1 = v1->c.ld;
1824 f2 = v2->c.ld;
1827 /* NOTE: we only do constant propagation if finite number (not
1828 NaN or infinity) (ANSI spec) */
1829 if (!ieee_finite(f1) || !ieee_finite(f2))
1830 goto general_case;
1832 switch(op) {
1833 case '+': f1 += f2; break;
1834 case '-': f1 -= f2; break;
1835 case '*': f1 *= f2; break;
1836 case '/':
1837 if (f2 == 0.0) {
1838 if (const_wanted)
1839 tcc_error("division by zero in constant");
1840 goto general_case;
1842 f1 /= f2;
1843 break;
1844 /* XXX: also handles tests ? */
1845 default:
1846 goto general_case;
1848 /* XXX: overflow test ? */
1849 if (v1->type.t == VT_FLOAT) {
1850 v1->c.f = f1;
1851 } else if (v1->type.t == VT_DOUBLE) {
1852 v1->c.d = f1;
1853 } else {
1854 v1->c.ld = f1;
1856 vtop--;
1857 } else {
1858 general_case:
1859 gen_opf(op);
1863 static int pointed_size(CType *type)
1865 int align;
1866 return type_size(pointed_type(type), &align);
1869 static void vla_runtime_pointed_size(CType *type)
1871 int align;
1872 vla_runtime_type_size(pointed_type(type), &align);
1875 static inline int is_null_pointer(SValue *p)
1877 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1878 return 0;
1879 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1880 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1881 ((p->type.t & VT_BTYPE) == VT_PTR &&
1882 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1885 static inline int is_integer_btype(int bt)
1887 return (bt == VT_BYTE || bt == VT_SHORT ||
1888 bt == VT_INT || bt == VT_LLONG);
1891 /* check types for comparison or subtraction of pointers */
1892 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1894 CType *type1, *type2, tmp_type1, tmp_type2;
1895 int bt1, bt2;
1897 /* null pointers are accepted for all comparisons as gcc */
1898 if (is_null_pointer(p1) || is_null_pointer(p2))
1899 return;
1900 type1 = &p1->type;
1901 type2 = &p2->type;
1902 bt1 = type1->t & VT_BTYPE;
1903 bt2 = type2->t & VT_BTYPE;
1904 /* accept comparison between pointer and integer with a warning */
1905 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1906 if (op != TOK_LOR && op != TOK_LAND )
1907 tcc_warning("comparison between pointer and integer");
1908 return;
1911 /* both must be pointers or implicit function pointers */
1912 if (bt1 == VT_PTR) {
1913 type1 = pointed_type(type1);
1914 } else if (bt1 != VT_FUNC)
1915 goto invalid_operands;
1917 if (bt2 == VT_PTR) {
1918 type2 = pointed_type(type2);
1919 } else if (bt2 != VT_FUNC) {
1920 invalid_operands:
1921 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1923 if ((type1->t & VT_BTYPE) == VT_VOID ||
1924 (type2->t & VT_BTYPE) == VT_VOID)
1925 return;
1926 tmp_type1 = *type1;
1927 tmp_type2 = *type2;
1928 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1929 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1930 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1931 /* gcc-like error if '-' is used */
1932 if (op == '-')
1933 goto invalid_operands;
1934 else
1935 tcc_warning("comparison of distinct pointer types lacks a cast");
1939 /* generic gen_op: handles types problems */
1940 ST_FUNC void gen_op(int op)
1942 int u, t1, t2, bt1, bt2, t;
1943 CType type1;
1945 redo:
1946 t1 = vtop[-1].type.t;
1947 t2 = vtop[0].type.t;
1948 bt1 = t1 & VT_BTYPE;
1949 bt2 = t2 & VT_BTYPE;
1951 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1952 tcc_error("operation on a struct");
1953 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
1954 if (bt2 == VT_FUNC) {
1955 mk_pointer(&vtop->type);
1956 gaddrof();
1958 if (bt1 == VT_FUNC) {
1959 vswap();
1960 mk_pointer(&vtop->type);
1961 gaddrof();
1962 vswap();
1964 goto redo;
1965 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1966 /* at least one operand is a pointer */
1967 /* relationnal op: must be both pointers */
1968 if (op >= TOK_ULT && op <= TOK_LOR) {
1969 check_comparison_pointer_types(vtop - 1, vtop, op);
1970 /* pointers are handled are unsigned */
1971 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1972 t = VT_LLONG | VT_UNSIGNED;
1973 #else
1974 t = VT_INT | VT_UNSIGNED;
1975 #endif
1976 goto std_op;
1978 /* if both pointers, then it must be the '-' op */
1979 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1980 if (op != '-')
1981 tcc_error("cannot use pointers here");
1982 check_comparison_pointer_types(vtop - 1, vtop, op);
1983 /* XXX: check that types are compatible */
1984 if (vtop[-1].type.t & VT_VLA) {
1985 vla_runtime_pointed_size(&vtop[-1].type);
1986 } else {
1987 vpushi(pointed_size(&vtop[-1].type));
1989 vrott(3);
1990 gen_opic(op);
1991 /* set to integer type */
1992 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1993 vtop->type.t = VT_LLONG;
1994 #else
1995 vtop->type.t = VT_INT;
1996 #endif
1997 vswap();
1998 gen_op(TOK_PDIV);
1999 } else {
2000 /* exactly one pointer : must be '+' or '-'. */
2001 if (op != '-' && op != '+')
2002 tcc_error("cannot use pointers here");
2003 /* Put pointer as first operand */
2004 if (bt2 == VT_PTR) {
2005 vswap();
2006 t = t1, t1 = t2, t2 = t;
2008 #if PTR_SIZE == 4
2009 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2010 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2011 gen_cast(&int_type);
2012 #endif
2013 type1 = vtop[-1].type;
2014 type1.t &= ~VT_ARRAY;
2015 if (vtop[-1].type.t & VT_VLA)
2016 vla_runtime_pointed_size(&vtop[-1].type);
2017 else {
2018 u = pointed_size(&vtop[-1].type);
2019 if (u < 0)
2020 tcc_error("unknown array element size");
2021 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2022 vpushll(u);
2023 #else
2024 /* XXX: cast to int ? (long long case) */
2025 vpushi(u);
2026 #endif
2028 gen_op('*');
2029 #if 0
2030 /* #ifdef CONFIG_TCC_BCHECK
2031 The main reason to removing this code:
2032 #include <stdio.h>
2033 int main ()
2035 int v[10];
2036 int i = 10;
2037 int j = 9;
2038 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2039 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2041 When this code is on. then the output looks like
2042 v+i-j = 0xfffffffe
2043 v+(i-j) = 0xbff84000
2045 /* if evaluating constant expression, no code should be
2046 generated, so no bound check */
2047 if (tcc_state->do_bounds_check && !const_wanted) {
2048 /* if bounded pointers, we generate a special code to
2049 test bounds */
2050 if (op == '-') {
2051 vpushi(0);
2052 vswap();
2053 gen_op('-');
2055 gen_bounded_ptr_add();
2056 } else
2057 #endif
2059 gen_opic(op);
2061 /* put again type if gen_opic() swaped operands */
2062 vtop->type = type1;
2064 } else if (is_float(bt1) || is_float(bt2)) {
2065 /* compute bigger type and do implicit casts */
2066 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2067 t = VT_LDOUBLE;
2068 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2069 t = VT_DOUBLE;
2070 } else {
2071 t = VT_FLOAT;
2073 /* floats can only be used for a few operations */
2074 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2075 (op < TOK_ULT || op > TOK_GT))
2076 tcc_error("invalid operands for binary operation");
2077 goto std_op;
2078 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2079 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2080 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
2081 t |= VT_UNSIGNED;
2082 goto std_op;
2083 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2084 /* cast to biggest op */
2085 t = VT_LLONG;
2086 /* convert to unsigned if it does not fit in a long long */
2087 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
2088 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
2089 t |= VT_UNSIGNED;
2090 goto std_op;
2091 } else {
2092 /* integer operations */
2093 t = VT_INT;
2094 /* convert to unsigned if it does not fit in an integer */
2095 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
2096 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
2097 t |= VT_UNSIGNED;
2098 std_op:
2099 /* XXX: currently, some unsigned operations are explicit, so
2100 we modify them here */
2101 if (t & VT_UNSIGNED) {
2102 if (op == TOK_SAR)
2103 op = TOK_SHR;
2104 else if (op == '/')
2105 op = TOK_UDIV;
2106 else if (op == '%')
2107 op = TOK_UMOD;
2108 else if (op == TOK_LT)
2109 op = TOK_ULT;
2110 else if (op == TOK_GT)
2111 op = TOK_UGT;
2112 else if (op == TOK_LE)
2113 op = TOK_ULE;
2114 else if (op == TOK_GE)
2115 op = TOK_UGE;
2117 vswap();
2118 type1.t = t;
2119 gen_cast(&type1);
2120 vswap();
2121 /* special case for shifts and long long: we keep the shift as
2122 an integer */
2123 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2124 type1.t = VT_INT;
2125 gen_cast(&type1);
2126 if (is_float(t))
2127 gen_opif(op);
2128 else
2129 gen_opic(op);
2130 if (op >= TOK_ULT && op <= TOK_GT) {
2131 /* relationnal op: the result is an int */
2132 vtop->type.t = VT_INT;
2133 } else {
2134 vtop->type.t = t;
2137 // Make sure that we have converted to an rvalue:
2138 if (vtop->r & VT_LVAL)
2139 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2142 #ifndef TCC_TARGET_ARM
2143 /* generic itof for unsigned long long case */
2144 static void gen_cvt_itof1(int t)
2146 #ifdef TCC_TARGET_ARM64
2147 gen_cvt_itof(t);
2148 #else
2149 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2150 (VT_LLONG | VT_UNSIGNED)) {
2152 if (t == VT_FLOAT)
2153 vpush_global_sym(&func_old_type, TOK___floatundisf);
2154 #if LDOUBLE_SIZE != 8
2155 else if (t == VT_LDOUBLE)
2156 vpush_global_sym(&func_old_type, TOK___floatundixf);
2157 #endif
2158 else
2159 vpush_global_sym(&func_old_type, TOK___floatundidf);
2160 vrott(2);
2161 gfunc_call(1);
2162 vpushi(0);
2163 vtop->r = reg_fret(t);
2164 } else {
2165 gen_cvt_itof(t);
2167 #endif
2169 #endif
2171 /* generic ftoi for unsigned long long case */
2172 static void gen_cvt_ftoi1(int t)
2174 #ifdef TCC_TARGET_ARM64
2175 gen_cvt_ftoi(t);
2176 #else
2177 int st;
2179 if (t == (VT_LLONG | VT_UNSIGNED)) {
2180 /* not handled natively */
2181 st = vtop->type.t & VT_BTYPE;
2182 if (st == VT_FLOAT)
2183 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2184 #if LDOUBLE_SIZE != 8
2185 else if (st == VT_LDOUBLE)
2186 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2187 #endif
2188 else
2189 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2190 vrott(2);
2191 gfunc_call(1);
2192 vpushi(0);
2193 vtop->r = REG_IRET;
2194 vtop->r2 = REG_LRET;
2195 } else {
2196 gen_cvt_ftoi(t);
2198 #endif
2201 /* force char or short cast */
2202 static void force_charshort_cast(int t)
2204 int bits, dbt;
2205 dbt = t & VT_BTYPE;
2206 /* XXX: add optimization if lvalue : just change type and offset */
2207 if (dbt == VT_BYTE)
2208 bits = 8;
2209 else
2210 bits = 16;
2211 if (t & VT_UNSIGNED) {
2212 vpushi((1 << bits) - 1);
2213 gen_op('&');
2214 } else {
2215 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2216 bits = 64 - bits;
2217 else
2218 bits = 32 - bits;
2219 vpushi(bits);
2220 gen_op(TOK_SHL);
2221 /* result must be signed or the SAR is converted to an SHL
2222 This was not the case when "t" was a signed short
2223 and the last value on the stack was an unsigned int */
2224 vtop->type.t &= ~VT_UNSIGNED;
2225 vpushi(bits);
2226 gen_op(TOK_SAR);
2230 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2231 static void gen_cast(CType *type)
2233 int sbt, dbt, sf, df, c, p;
2235 /* special delayed cast for char/short */
2236 /* XXX: in some cases (multiple cascaded casts), it may still
2237 be incorrect */
2238 if (vtop->r & VT_MUSTCAST) {
2239 vtop->r &= ~VT_MUSTCAST;
2240 force_charshort_cast(vtop->type.t);
2243 /* bitfields first get cast to ints */
2244 if (vtop->type.t & VT_BITFIELD) {
2245 gv(RC_INT);
2248 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2249 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2251 if (sbt != dbt) {
2252 sf = is_float(sbt);
2253 df = is_float(dbt);
2254 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2255 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2256 if (c) {
2257 /* constant case: we can do it now */
2258 /* XXX: in ISOC, cannot do it if error in convert */
2259 if (sbt == VT_FLOAT)
2260 vtop->c.ld = vtop->c.f;
2261 else if (sbt == VT_DOUBLE)
2262 vtop->c.ld = vtop->c.d;
2264 if (df) {
2265 if ((sbt & VT_BTYPE) == VT_LLONG) {
2266 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2267 vtop->c.ld = vtop->c.i;
2268 else
2269 vtop->c.ld = -(long double)-vtop->c.i;
2270 } else if(!sf) {
2271 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2272 vtop->c.ld = (uint32_t)vtop->c.i;
2273 else
2274 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2277 if (dbt == VT_FLOAT)
2278 vtop->c.f = (float)vtop->c.ld;
2279 else if (dbt == VT_DOUBLE)
2280 vtop->c.d = (double)vtop->c.ld;
2281 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2282 vtop->c.i = vtop->c.ld;
2283 } else if (sf && dbt == VT_BOOL) {
2284 vtop->c.i = (vtop->c.ld != 0);
2285 } else {
2286 if(sf)
2287 vtop->c.i = vtop->c.ld;
2288 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2290 else if (sbt & VT_UNSIGNED)
2291 vtop->c.i = (uint32_t)vtop->c.i;
2292 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2293 else if (sbt == VT_PTR)
2295 #endif
2296 else if (sbt != VT_LLONG)
2297 vtop->c.i = ((uint32_t)vtop->c.i |
2298 -(vtop->c.i & 0x80000000));
2300 if (dbt == (VT_LLONG|VT_UNSIGNED))
2302 else if (dbt == VT_BOOL)
2303 vtop->c.i = (vtop->c.i != 0);
2304 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2305 else if (dbt == VT_PTR)
2307 #endif
2308 else if (dbt != VT_LLONG) {
2309 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2310 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2311 0xffffffff);
2312 vtop->c.i &= m;
2313 if (!(dbt & VT_UNSIGNED))
2314 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2317 } else if (p && dbt == VT_BOOL) {
2318 vtop->r = VT_CONST;
2319 vtop->c.i = 1;
2320 } else {
2321 /* non constant case: generate code */
2322 if (sf && df) {
2323 /* convert from fp to fp */
2324 gen_cvt_ftof(dbt);
2325 } else if (df) {
2326 /* convert int to fp */
2327 gen_cvt_itof1(dbt);
2328 } else if (sf) {
2329 /* convert fp to int */
2330 if (dbt == VT_BOOL) {
2331 vpushi(0);
2332 gen_op(TOK_NE);
2333 } else {
2334 if (sbt == VT_FLOAT) {
2335 /* cast to DOUBLE to avoid precision loss */
2336 gen_cvt_ftof(VT_DOUBLE);
2337 vtop->type.t = (vtop->type.t & ~VT_BTYPE) | VT_DOUBLE;
2339 /* we handle char/short/etc... with generic code */
2340 if (dbt != (VT_INT | VT_UNSIGNED) &&
2341 dbt != (VT_LLONG | VT_UNSIGNED) &&
2342 dbt != VT_LLONG)
2343 dbt = VT_INT;
2344 gen_cvt_ftoi1(dbt);
2345 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2346 /* additional cast for char/short... */
2347 vtop->type.t = dbt;
2348 gen_cast(type);
2351 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2352 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2353 if ((sbt & VT_BTYPE) != VT_LLONG) {
2354 /* scalar to long long */
2355 /* machine independent conversion */
2356 gv(RC_INT);
2357 /* generate high word */
2358 if (sbt == (VT_INT | VT_UNSIGNED)) {
2359 vpushi(0);
2360 gv(RC_INT);
2361 } else {
2362 if (sbt == VT_PTR) {
2363 /* cast from pointer to int before we apply
2364 shift operation, which pointers don't support*/
2365 gen_cast(&int_type);
2367 gv_dup();
2368 vpushi(31);
2369 gen_op(TOK_SAR);
2371 /* patch second register */
2372 vtop[-1].r2 = vtop->r;
2373 vpop();
2375 #else
2376 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2377 (dbt & VT_BTYPE) == VT_PTR ||
2378 (dbt & VT_BTYPE) == VT_FUNC) {
2379 if ((sbt & VT_BTYPE) != VT_LLONG &&
2380 (sbt & VT_BTYPE) != VT_PTR &&
2381 (sbt & VT_BTYPE) != VT_FUNC) {
2382 /* need to convert from 32bit to 64bit */
2383 gv(RC_INT);
2384 if (sbt != (VT_INT | VT_UNSIGNED)) {
2385 #if defined(TCC_TARGET_ARM64)
2386 gen_cvt_sxtw();
2387 #elif defined(TCC_TARGET_X86_64)
2388 int r = gv(RC_INT);
2389 /* x86_64 specific: movslq */
2390 o(0x6348);
2391 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2392 #else
2393 #error
2394 #endif
2397 #endif
2398 } else if (dbt == VT_BOOL) {
2399 /* scalar to bool */
2400 vpushi(0);
2401 gen_op(TOK_NE);
2402 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2403 (dbt & VT_BTYPE) == VT_SHORT) {
2404 if (sbt == VT_PTR) {
2405 vtop->type.t = VT_INT;
2406 tcc_warning("nonportable conversion from pointer to char/short");
2408 force_charshort_cast(dbt);
2409 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2410 } else if ((dbt & VT_BTYPE) == VT_INT) {
2411 /* scalar to int */
2412 if ((sbt & VT_BTYPE) == VT_LLONG) {
2413 /* from long long: just take low order word */
2414 lexpand();
2415 vpop();
2417 /* if lvalue and single word type, nothing to do because
2418 the lvalue already contains the real type size (see
2419 VT_LVAL_xxx constants) */
2420 #endif
2423 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2424 /* if we are casting between pointer types,
2425 we must update the VT_LVAL_xxx size */
2426 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2427 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2429 vtop->type = *type;
2432 /* return type size as known at compile time. Put alignment at 'a' */
2433 ST_FUNC int type_size(CType *type, int *a)
2435 Sym *s;
2436 int bt;
2438 bt = type->t & VT_BTYPE;
2439 if (bt == VT_STRUCT) {
2440 /* struct/union */
2441 s = type->ref;
2442 *a = s->r;
2443 return s->c;
2444 } else if (bt == VT_PTR) {
2445 if (type->t & VT_ARRAY) {
2446 int ts;
2448 s = type->ref;
2449 ts = type_size(&s->type, a);
2451 if (ts < 0 && s->c < 0)
2452 ts = -ts;
2454 return ts * s->c;
2455 } else {
2456 *a = PTR_SIZE;
2457 return PTR_SIZE;
2459 } else if (bt == VT_LDOUBLE) {
2460 *a = LDOUBLE_ALIGN;
2461 return LDOUBLE_SIZE;
2462 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2463 #ifdef TCC_TARGET_I386
2464 #ifdef TCC_TARGET_PE
2465 *a = 8;
2466 #else
2467 *a = 4;
2468 #endif
2469 #elif defined(TCC_TARGET_ARM)
2470 #ifdef TCC_ARM_EABI
2471 *a = 8;
2472 #else
2473 *a = 4;
2474 #endif
2475 #else
2476 *a = 8;
2477 #endif
2478 return 8;
2479 } else if (bt == VT_INT || bt == VT_FLOAT) {
2480 *a = 4;
2481 return 4;
2482 } else if (bt == VT_SHORT) {
2483 *a = 2;
2484 return 2;
2485 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2486 *a = 8;
2487 return 16;
2488 } else if (bt == VT_ENUM) {
2489 *a = 4;
2490 /* Enums might be incomplete, so don't just return '4' here. */
2491 return type->ref->c;
2492 } else {
2493 /* char, void, function, _Bool */
2494 *a = 1;
2495 return 1;
2499 /* push type size as known at runtime time on top of value stack. Put
2500 alignment at 'a' */
2501 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2503 if (type->t & VT_VLA) {
2504 type_size(&type->ref->type, a);
2505 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2506 } else {
2507 vpushi(type_size(type, a));
2511 static void vla_sp_restore(void) {
2512 if (vlas_in_scope) {
2513 gen_vla_sp_restore(vla_sp_loc);
2517 static void vla_sp_restore_root(void) {
2518 if (vlas_in_scope) {
2519 gen_vla_sp_restore(vla_sp_root_loc);
2523 /* return the pointed type of t */
2524 static inline CType *pointed_type(CType *type)
2526 return &type->ref->type;
2529 /* modify type so that its it is a pointer to type. */
2530 ST_FUNC void mk_pointer(CType *type)
2532 Sym *s;
2533 s = sym_push(SYM_FIELD, type, 0, -1);
2534 type->t = VT_PTR | (type->t & ~VT_TYPE);
2535 type->ref = s;
2538 /* compare function types. OLD functions match any new functions */
2539 static int is_compatible_func(CType *type1, CType *type2)
2541 Sym *s1, *s2;
2543 s1 = type1->ref;
2544 s2 = type2->ref;
2545 if (!is_compatible_types(&s1->type, &s2->type))
2546 return 0;
2547 /* check func_call */
2548 if (s1->a.func_call != s2->a.func_call)
2549 return 0;
2550 /* XXX: not complete */
2551 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2552 return 1;
2553 if (s1->c != s2->c)
2554 return 0;
2555 while (s1 != NULL) {
2556 if (s2 == NULL)
2557 return 0;
2558 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2559 return 0;
2560 s1 = s1->next;
2561 s2 = s2->next;
2563 if (s2)
2564 return 0;
2565 return 1;
2568 /* return true if type1 and type2 are the same. If unqualified is
2569 true, qualifiers on the types are ignored.
2571 - enums are not checked as gcc __builtin_types_compatible_p ()
2573 static int compare_types(CType *type1, CType *type2, int unqualified)
2575 int bt1, t1, t2;
2577 t1 = type1->t & VT_TYPE;
2578 t2 = type2->t & VT_TYPE;
2579 if (unqualified) {
2580 /* strip qualifiers before comparing */
2581 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2582 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2584 /* Default Vs explicit signedness only matters for char */
2585 if ((t1 & VT_BTYPE) != VT_BYTE) {
2586 t1 &= ~VT_DEFSIGN;
2587 t2 &= ~VT_DEFSIGN;
2589 /* An enum is compatible with (unsigned) int. Ideally we would
2590 store the enums signedness in type->ref.a.<some_bit> and
2591 only accept unsigned enums with unsigned int and vice versa.
2592 But one of our callers (gen_assign_cast) always strips VT_UNSIGNED
2593 from pointer target types, so we can't add it here either. */
2594 if ((t1 & VT_BTYPE) == VT_ENUM) {
2595 t1 = VT_INT;
2596 if (type1->ref->a.unsigned_enum)
2597 t1 |= VT_UNSIGNED;
2599 if ((t2 & VT_BTYPE) == VT_ENUM) {
2600 t2 = VT_INT;
2601 if (type2->ref->a.unsigned_enum)
2602 t2 |= VT_UNSIGNED;
2604 /* XXX: bitfields ? */
2605 if (t1 != t2)
2606 return 0;
2607 /* test more complicated cases */
2608 bt1 = t1 & VT_BTYPE;
2609 if (bt1 == VT_PTR) {
2610 type1 = pointed_type(type1);
2611 type2 = pointed_type(type2);
2612 return is_compatible_types(type1, type2);
2613 } else if (bt1 == VT_STRUCT) {
2614 return (type1->ref == type2->ref);
2615 } else if (bt1 == VT_FUNC) {
2616 return is_compatible_func(type1, type2);
2617 } else {
2618 return 1;
2622 /* return true if type1 and type2 are exactly the same (including
2623 qualifiers).
2625 static int is_compatible_types(CType *type1, CType *type2)
2627 return compare_types(type1,type2,0);
2630 /* return true if type1 and type2 are the same (ignoring qualifiers).
2632 static int is_compatible_parameter_types(CType *type1, CType *type2)
2634 return compare_types(type1,type2,1);
2637 /* print a type. If 'varstr' is not NULL, then the variable is also
2638 printed in the type */
2639 /* XXX: union */
2640 /* XXX: add array and function pointers */
2641 static void type_to_str(char *buf, int buf_size,
2642 CType *type, const char *varstr)
2644 int bt, v, t;
2645 Sym *s, *sa;
2646 char buf1[256];
2647 const char *tstr;
2649 t = type->t & VT_TYPE;
2650 bt = t & VT_BTYPE;
2651 buf[0] = '\0';
2652 if (t & VT_CONSTANT)
2653 pstrcat(buf, buf_size, "const ");
2654 if (t & VT_VOLATILE)
2655 pstrcat(buf, buf_size, "volatile ");
2656 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2657 pstrcat(buf, buf_size, "unsigned ");
2658 else if (t & VT_DEFSIGN)
2659 pstrcat(buf, buf_size, "signed ");
2660 switch(bt) {
2661 case VT_VOID:
2662 tstr = "void";
2663 goto add_tstr;
2664 case VT_BOOL:
2665 tstr = "_Bool";
2666 goto add_tstr;
2667 case VT_BYTE:
2668 tstr = "char";
2669 goto add_tstr;
2670 case VT_SHORT:
2671 tstr = "short";
2672 goto add_tstr;
2673 case VT_INT:
2674 tstr = "int";
2675 goto add_tstr;
2676 case VT_LONG:
2677 tstr = "long";
2678 goto add_tstr;
2679 case VT_LLONG:
2680 tstr = "long long";
2681 goto add_tstr;
2682 case VT_FLOAT:
2683 tstr = "float";
2684 goto add_tstr;
2685 case VT_DOUBLE:
2686 tstr = "double";
2687 goto add_tstr;
2688 case VT_LDOUBLE:
2689 tstr = "long double";
2690 add_tstr:
2691 pstrcat(buf, buf_size, tstr);
2692 break;
2693 case VT_ENUM:
2694 case VT_STRUCT:
2695 if (bt == VT_STRUCT)
2696 tstr = "struct ";
2697 else
2698 tstr = "enum ";
2699 pstrcat(buf, buf_size, tstr);
2700 v = type->ref->v & ~SYM_STRUCT;
2701 if (v >= SYM_FIRST_ANOM)
2702 pstrcat(buf, buf_size, "<anonymous>");
2703 else
2704 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2705 break;
2706 case VT_FUNC:
2707 s = type->ref;
2708 type_to_str(buf, buf_size, &s->type, varstr);
2709 pstrcat(buf, buf_size, "(");
2710 sa = s->next;
2711 while (sa != NULL) {
2712 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2713 pstrcat(buf, buf_size, buf1);
2714 sa = sa->next;
2715 if (sa)
2716 pstrcat(buf, buf_size, ", ");
2718 pstrcat(buf, buf_size, ")");
2719 goto no_var;
2720 case VT_PTR:
2721 s = type->ref;
2722 if (t & VT_ARRAY) {
2723 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2724 type_to_str(buf, buf_size, &s->type, buf1);
2725 goto no_var;
2727 pstrcpy(buf1, sizeof(buf1), "*");
2728 if (t & VT_CONSTANT)
2729 pstrcat(buf1, buf_size, "const ");
2730 if (t & VT_VOLATILE)
2731 pstrcat(buf1, buf_size, "volatile ");
2732 if (varstr)
2733 pstrcat(buf1, sizeof(buf1), varstr);
2734 type_to_str(buf, buf_size, &s->type, buf1);
2735 goto no_var;
2737 if (varstr) {
2738 pstrcat(buf, buf_size, " ");
2739 pstrcat(buf, buf_size, varstr);
2741 no_var: ;
2744 /* verify type compatibility to store vtop in 'dt' type, and generate
2745 casts if needed. */
2746 static void gen_assign_cast(CType *dt)
2748 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2749 char buf1[256], buf2[256];
2750 int dbt, sbt;
2752 st = &vtop->type; /* source type */
2753 dbt = dt->t & VT_BTYPE;
2754 sbt = st->t & VT_BTYPE;
2755 if (sbt == VT_VOID || dbt == VT_VOID) {
2756 if (sbt == VT_VOID && dbt == VT_VOID)
2757 ; /*
2758 It is Ok if both are void
2759 A test program:
2760 void func1() {}
2761 void func2() {
2762 return func1();
2764 gcc accepts this program
2766 else
2767 tcc_error("cannot cast from/to void");
2769 if (dt->t & VT_CONSTANT)
2770 tcc_warning("assignment of read-only location");
2771 switch(dbt) {
2772 case VT_PTR:
2773 /* special cases for pointers */
2774 /* '0' can also be a pointer */
2775 if (is_null_pointer(vtop))
2776 goto type_ok;
2777 /* accept implicit pointer to integer cast with warning */
2778 if (is_integer_btype(sbt)) {
2779 tcc_warning("assignment makes pointer from integer without a cast");
2780 goto type_ok;
2782 type1 = pointed_type(dt);
2783 /* a function is implicitely a function pointer */
2784 if (sbt == VT_FUNC) {
2785 if ((type1->t & VT_BTYPE) != VT_VOID &&
2786 !is_compatible_types(pointed_type(dt), st))
2787 tcc_warning("assignment from incompatible pointer type");
2788 goto type_ok;
2790 if (sbt != VT_PTR)
2791 goto error;
2792 type2 = pointed_type(st);
2793 if ((type1->t & VT_BTYPE) == VT_VOID ||
2794 (type2->t & VT_BTYPE) == VT_VOID) {
2795 /* void * can match anything */
2796 } else {
2797 /* exact type match, except for qualifiers */
2798 tmp_type1 = *type1;
2799 tmp_type2 = *type2;
2800 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2801 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2802 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2803 /* Like GCC don't warn by default for merely changes
2804 in pointer target signedness. Do warn for different
2805 base types, though, in particular for unsigned enums
2806 and signed int targets. */
2807 if ((tmp_type1.t & (VT_DEFSIGN | VT_UNSIGNED)) !=
2808 (tmp_type2.t & (VT_DEFSIGN | VT_UNSIGNED)) &&
2809 (tmp_type1.t & VT_BTYPE) == (tmp_type2.t & VT_BTYPE))
2811 else
2812 tcc_warning("assignment from incompatible pointer type");
2815 /* check const and volatile */
2816 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2817 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2818 tcc_warning("assignment discards qualifiers from pointer target type");
2819 break;
2820 case VT_BYTE:
2821 case VT_SHORT:
2822 case VT_INT:
2823 case VT_LLONG:
2824 if (sbt == VT_PTR || sbt == VT_FUNC) {
2825 tcc_warning("assignment makes integer from pointer without a cast");
2826 } else if (sbt == VT_STRUCT) {
2827 goto case_VT_STRUCT;
2829 /* XXX: more tests */
2830 break;
2831 case VT_STRUCT:
2832 case_VT_STRUCT:
2833 tmp_type1 = *dt;
2834 tmp_type2 = *st;
2835 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2836 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2837 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2838 error:
2839 type_to_str(buf1, sizeof(buf1), st, NULL);
2840 type_to_str(buf2, sizeof(buf2), dt, NULL);
2841 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2843 break;
2845 type_ok:
2846 gen_cast(dt);
2849 /* store vtop in lvalue pushed on stack */
2850 ST_FUNC void vstore(void)
2852 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2854 ft = vtop[-1].type.t;
2855 sbt = vtop->type.t & VT_BTYPE;
2856 dbt = ft & VT_BTYPE;
2857 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2858 (sbt == VT_INT && dbt == VT_SHORT))
2859 && !(vtop->type.t & VT_BITFIELD)) {
2860 /* optimize char/short casts */
2861 delayed_cast = VT_MUSTCAST;
2862 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2863 ((1 << VT_STRUCT_SHIFT) - 1));
2864 /* XXX: factorize */
2865 if (ft & VT_CONSTANT)
2866 tcc_warning("assignment of read-only location");
2867 } else {
2868 delayed_cast = 0;
2869 if (!(ft & VT_BITFIELD))
2870 gen_assign_cast(&vtop[-1].type);
2873 if (sbt == VT_STRUCT) {
2874 /* if structure, only generate pointer */
2875 /* structure assignment : generate memcpy */
2876 /* XXX: optimize if small size */
2877 size = type_size(&vtop->type, &align);
2879 /* destination */
2880 vswap();
2881 vtop->type.t = VT_PTR;
2882 gaddrof();
2884 /* address of memcpy() */
2885 #ifdef TCC_ARM_EABI
2886 if(!(align & 7))
2887 vpush_global_sym(&func_old_type, TOK_memcpy8);
2888 else if(!(align & 3))
2889 vpush_global_sym(&func_old_type, TOK_memcpy4);
2890 else
2891 #endif
2892 /* Use memmove, rather than memcpy, as dest and src may be same: */
2893 vpush_global_sym(&func_old_type, TOK_memmove);
2895 vswap();
2896 /* source */
2897 vpushv(vtop - 2);
2898 vtop->type.t = VT_PTR;
2899 gaddrof();
2900 /* type size */
2901 vpushi(size);
2902 gfunc_call(3);
2904 /* leave source on stack */
2905 } else if (ft & VT_BITFIELD) {
2906 /* bitfield store handling */
2908 /* save lvalue as expression result (example: s.b = s.a = n;) */
2909 vdup(), vtop[-1] = vtop[-2];
2911 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2912 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2913 /* remove bit field info to avoid loops */
2914 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2916 if((ft & VT_BTYPE) == VT_BOOL) {
2917 gen_cast(&vtop[-1].type);
2918 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2921 /* duplicate destination */
2922 vdup();
2923 vtop[-1] = vtop[-2];
2925 /* mask and shift source */
2926 if((ft & VT_BTYPE) != VT_BOOL) {
2927 if((ft & VT_BTYPE) == VT_LLONG) {
2928 vpushll((1ULL << bit_size) - 1ULL);
2929 } else {
2930 vpushi((1 << bit_size) - 1);
2932 gen_op('&');
2934 vpushi(bit_pos);
2935 gen_op(TOK_SHL);
2936 /* load destination, mask and or with source */
2937 vswap();
2938 if((ft & VT_BTYPE) == VT_LLONG) {
2939 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2940 } else {
2941 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2943 gen_op('&');
2944 gen_op('|');
2945 /* store result */
2946 vstore();
2947 /* ... and discard */
2948 vpop();
2950 } else {
2951 #ifdef CONFIG_TCC_BCHECK
2952 /* bound check case */
2953 if (vtop[-1].r & VT_MUSTBOUND) {
2954 vswap();
2955 gbound();
2956 vswap();
2958 #endif
2959 rc = RC_INT;
2960 if (is_float(ft)) {
2961 rc = RC_FLOAT;
2962 #ifdef TCC_TARGET_X86_64
2963 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2964 rc = RC_ST0;
2965 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2966 rc = RC_FRET;
2968 #endif
2970 r = gv(rc); /* generate value */
2971 /* if lvalue was saved on stack, must read it */
2972 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2973 SValue sv;
2974 t = get_reg(RC_INT);
2975 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2976 sv.type.t = VT_PTR;
2977 #else
2978 sv.type.t = VT_INT;
2979 #endif
2980 sv.r = VT_LOCAL | VT_LVAL;
2981 sv.c.i = vtop[-1].c.i;
2982 load(t, &sv);
2983 vtop[-1].r = t | VT_LVAL;
2985 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2986 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2987 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2988 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2989 #else
2990 if ((ft & VT_BTYPE) == VT_LLONG) {
2991 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2992 #endif
2993 vtop[-1].type.t = load_type;
2994 store(r, vtop - 1);
2995 vswap();
2996 /* convert to int to increment easily */
2997 vtop->type.t = addr_type;
2998 gaddrof();
2999 vpushi(load_size);
3000 gen_op('+');
3001 vtop->r |= VT_LVAL;
3002 vswap();
3003 vtop[-1].type.t = load_type;
3004 /* XXX: it works because r2 is spilled last ! */
3005 store(vtop->r2, vtop - 1);
3006 } else {
3007 store(r, vtop - 1);
3010 vswap();
3011 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3012 vtop->r |= delayed_cast;
3016 /* post defines POST/PRE add. c is the token ++ or -- */
3017 ST_FUNC void inc(int post, int c)
3019 test_lvalue();
3020 vdup(); /* save lvalue */
3021 if (post) {
3022 gv_dup(); /* duplicate value */
3023 vrotb(3);
3024 vrotb(3);
3026 /* add constant */
3027 vpushi(c - TOK_MID);
3028 gen_op('+');
3029 vstore(); /* store value */
3030 if (post)
3031 vpop(); /* if post op, return saved value */
3034 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3036 /* read the string */
3037 if (tok != TOK_STR)
3038 expect(msg);
3039 cstr_new(astr);
3040 while (tok == TOK_STR) {
3041 /* XXX: add \0 handling too ? */
3042 cstr_cat(astr, tokc.str.data, -1);
3043 next();
3045 cstr_ccat(astr, '\0');
3048 /* If I is >= 1 and a power of two, returns log2(i)+1.
3049 If I is 0 returns 0. */
3050 static int exact_log2p1(int i)
3052 int ret;
3053 if (!i)
3054 return 0;
3055 for (ret = 1; i >= 1 << 8; ret += 8)
3056 i >>= 8;
3057 if (i >= 1 << 4)
3058 ret += 4, i >>= 4;
3059 if (i >= 1 << 2)
3060 ret += 2, i >>= 2;
3061 if (i >= 1 << 1)
3062 ret++;
3063 return ret;
3066 /* Parse GNUC __attribute__ extension. Currently, the following
3067 extensions are recognized:
3068 - aligned(n) : set data/function alignment.
3069 - packed : force data alignment to 1
3070 - section(x) : generate data/code in this section.
3071 - unused : currently ignored, but may be used someday.
3072 - regparm(n) : pass function parameters in registers (i386 only)
3074 static void parse_attribute(AttributeDef *ad)
3076 int t, n;
3077 CString astr;
3079 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
3080 next();
3081 skip('(');
3082 skip('(');
3083 while (tok != ')') {
3084 if (tok < TOK_IDENT)
3085 expect("attribute name");
3086 t = tok;
3087 next();
3088 switch(t) {
3089 case TOK_SECTION1:
3090 case TOK_SECTION2:
3091 skip('(');
3092 parse_mult_str(&astr, "section name");
3093 ad->section = find_section(tcc_state, (char *)astr.data);
3094 skip(')');
3095 cstr_free(&astr);
3096 break;
3097 case TOK_ALIAS1:
3098 case TOK_ALIAS2:
3099 skip('(');
3100 parse_mult_str(&astr, "alias(\"target\")");
3101 ad->alias_target = /* save string as token, for later */
3102 tok_alloc((char*)astr.data, astr.size-1)->tok;
3103 skip(')');
3104 cstr_free(&astr);
3105 break;
3106 case TOK_VISIBILITY1:
3107 case TOK_VISIBILITY2:
3108 skip('(');
3109 parse_mult_str(&astr,
3110 "visibility(\"default|hidden|internal|protected\")");
3111 if (!strcmp (astr.data, "default"))
3112 ad->a.visibility = STV_DEFAULT;
3113 else if (!strcmp (astr.data, "hidden"))
3114 ad->a.visibility = STV_HIDDEN;
3115 else if (!strcmp (astr.data, "internal"))
3116 ad->a.visibility = STV_INTERNAL;
3117 else if (!strcmp (astr.data, "protected"))
3118 ad->a.visibility = STV_PROTECTED;
3119 else
3120 expect("visibility(\"default|hidden|internal|protected\")");
3121 skip(')');
3122 cstr_free(&astr);
3123 break;
3124 case TOK_ALIGNED1:
3125 case TOK_ALIGNED2:
3126 if (tok == '(') {
3127 next();
3128 n = expr_const();
3129 if (n <= 0 || (n & (n - 1)) != 0)
3130 tcc_error("alignment must be a positive power of two");
3131 skip(')');
3132 } else {
3133 n = MAX_ALIGN;
3135 ad->a.aligned = exact_log2p1(n);
3136 if (n != 1 << (ad->a.aligned - 1))
3137 tcc_error("alignment of %d is larger than implemented", n);
3138 break;
3139 case TOK_PACKED1:
3140 case TOK_PACKED2:
3141 ad->a.packed = 1;
3142 break;
3143 case TOK_WEAK1:
3144 case TOK_WEAK2:
3145 ad->a.weak = 1;
3146 break;
3147 case TOK_UNUSED1:
3148 case TOK_UNUSED2:
3149 /* currently, no need to handle it because tcc does not
3150 track unused objects */
3151 break;
3152 case TOK_NORETURN1:
3153 case TOK_NORETURN2:
3154 /* currently, no need to handle it because tcc does not
3155 track unused objects */
3156 break;
3157 case TOK_CDECL1:
3158 case TOK_CDECL2:
3159 case TOK_CDECL3:
3160 ad->a.func_call = FUNC_CDECL;
3161 break;
3162 case TOK_STDCALL1:
3163 case TOK_STDCALL2:
3164 case TOK_STDCALL3:
3165 ad->a.func_call = FUNC_STDCALL;
3166 break;
3167 #ifdef TCC_TARGET_I386
3168 case TOK_REGPARM1:
3169 case TOK_REGPARM2:
3170 skip('(');
3171 n = expr_const();
3172 if (n > 3)
3173 n = 3;
3174 else if (n < 0)
3175 n = 0;
3176 if (n > 0)
3177 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
3178 skip(')');
3179 break;
3180 case TOK_FASTCALL1:
3181 case TOK_FASTCALL2:
3182 case TOK_FASTCALL3:
3183 ad->a.func_call = FUNC_FASTCALLW;
3184 break;
3185 #endif
3186 case TOK_MODE:
3187 skip('(');
3188 switch(tok) {
3189 case TOK_MODE_DI:
3190 ad->a.mode = VT_LLONG + 1;
3191 break;
3192 case TOK_MODE_QI:
3193 ad->a.mode = VT_BYTE + 1;
3194 break;
3195 case TOK_MODE_HI:
3196 ad->a.mode = VT_SHORT + 1;
3197 break;
3198 case TOK_MODE_SI:
3199 case TOK_MODE_word:
3200 ad->a.mode = VT_INT + 1;
3201 break;
3202 default:
3203 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3204 break;
3206 next();
3207 skip(')');
3208 break;
3209 case TOK_DLLEXPORT:
3210 ad->a.func_export = 1;
3211 break;
3212 case TOK_DLLIMPORT:
3213 ad->a.func_import = 1;
3214 break;
3215 default:
3216 if (tcc_state->warn_unsupported)
3217 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3218 /* skip parameters */
3219 if (tok == '(') {
3220 int parenthesis = 0;
3221 do {
3222 if (tok == '(')
3223 parenthesis++;
3224 else if (tok == ')')
3225 parenthesis--;
3226 next();
3227 } while (parenthesis && tok != -1);
3229 break;
3231 if (tok != ',')
3232 break;
3233 next();
3235 skip(')');
3236 skip(')');
3240 static Sym * find_field (CType *type, int v)
3242 Sym *s = type->ref;
3243 v |= SYM_FIELD;
3244 while ((s = s->next) != NULL) {
3245 if ((s->v & SYM_FIELD) &&
3246 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3247 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3248 Sym *ret = find_field (&s->type, v);
3249 if (ret)
3250 return ret;
3252 if (s->v == v)
3253 break;
3255 return s;
3258 static void struct_add_offset (Sym *s, int offset)
3260 while ((s = s->next) != NULL) {
3261 if ((s->v & SYM_FIELD) &&
3262 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3263 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3264 struct_add_offset(s->type.ref, offset);
3265 } else
3266 s->c += offset;
3270 static void struct_layout(CType *type, AttributeDef *ad)
3272 int align, maxalign, offset, c, bit_pos, bt, prevbt, prev_bit_size;
3273 int pcc = !tcc_state->ms_bitfields;
3274 Sym *f;
3275 if (ad->a.aligned)
3276 maxalign = 1 << (ad->a.aligned - 1);
3277 else
3278 maxalign = 1;
3279 offset = 0;
3280 c = 0;
3281 bit_pos = 0;
3282 prevbt = VT_STRUCT; /* make it never match */
3283 prev_bit_size = 0;
3284 for (f = type->ref->next; f; f = f->next) {
3285 int typealign, bit_size;
3286 int size = type_size(&f->type, &typealign);
3287 if (f->type.t & VT_BITFIELD)
3288 bit_size = (f->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
3289 else
3290 bit_size = -1;
3291 if (bit_size == 0 && pcc) {
3292 /* Zero-width bit-fields in PCC mode aren't affected
3293 by any packing (attribute or pragma). */
3294 align = typealign;
3295 } else if (f->r > 1) {
3296 align = f->r;
3297 } else if (ad->a.packed || f->r == 1) {
3298 align = 1;
3299 /* Packed fields or packed records don't let the base type
3300 influence the records type alignment. */
3301 typealign = 1;
3302 } else {
3303 align = typealign;
3305 if (type->ref->type.t != TOK_STRUCT) {
3306 if (pcc && bit_size >= 0)
3307 size = (bit_size + 7) >> 3;
3308 /* Bit position is already zero from our caller. */
3309 offset = 0;
3310 if (size > c)
3311 c = size;
3312 } else if (bit_size < 0) {
3313 int addbytes = pcc ? (bit_pos + 7) >> 3 : 0;
3314 prevbt = VT_STRUCT;
3315 prev_bit_size = 0;
3316 c = (c + addbytes + align - 1) & -align;
3317 offset = c;
3318 if (size > 0)
3319 c += size;
3320 bit_pos = 0;
3321 } else {
3322 /* A bit-field. Layout is more complicated. There are two
3323 options TCC implements: PCC compatible and MS compatible
3324 (PCC compatible is what GCC uses for almost all targets).
3325 In PCC layout the overall size of the struct (in c) is
3326 _excluding_ the current run of bit-fields (that is,
3327 there's at least additional bit_pos bits after c). In
3328 MS layout c does include the current run of bit-fields.
3330 This matters for calculating the natural alignment buckets
3331 in PCC mode. */
3333 /* 'align' will be used to influence records alignment,
3334 so it's the max of specified and type alignment, except
3335 in certain cases that depend on the mode. */
3336 if (align < typealign)
3337 align = typealign;
3338 if (pcc) {
3339 /* In PCC layout a non-packed bit-field is placed adjacent
3340 to the preceding bit-fields, except if it would overflow
3341 its container (depending on base type) or it's a zero-width
3342 bit-field. Packed non-zero-width bit-fields always are
3343 placed adjacent. */
3344 int ofs = (c * 8 + bit_pos) % (typealign * 8);
3345 int ofs2 = ofs + bit_size + (typealign * 8) - 1;
3346 if (bit_size == 0 ||
3347 (typealign != 1 &&
3348 (ofs2 / (typealign * 8)) > (size/typealign))) {
3349 c = (c + ((bit_pos + 7) >> 3) + typealign - 1) & -typealign;
3350 bit_pos = 0;
3352 offset = c;
3353 /* In PCC layout named bit-fields influence the alignment
3354 of the containing struct using the base types alignment,
3355 except for packed fields (which here have correct
3356 align/typealign). */
3357 if ((f->v & SYM_FIRST_ANOM))
3358 align = 1;
3359 } else {
3360 bt = f->type.t & VT_BTYPE;
3361 if ((bit_pos + bit_size > size * 8) ||
3362 (bit_size > 0) == (bt != prevbt)) {
3363 c = (c + typealign - 1) & -typealign;
3364 offset = c;
3365 bit_pos = 0;
3366 /* In MS bitfield mode a bit-field run always uses
3367 at least as many bits as the underlying type.
3368 To start a new run it's also required that this
3369 or the last bit-field had non-zero width. */
3370 if (bit_size || prev_bit_size)
3371 c += size;
3373 /* In MS layout the records alignment is normally
3374 influenced by the field, except for a zero-width
3375 field at the start of a run (but by further zero-width
3376 fields it is again). */
3377 if (bit_size == 0 && prevbt != bt)
3378 align = 1;
3379 prevbt = bt;
3380 prev_bit_size = bit_size;
3382 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3383 | (bit_pos << VT_STRUCT_SHIFT);
3384 bit_pos += bit_size;
3385 if (pcc && bit_pos >= size * 8) {
3386 c += size;
3387 bit_pos -= size * 8;
3390 if (align > maxalign)
3391 maxalign = align;
3392 #if 0
3393 printf("set field %s offset=%d c=%d",
3394 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, c);
3395 if (f->type.t & VT_BITFIELD) {
3396 printf(" pos=%d size=%d",
3397 (f->type.t >> VT_STRUCT_SHIFT) & 0x3f,
3398 (f->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3400 printf("\n");
3401 #endif
3403 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3404 Sym *ass;
3405 /* An anonymous struct/union. Adjust member offsets
3406 to reflect the real offset of our containing struct.
3407 Also set the offset of this anon member inside
3408 the outer struct to be zero. Via this it
3409 works when accessing the field offset directly
3410 (from base object), as well as when recursing
3411 members in initializer handling. */
3412 int v2 = f->type.ref->v;
3413 if (!(v2 & SYM_FIELD) &&
3414 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3415 Sym **pps;
3416 /* This happens only with MS extensions. The
3417 anon member has a named struct type, so it
3418 potentially is shared with other references.
3419 We need to unshare members so we can modify
3420 them. */
3421 ass = f->type.ref;
3422 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3423 &f->type.ref->type, 0,
3424 f->type.ref->c);
3425 pps = &f->type.ref->next;
3426 while ((ass = ass->next) != NULL) {
3427 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3428 pps = &((*pps)->next);
3430 *pps = NULL;
3432 struct_add_offset(f->type.ref, offset);
3433 f->c = 0;
3434 } else {
3435 f->c = offset;
3438 f->r = 0;
3440 /* store size and alignment */
3441 type->ref->c = (c + (pcc ? (bit_pos + 7) >> 3 : 0)
3442 + maxalign - 1) & -maxalign;
3443 type->ref->r = maxalign;
3446 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
3447 static void struct_decl(CType *type, AttributeDef *ad, int u)
3449 int a, v, size, align, flexible, alignoverride;
3450 long c;
3451 int bit_size, bsize, bt;
3452 Sym *s, *ss, **ps;
3453 AttributeDef ad1;
3454 CType type1, btype;
3456 a = tok; /* save decl type */
3457 next();
3458 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3459 parse_attribute(ad);
3460 if (tok != '{') {
3461 v = tok;
3462 next();
3463 /* struct already defined ? return it */
3464 if (v < TOK_IDENT)
3465 expect("struct/union/enum name");
3466 s = struct_find(v);
3467 if (s && (s->scope == local_scope || (tok != '{' && tok != ';'))) {
3468 if (s->type.t != a)
3469 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3470 goto do_decl;
3472 } else {
3473 v = anon_sym++;
3475 /* Record the original enum/struct/union token. */
3476 type1.t = a;
3477 type1.ref = NULL;
3478 /* we put an undefined size for struct/union */
3479 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3480 s->r = 0; /* default alignment is zero as gcc */
3481 /* put struct/union/enum name in type */
3482 do_decl:
3483 type->t = u;
3484 type->ref = s;
3486 if (tok == '{') {
3487 next();
3488 if (s->c != -1)
3489 tcc_error("struct/union/enum already defined");
3490 /* cannot be empty */
3491 c = 0;
3492 /* non empty enums are not allowed */
3493 if (a == TOK_ENUM) {
3494 int seen_neg = 0;
3495 int seen_wide = 0;
3496 for(;;) {
3497 CType *t = &int_type;
3498 v = tok;
3499 if (v < TOK_UIDENT)
3500 expect("identifier");
3501 ss = sym_find(v);
3502 if (ss && !local_stack)
3503 tcc_error("redefinition of enumerator '%s'",
3504 get_tok_str(v, NULL));
3505 next();
3506 if (tok == '=') {
3507 next();
3508 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
3509 c = expr_const64();
3510 #else
3511 /* We really want to support long long enums
3512 on i386 as well, but the Sym structure only
3513 holds a 'long' for associated constants,
3514 and enlarging it would bump its size (no
3515 available padding). So punt for now. */
3516 c = expr_const();
3517 #endif
3519 if (c < 0)
3520 seen_neg = 1;
3521 if (c != (int)c && (unsigned long)c != (unsigned int)c)
3522 seen_wide = 1, t = &size_type;
3523 /* enum symbols have static storage */
3524 ss = sym_push(v, t, VT_CONST, c);
3525 ss->type.t |= VT_STATIC;
3526 if (tok != ',')
3527 break;
3528 next();
3529 c++;
3530 /* NOTE: we accept a trailing comma */
3531 if (tok == '}')
3532 break;
3534 if (!seen_neg)
3535 s->a.unsigned_enum = 1;
3536 s->c = type_size(seen_wide ? &size_type : &int_type, &align);
3537 skip('}');
3538 } else {
3539 ps = &s->next;
3540 flexible = 0;
3541 while (tok != '}') {
3542 if (!parse_btype(&btype, &ad1)) {
3543 skip(';');
3544 continue;
3546 while (1) {
3547 if (flexible)
3548 tcc_error("flexible array member '%s' not at the end of struct",
3549 get_tok_str(v, NULL));
3550 bit_size = -1;
3551 v = 0;
3552 type1 = btype;
3553 if (tok != ':') {
3554 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3555 if (v == 0) {
3556 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3557 expect("identifier");
3558 else {
3559 int v = btype.ref->v;
3560 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3561 if (tcc_state->ms_extensions == 0)
3562 expect("identifier");
3566 if (type_size(&type1, &align) < 0) {
3567 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3568 flexible = 1;
3569 else
3570 tcc_error("field '%s' has incomplete type",
3571 get_tok_str(v, NULL));
3573 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3574 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3575 tcc_error("invalid type for '%s'",
3576 get_tok_str(v, NULL));
3578 if (tok == ':') {
3579 next();
3580 bit_size = expr_const();
3581 /* XXX: handle v = 0 case for messages */
3582 if (bit_size < 0)
3583 tcc_error("negative width in bit-field '%s'",
3584 get_tok_str(v, NULL));
3585 if (v && bit_size == 0)
3586 tcc_error("zero width for bit-field '%s'",
3587 get_tok_str(v, NULL));
3588 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3589 parse_attribute(&ad1);
3591 size = type_size(&type1, &align);
3592 /* Only remember non-default alignment. */
3593 alignoverride = 0;
3594 if (ad1.a.aligned) {
3595 int speca = 1 << (ad1.a.aligned - 1);
3596 alignoverride = speca;
3597 } else if (ad1.a.packed || ad->a.packed) {
3598 alignoverride = 1;
3599 } else if (*tcc_state->pack_stack_ptr) {
3600 if (align > *tcc_state->pack_stack_ptr)
3601 alignoverride = *tcc_state->pack_stack_ptr;
3603 if (bit_size >= 0) {
3604 bt = type1.t & VT_BTYPE;
3605 if (bt != VT_INT &&
3606 bt != VT_BYTE &&
3607 bt != VT_SHORT &&
3608 bt != VT_BOOL &&
3609 bt != VT_ENUM &&
3610 bt != VT_LLONG)
3611 tcc_error("bitfields must have scalar type");
3612 bsize = size * 8;
3613 if (bit_size > bsize) {
3614 tcc_error("width of '%s' exceeds its type",
3615 get_tok_str(v, NULL));
3616 } else if (bit_size == bsize) {
3617 /* no need for bit fields */
3619 } else {
3620 type1.t |= VT_BITFIELD |
3621 (0 << VT_STRUCT_SHIFT) |
3622 (bit_size << (VT_STRUCT_SHIFT + 6));
3625 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3626 /* Remember we've seen a real field to check
3627 for placement of flexible array member. */
3628 c = 1;
3630 /* If member is a struct or bit-field, enforce
3631 placing into the struct (as anonymous). */
3632 if (v == 0 &&
3633 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3634 bit_size >= 0)) {
3635 v = anon_sym++;
3637 if (v) {
3638 ss = sym_push(v | SYM_FIELD, &type1, alignoverride, 0);
3639 *ps = ss;
3640 ps = &ss->next;
3642 if (tok == ';' || tok == TOK_EOF)
3643 break;
3644 skip(',');
3646 skip(';');
3648 skip('}');
3649 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3650 parse_attribute(ad);
3651 struct_layout(type, ad);
3656 /* return 1 if basic type is a type size (short, long, long long) */
3657 ST_FUNC int is_btype_size(int bt)
3659 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3662 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3663 are added to the element type, copied because it could be a typedef. */
3664 static void parse_btype_qualify(CType *type, int qualifiers)
3666 while (type->t & VT_ARRAY) {
3667 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3668 type = &type->ref->type;
3670 type->t |= qualifiers;
3673 /* return 0 if no type declaration. otherwise, return the basic type
3674 and skip it.
3676 static int parse_btype(CType *type, AttributeDef *ad)
3678 int t, u, bt_size, complete, type_found, typespec_found;
3679 Sym *s;
3680 CType type1;
3682 memset(ad, 0, sizeof(AttributeDef));
3683 complete = 0;
3684 type_found = 0;
3685 typespec_found = 0;
3686 t = 0;
3687 while(1) {
3688 switch(tok) {
3689 case TOK_EXTENSION:
3690 /* currently, we really ignore extension */
3691 next();
3692 continue;
3694 /* basic types */
3695 case TOK_CHAR:
3696 u = VT_BYTE;
3697 basic_type:
3698 next();
3699 basic_type1:
3700 if (complete)
3701 tcc_error("too many basic types");
3702 t |= u;
3703 bt_size = is_btype_size (u & VT_BTYPE);
3704 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3705 complete = 1;
3706 typespec_found = 1;
3707 break;
3708 case TOK_VOID:
3709 u = VT_VOID;
3710 goto basic_type;
3711 case TOK_SHORT:
3712 u = VT_SHORT;
3713 goto basic_type;
3714 case TOK_INT:
3715 u = VT_INT;
3716 goto basic_type;
3717 case TOK_LONG:
3718 next();
3719 if ((t & VT_BTYPE) == VT_DOUBLE) {
3720 #ifndef TCC_TARGET_PE
3721 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3722 #endif
3723 } else if ((t & VT_BTYPE) == VT_LONG) {
3724 t = (t & ~VT_BTYPE) | VT_LLONG;
3725 } else {
3726 u = VT_LONG;
3727 goto basic_type1;
3729 break;
3730 #ifdef TCC_TARGET_ARM64
3731 case TOK_UINT128:
3732 /* GCC's __uint128_t appears in some Linux header files. Make it a
3733 synonym for long double to get the size and alignment right. */
3734 u = VT_LDOUBLE;
3735 goto basic_type;
3736 #endif
3737 case TOK_BOOL:
3738 u = VT_BOOL;
3739 goto basic_type;
3740 case TOK_FLOAT:
3741 u = VT_FLOAT;
3742 goto basic_type;
3743 case TOK_DOUBLE:
3744 next();
3745 if ((t & VT_BTYPE) == VT_LONG) {
3746 #ifdef TCC_TARGET_PE
3747 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3748 #else
3749 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3750 #endif
3751 } else {
3752 u = VT_DOUBLE;
3753 goto basic_type1;
3755 break;
3756 case TOK_ENUM:
3757 struct_decl(&type1, ad, VT_ENUM);
3758 basic_type2:
3759 u = type1.t;
3760 type->ref = type1.ref;
3761 goto basic_type1;
3762 case TOK_STRUCT:
3763 case TOK_UNION:
3764 struct_decl(&type1, ad, VT_STRUCT);
3765 goto basic_type2;
3767 /* type modifiers */
3768 case TOK_CONST1:
3769 case TOK_CONST2:
3770 case TOK_CONST3:
3771 type->t = t;
3772 parse_btype_qualify(type, VT_CONSTANT);
3773 t = type->t;
3774 next();
3775 break;
3776 case TOK_VOLATILE1:
3777 case TOK_VOLATILE2:
3778 case TOK_VOLATILE3:
3779 type->t = t;
3780 parse_btype_qualify(type, VT_VOLATILE);
3781 t = type->t;
3782 next();
3783 break;
3784 case TOK_SIGNED1:
3785 case TOK_SIGNED2:
3786 case TOK_SIGNED3:
3787 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3788 tcc_error("signed and unsigned modifier");
3789 typespec_found = 1;
3790 t |= VT_DEFSIGN;
3791 next();
3792 break;
3793 case TOK_REGISTER:
3794 case TOK_AUTO:
3795 case TOK_RESTRICT1:
3796 case TOK_RESTRICT2:
3797 case TOK_RESTRICT3:
3798 next();
3799 break;
3800 case TOK_UNSIGNED:
3801 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3802 tcc_error("signed and unsigned modifier");
3803 t |= VT_DEFSIGN | VT_UNSIGNED;
3804 next();
3805 typespec_found = 1;
3806 break;
3808 /* storage */
3809 case TOK_EXTERN:
3810 t |= VT_EXTERN;
3811 next();
3812 break;
3813 case TOK_STATIC:
3814 t |= VT_STATIC;
3815 next();
3816 break;
3817 case TOK_TYPEDEF:
3818 t |= VT_TYPEDEF;
3819 next();
3820 break;
3821 case TOK_INLINE1:
3822 case TOK_INLINE2:
3823 case TOK_INLINE3:
3824 t |= VT_INLINE;
3825 next();
3826 break;
3828 /* GNUC attribute */
3829 case TOK_ATTRIBUTE1:
3830 case TOK_ATTRIBUTE2:
3831 parse_attribute(ad);
3832 if (ad->a.mode) {
3833 u = ad->a.mode -1;
3834 t = (t & ~VT_BTYPE) | u;
3836 break;
3837 /* GNUC typeof */
3838 case TOK_TYPEOF1:
3839 case TOK_TYPEOF2:
3840 case TOK_TYPEOF3:
3841 next();
3842 parse_expr_type(&type1);
3843 /* remove all storage modifiers except typedef */
3844 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3845 goto basic_type2;
3846 default:
3847 if (typespec_found)
3848 goto the_end;
3849 s = sym_find(tok);
3850 if (!s || !(s->type.t & VT_TYPEDEF))
3851 goto the_end;
3853 type->t = ((s->type.t & ~VT_TYPEDEF) |
3854 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3855 type->ref = s->type.ref;
3856 if (t & (VT_CONSTANT | VT_VOLATILE))
3857 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3858 t = type->t;
3860 if (s->r) {
3861 /* get attributes from typedef */
3862 if (0 == ad->a.aligned)
3863 ad->a.aligned = s->a.aligned;
3864 if (0 == ad->a.func_call)
3865 ad->a.func_call = s->a.func_call;
3866 ad->a.packed |= s->a.packed;
3868 next();
3869 typespec_found = 1;
3870 break;
3872 type_found = 1;
3874 the_end:
3875 if (tcc_state->char_is_unsigned) {
3876 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3877 t |= VT_UNSIGNED;
3880 /* long is never used as type */
3881 if ((t & VT_BTYPE) == VT_LONG)
3882 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3883 defined TCC_TARGET_PE
3884 t = (t & ~VT_BTYPE) | VT_INT;
3885 #else
3886 t = (t & ~VT_BTYPE) | VT_LLONG;
3887 #endif
3888 type->t = t;
3889 return type_found;
3892 /* convert a function parameter type (array to pointer and function to
3893 function pointer) */
3894 static inline void convert_parameter_type(CType *pt)
3896 /* remove const and volatile qualifiers (XXX: const could be used
3897 to indicate a const function parameter */
3898 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3899 /* array must be transformed to pointer according to ANSI C */
3900 pt->t &= ~VT_ARRAY;
3901 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3902 mk_pointer(pt);
3906 ST_FUNC void parse_asm_str(CString *astr)
3908 skip('(');
3909 parse_mult_str(astr, "string constant");
3912 /* Parse an asm label and return the token */
3913 static int asm_label_instr(void)
3915 int v;
3916 CString astr;
3918 next();
3919 parse_asm_str(&astr);
3920 skip(')');
3921 #ifdef ASM_DEBUG
3922 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3923 #endif
3924 v = tok_alloc(astr.data, astr.size - 1)->tok;
3925 cstr_free(&astr);
3926 return v;
3929 static void post_type(CType *type, AttributeDef *ad, int storage)
3931 int n, l, t1, arg_size, align;
3932 Sym **plast, *s, *first;
3933 AttributeDef ad1;
3934 CType pt;
3936 if (tok == '(') {
3937 /* function declaration */
3938 next();
3939 l = 0;
3940 first = NULL;
3941 plast = &first;
3942 arg_size = 0;
3943 if (tok != ')') {
3944 for(;;) {
3945 /* read param name and compute offset */
3946 if (l != FUNC_OLD) {
3947 if (!parse_btype(&pt, &ad1)) {
3948 if (l) {
3949 tcc_error("invalid type");
3950 } else {
3951 l = FUNC_OLD;
3952 goto old_proto;
3955 l = FUNC_NEW;
3956 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3957 break;
3958 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3959 if ((pt.t & VT_BTYPE) == VT_VOID)
3960 tcc_error("parameter declared as void");
3961 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3962 } else {
3963 old_proto:
3964 n = tok;
3965 if (n < TOK_UIDENT)
3966 expect("identifier");
3967 pt.t = VT_INT;
3968 next();
3970 convert_parameter_type(&pt);
3971 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3972 *plast = s;
3973 plast = &s->next;
3974 if (tok == ')')
3975 break;
3976 skip(',');
3977 if (l == FUNC_NEW && tok == TOK_DOTS) {
3978 l = FUNC_ELLIPSIS;
3979 next();
3980 break;
3984 /* if no parameters, then old type prototype */
3985 if (l == 0)
3986 l = FUNC_OLD;
3987 skip(')');
3988 /* NOTE: const is ignored in returned type as it has a special
3989 meaning in gcc / C++ */
3990 type->t &= ~VT_CONSTANT;
3991 /* some ancient pre-K&R C allows a function to return an array
3992 and the array brackets to be put after the arguments, such
3993 that "int c()[]" means something like "int[] c()" */
3994 if (tok == '[') {
3995 next();
3996 skip(']'); /* only handle simple "[]" */
3997 type->t |= VT_PTR;
3999 /* we push a anonymous symbol which will contain the function prototype */
4000 ad->a.func_args = arg_size;
4001 s = sym_push(SYM_FIELD, type, 0, l);
4002 s->a = ad->a;
4003 s->next = first;
4004 type->t = VT_FUNC;
4005 type->ref = s;
4006 } else if (tok == '[') {
4007 int saved_nocode_wanted = nocode_wanted;
4008 /* array definition */
4009 next();
4010 if (tok == TOK_RESTRICT1)
4011 next();
4012 n = -1;
4013 t1 = 0;
4014 if (tok != ']') {
4015 if (!local_stack || (storage & VT_STATIC))
4016 vpushi(expr_const());
4017 else {
4018 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4019 length must always be evaluated, even under nocode_wanted,
4020 so that its size slot is initialized (e.g. under sizeof
4021 or typeof). */
4022 nocode_wanted = 0;
4023 gexpr();
4025 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4026 n = vtop->c.i;
4027 if (n < 0)
4028 tcc_error("invalid array size");
4029 } else {
4030 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4031 tcc_error("size of variable length array should be an integer");
4032 t1 = VT_VLA;
4035 skip(']');
4036 /* parse next post type */
4037 post_type(type, ad, storage);
4038 if (type->t == VT_FUNC)
4039 tcc_error("declaration of an array of functions");
4040 t1 |= type->t & VT_VLA;
4042 if (t1 & VT_VLA) {
4043 loc -= type_size(&int_type, &align);
4044 loc &= -align;
4045 n = loc;
4047 vla_runtime_type_size(type, &align);
4048 gen_op('*');
4049 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4050 vswap();
4051 vstore();
4053 if (n != -1)
4054 vpop();
4055 nocode_wanted = saved_nocode_wanted;
4057 /* we push an anonymous symbol which will contain the array
4058 element type */
4059 s = sym_push(SYM_FIELD, type, 0, n);
4060 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4061 type->ref = s;
4065 /* Parse a type declaration (except basic type), and return the type
4066 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4067 expected. 'type' should contain the basic type. 'ad' is the
4068 attribute definition of the basic type. It can be modified by
4069 type_decl().
4071 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
4073 Sym *s;
4074 CType type1, *type2;
4075 int qualifiers, storage;
4077 while (tok == '*') {
4078 qualifiers = 0;
4079 redo:
4080 next();
4081 switch(tok) {
4082 case TOK_CONST1:
4083 case TOK_CONST2:
4084 case TOK_CONST3:
4085 qualifiers |= VT_CONSTANT;
4086 goto redo;
4087 case TOK_VOLATILE1:
4088 case TOK_VOLATILE2:
4089 case TOK_VOLATILE3:
4090 qualifiers |= VT_VOLATILE;
4091 goto redo;
4092 case TOK_RESTRICT1:
4093 case TOK_RESTRICT2:
4094 case TOK_RESTRICT3:
4095 goto redo;
4096 /* XXX: clarify attribute handling */
4097 case TOK_ATTRIBUTE1:
4098 case TOK_ATTRIBUTE2:
4099 parse_attribute(ad);
4100 break;
4102 mk_pointer(type);
4103 type->t |= qualifiers;
4106 /* recursive type */
4107 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
4108 type1.t = 0; /* XXX: same as int */
4109 if (tok == '(') {
4110 next();
4111 /* XXX: this is not correct to modify 'ad' at this point, but
4112 the syntax is not clear */
4113 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
4114 parse_attribute(ad);
4115 type_decl(&type1, ad, v, td);
4116 skip(')');
4117 } else {
4118 /* type identifier */
4119 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4120 *v = tok;
4121 next();
4122 } else {
4123 if (!(td & TYPE_ABSTRACT))
4124 expect("identifier");
4125 *v = 0;
4128 storage = type->t & VT_STORAGE;
4129 type->t &= ~VT_STORAGE;
4130 post_type(type, ad, storage);
4131 type->t |= storage;
4132 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
4133 parse_attribute(ad);
4135 if (!type1.t)
4136 return;
4137 /* append type at the end of type1 */
4138 type2 = &type1;
4139 for(;;) {
4140 s = type2->ref;
4141 type2 = &s->type;
4142 if (!type2->t) {
4143 *type2 = *type;
4144 break;
4147 *type = type1;
4150 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4151 ST_FUNC int lvalue_type(int t)
4153 int bt, r;
4154 r = VT_LVAL;
4155 bt = t & VT_BTYPE;
4156 if (bt == VT_BYTE || bt == VT_BOOL)
4157 r |= VT_LVAL_BYTE;
4158 else if (bt == VT_SHORT)
4159 r |= VT_LVAL_SHORT;
4160 else
4161 return r;
4162 if (t & VT_UNSIGNED)
4163 r |= VT_LVAL_UNSIGNED;
4164 return r;
4167 /* indirection with full error checking and bound check */
4168 ST_FUNC void indir(void)
4170 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4171 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4172 return;
4173 expect("pointer");
4175 if (vtop->r & VT_LVAL)
4176 gv(RC_INT);
4177 vtop->type = *pointed_type(&vtop->type);
4178 /* Arrays and functions are never lvalues */
4179 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4180 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4181 vtop->r |= lvalue_type(vtop->type.t);
4182 /* if bound checking, the referenced pointer must be checked */
4183 #ifdef CONFIG_TCC_BCHECK
4184 if (tcc_state->do_bounds_check)
4185 vtop->r |= VT_MUSTBOUND;
4186 #endif
4190 /* pass a parameter to a function and do type checking and casting */
4191 static void gfunc_param_typed(Sym *func, Sym *arg)
4193 int func_type;
4194 CType type;
4196 func_type = func->c;
4197 if (func_type == FUNC_OLD ||
4198 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4199 /* default casting : only need to convert float to double */
4200 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4201 type.t = VT_DOUBLE;
4202 gen_cast(&type);
4203 } else if (vtop->type.t & VT_BITFIELD) {
4204 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4205 type.ref = vtop->type.ref;
4206 gen_cast(&type);
4208 } else if (arg == NULL) {
4209 tcc_error("too many arguments to function");
4210 } else {
4211 type = arg->type;
4212 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4213 gen_assign_cast(&type);
4217 /* parse an expression of the form '(type)' or '(expr)' and return its
4218 type */
4219 static void parse_expr_type(CType *type)
4221 int n;
4222 AttributeDef ad;
4224 skip('(');
4225 if (parse_btype(type, &ad)) {
4226 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4227 } else {
4228 expr_type(type);
4230 skip(')');
4233 static void parse_type(CType *type)
4235 AttributeDef ad;
4236 int n;
4238 if (!parse_btype(type, &ad)) {
4239 expect("type");
4241 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4244 static void vpush_tokc(int t)
4246 CType type;
4247 type.t = t;
4248 type.ref = 0;
4249 vsetc(&type, VT_CONST, &tokc);
4252 ST_FUNC void unary(void)
4254 int n, t, align, size, r, sizeof_caller;
4255 CType type;
4256 Sym *s;
4257 AttributeDef ad;
4259 sizeof_caller = in_sizeof;
4260 in_sizeof = 0;
4261 /* XXX: GCC 2.95.3 does not generate a table although it should be
4262 better here */
4263 tok_next:
4264 switch(tok) {
4265 case TOK_EXTENSION:
4266 next();
4267 goto tok_next;
4268 case TOK_CINT:
4269 case TOK_CCHAR:
4270 case TOK_LCHAR:
4271 vpushi(tokc.i);
4272 next();
4273 break;
4274 case TOK_CUINT:
4275 vpush_tokc(VT_INT | VT_UNSIGNED);
4276 next();
4277 break;
4278 case TOK_CLLONG:
4279 vpush_tokc(VT_LLONG);
4280 next();
4281 break;
4282 case TOK_CULLONG:
4283 vpush_tokc(VT_LLONG | VT_UNSIGNED);
4284 next();
4285 break;
4286 case TOK_CFLOAT:
4287 vpush_tokc(VT_FLOAT);
4288 next();
4289 break;
4290 case TOK_CDOUBLE:
4291 vpush_tokc(VT_DOUBLE);
4292 next();
4293 break;
4294 case TOK_CLDOUBLE:
4295 vpush_tokc(VT_LDOUBLE);
4296 next();
4297 break;
4298 case TOK___FUNCTION__:
4299 if (!gnu_ext)
4300 goto tok_identifier;
4301 /* fall thru */
4302 case TOK___FUNC__:
4304 void *ptr;
4305 int len;
4306 /* special function name identifier */
4307 len = strlen(funcname) + 1;
4308 /* generate char[len] type */
4309 type.t = VT_BYTE;
4310 mk_pointer(&type);
4311 type.t |= VT_ARRAY;
4312 type.ref->c = len;
4313 vpush_ref(&type, data_section, data_section->data_offset, len);
4314 ptr = section_ptr_add(data_section, len);
4315 memcpy(ptr, funcname, len);
4316 next();
4318 break;
4319 case TOK_LSTR:
4320 #ifdef TCC_TARGET_PE
4321 t = VT_SHORT | VT_UNSIGNED;
4322 #else
4323 t = VT_INT;
4324 #endif
4325 goto str_init;
4326 case TOK_STR:
4327 /* string parsing */
4328 t = VT_BYTE;
4329 str_init:
4330 if (tcc_state->warn_write_strings)
4331 t |= VT_CONSTANT;
4332 type.t = t;
4333 mk_pointer(&type);
4334 type.t |= VT_ARRAY;
4335 memset(&ad, 0, sizeof(AttributeDef));
4336 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4337 break;
4338 case '(':
4339 next();
4340 /* cast ? */
4341 if (parse_btype(&type, &ad)) {
4342 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4343 skip(')');
4344 /* check ISOC99 compound literal */
4345 if (tok == '{') {
4346 /* data is allocated locally by default */
4347 if (global_expr)
4348 r = VT_CONST;
4349 else
4350 r = VT_LOCAL;
4351 /* all except arrays are lvalues */
4352 if (!(type.t & VT_ARRAY))
4353 r |= lvalue_type(type.t);
4354 memset(&ad, 0, sizeof(AttributeDef));
4355 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4356 } else {
4357 if (sizeof_caller) {
4358 vpush(&type);
4359 return;
4361 unary();
4362 gen_cast(&type);
4364 } else if (tok == '{') {
4365 int saved_nocode_wanted = nocode_wanted;
4366 if (const_wanted)
4367 tcc_error("expected constant");
4368 /* save all registers */
4369 save_regs(0);
4370 /* statement expression : we do not accept break/continue
4371 inside as GCC does. We do retain the nocode_wanted state,
4372 as statement expressions can't ever be entered from the
4373 outside, so any reactivation of code emission (from labels
4374 or loop heads) can be disabled again after the end of it. */
4375 block(NULL, NULL, 1);
4376 nocode_wanted = saved_nocode_wanted;
4377 skip(')');
4378 } else {
4379 gexpr();
4380 skip(')');
4382 break;
4383 case '*':
4384 next();
4385 unary();
4386 indir();
4387 break;
4388 case '&':
4389 next();
4390 unary();
4391 /* functions names must be treated as function pointers,
4392 except for unary '&' and sizeof. Since we consider that
4393 functions are not lvalues, we only have to handle it
4394 there and in function calls. */
4395 /* arrays can also be used although they are not lvalues */
4396 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4397 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
4398 test_lvalue();
4399 mk_pointer(&vtop->type);
4400 gaddrof();
4401 break;
4402 case '!':
4403 next();
4404 unary();
4405 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4406 CType boolean;
4407 boolean.t = VT_BOOL;
4408 gen_cast(&boolean);
4409 vtop->c.i = !vtop->c.i;
4410 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4411 vtop->c.i ^= 1;
4412 else {
4413 save_regs(1);
4414 vseti(VT_JMP, gvtst(1, 0));
4416 break;
4417 case '~':
4418 next();
4419 unary();
4420 vpushi(-1);
4421 gen_op('^');
4422 break;
4423 case '+':
4424 next();
4425 unary();
4426 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4427 tcc_error("pointer not accepted for unary plus");
4428 /* In order to force cast, we add zero, except for floating point
4429 where we really need an noop (otherwise -0.0 will be transformed
4430 into +0.0). */
4431 if (!is_float(vtop->type.t)) {
4432 vpushi(0);
4433 gen_op('+');
4435 break;
4436 case TOK_SIZEOF:
4437 case TOK_ALIGNOF1:
4438 case TOK_ALIGNOF2:
4439 t = tok;
4440 next();
4441 in_sizeof++;
4442 unary_type(&type); // Perform a in_sizeof = 0;
4443 size = type_size(&type, &align);
4444 if (t == TOK_SIZEOF) {
4445 if (!(type.t & VT_VLA)) {
4446 if (size < 0)
4447 tcc_error("sizeof applied to an incomplete type");
4448 vpushs(size);
4449 } else {
4450 vla_runtime_type_size(&type, &align);
4452 } else {
4453 vpushs(align);
4455 vtop->type.t |= VT_UNSIGNED;
4456 break;
4458 case TOK_builtin_expect:
4460 /* __builtin_expect is a no-op for now */
4461 next();
4462 skip('(');
4463 expr_eq();
4464 skip(',');
4465 nocode_wanted++;
4466 expr_lor_const();
4467 vpop();
4468 nocode_wanted--;
4469 skip(')');
4471 break;
4472 case TOK_builtin_types_compatible_p:
4474 CType type1, type2;
4475 next();
4476 skip('(');
4477 parse_type(&type1);
4478 skip(',');
4479 parse_type(&type2);
4480 skip(')');
4481 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
4482 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
4483 vpushi(is_compatible_types(&type1, &type2));
4485 break;
4486 case TOK_builtin_choose_expr:
4488 int64_t c;
4489 next();
4490 skip('(');
4491 c = expr_const64();
4492 skip(',');
4493 if (!c) {
4494 nocode_wanted++;
4496 expr_eq();
4497 if (!c) {
4498 vpop();
4499 nocode_wanted--;
4501 skip(',');
4502 if (c) {
4503 nocode_wanted++;
4505 expr_eq();
4506 if (c) {
4507 vpop();
4508 nocode_wanted--;
4510 skip(')');
4512 break;
4513 case TOK_builtin_constant_p:
4515 int res;
4516 next();
4517 skip('(');
4518 nocode_wanted++;
4519 gexpr();
4520 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4521 vpop();
4522 nocode_wanted--;
4523 skip(')');
4524 vpushi(res);
4526 break;
4527 case TOK_builtin_frame_address:
4528 case TOK_builtin_return_address:
4530 int tok1 = tok;
4531 int level;
4532 CType type;
4533 next();
4534 skip('(');
4535 if (tok != TOK_CINT) {
4536 tcc_error("%s only takes positive integers",
4537 tok1 == TOK_builtin_return_address ?
4538 "__builtin_return_address" :
4539 "__builtin_frame_address");
4541 level = (uint32_t)tokc.i;
4542 next();
4543 skip(')');
4544 type.t = VT_VOID;
4545 mk_pointer(&type);
4546 vset(&type, VT_LOCAL, 0); /* local frame */
4547 while (level--) {
4548 mk_pointer(&vtop->type);
4549 indir(); /* -> parent frame */
4551 if (tok1 == TOK_builtin_return_address) {
4552 // assume return address is just above frame pointer on stack
4553 vpushi(PTR_SIZE);
4554 gen_op('+');
4555 mk_pointer(&vtop->type);
4556 indir();
4559 break;
4560 #ifdef TCC_TARGET_X86_64
4561 #ifdef TCC_TARGET_PE
4562 case TOK_builtin_va_start:
4564 next();
4565 skip('(');
4566 expr_eq();
4567 skip(',');
4568 expr_eq();
4569 skip(')');
4570 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4571 tcc_error("__builtin_va_start expects a local variable");
4572 vtop->r &= ~(VT_LVAL | VT_REF);
4573 vtop->type = char_pointer_type;
4574 vtop->c.i += 8;
4575 vstore();
4577 break;
4578 #else
4579 case TOK_builtin_va_arg_types:
4581 CType type;
4582 next();
4583 skip('(');
4584 parse_type(&type);
4585 skip(')');
4586 vpushi(classify_x86_64_va_arg(&type));
4588 break;
4589 #endif
4590 #endif
4592 #ifdef TCC_TARGET_ARM64
4593 case TOK___va_start: {
4594 next();
4595 skip('(');
4596 expr_eq();
4597 skip(',');
4598 expr_eq();
4599 skip(')');
4600 //xx check types
4601 gen_va_start();
4602 vpushi(0);
4603 vtop->type.t = VT_VOID;
4604 break;
4606 case TOK___va_arg: {
4607 CType type;
4608 next();
4609 skip('(');
4610 expr_eq();
4611 skip(',');
4612 parse_type(&type);
4613 skip(')');
4614 //xx check types
4615 gen_va_arg(&type);
4616 vtop->type = type;
4617 break;
4619 case TOK___arm64_clear_cache: {
4620 next();
4621 skip('(');
4622 expr_eq();
4623 skip(',');
4624 expr_eq();
4625 skip(')');
4626 gen_clear_cache();
4627 vpushi(0);
4628 vtop->type.t = VT_VOID;
4629 break;
4631 #endif
4632 /* pre operations */
4633 case TOK_INC:
4634 case TOK_DEC:
4635 t = tok;
4636 next();
4637 unary();
4638 inc(0, t);
4639 break;
4640 case '-':
4641 next();
4642 unary();
4643 t = vtop->type.t & VT_BTYPE;
4644 if (is_float(t)) {
4645 /* In IEEE negate(x) isn't subtract(0,x), but rather
4646 subtract(-0, x). */
4647 vpush(&vtop->type);
4648 if (t == VT_FLOAT)
4649 vtop->c.f = -1.0 * 0.0;
4650 else if (t == VT_DOUBLE)
4651 vtop->c.d = -1.0 * 0.0;
4652 else
4653 vtop->c.ld = -1.0 * 0.0;
4654 } else
4655 vpushi(0);
4656 vswap();
4657 gen_op('-');
4658 break;
4659 case TOK_LAND:
4660 if (!gnu_ext)
4661 goto tok_identifier;
4662 next();
4663 /* allow to take the address of a label */
4664 if (tok < TOK_UIDENT)
4665 expect("label identifier");
4666 s = label_find(tok);
4667 if (!s) {
4668 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4669 } else {
4670 if (s->r == LABEL_DECLARED)
4671 s->r = LABEL_FORWARD;
4673 if (!s->type.t) {
4674 s->type.t = VT_VOID;
4675 mk_pointer(&s->type);
4676 s->type.t |= VT_STATIC;
4678 vpushsym(&s->type, s);
4679 next();
4680 break;
4682 // special qnan , snan and infinity values
4683 case TOK___NAN__:
4684 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4685 next();
4686 break;
4687 case TOK___SNAN__:
4688 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4689 next();
4690 break;
4691 case TOK___INF__:
4692 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4693 next();
4694 break;
4696 default:
4697 tok_identifier:
4698 t = tok;
4699 next();
4700 if (t < TOK_UIDENT)
4701 expect("identifier");
4702 s = sym_find(t);
4703 if (!s) {
4704 const char *name = get_tok_str(t, NULL);
4705 if (tok != '(')
4706 tcc_error("'%s' undeclared", name);
4707 /* for simple function calls, we tolerate undeclared
4708 external reference to int() function */
4709 if (tcc_state->warn_implicit_function_declaration
4710 #ifdef TCC_TARGET_PE
4711 /* people must be warned about using undeclared WINAPI functions
4712 (which usually start with uppercase letter) */
4713 || (name[0] >= 'A' && name[0] <= 'Z')
4714 #endif
4716 tcc_warning("implicit declaration of function '%s'", name);
4717 s = external_global_sym(t, &func_old_type, 0);
4720 r = s->r;
4721 /* A symbol that has a register is a local register variable,
4722 which starts out as VT_LOCAL value. */
4723 if ((r & VT_VALMASK) < VT_CONST)
4724 r = (r & ~VT_VALMASK) | VT_LOCAL;
4726 vset(&s->type, r, s->c);
4727 /* Point to s as backpointer (even without r&VT_SYM).
4728 Will be used by at least the x86 inline asm parser for
4729 regvars. */
4730 vtop->sym = s;
4731 if (vtop->r & VT_SYM) {
4732 vtop->c.i = 0;
4734 break;
4737 /* post operations */
4738 while (1) {
4739 if (tok == TOK_INC || tok == TOK_DEC) {
4740 inc(1, tok);
4741 next();
4742 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4743 int qualifiers;
4744 /* field */
4745 if (tok == TOK_ARROW)
4746 indir();
4747 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4748 test_lvalue();
4749 gaddrof();
4750 /* expect pointer on structure */
4751 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4752 expect("struct or union");
4753 if (tok == TOK_CDOUBLE)
4754 expect("field name");
4755 next();
4756 if (tok == TOK_CINT || tok == TOK_CUINT)
4757 expect("field name");
4758 s = find_field(&vtop->type, tok);
4759 if (!s)
4760 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4761 /* add field offset to pointer */
4762 vtop->type = char_pointer_type; /* change type to 'char *' */
4763 vpushi(s->c);
4764 gen_op('+');
4765 /* change type to field type, and set to lvalue */
4766 vtop->type = s->type;
4767 vtop->type.t |= qualifiers;
4768 /* an array is never an lvalue */
4769 if (!(vtop->type.t & VT_ARRAY)) {
4770 vtop->r |= lvalue_type(vtop->type.t);
4771 #ifdef CONFIG_TCC_BCHECK
4772 /* if bound checking, the referenced pointer must be checked */
4773 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
4774 vtop->r |= VT_MUSTBOUND;
4775 #endif
4777 next();
4778 } else if (tok == '[') {
4779 next();
4780 gexpr();
4781 gen_op('+');
4782 indir();
4783 skip(']');
4784 } else if (tok == '(') {
4785 SValue ret;
4786 Sym *sa;
4787 int nb_args, ret_nregs, ret_align, regsize, variadic;
4789 /* function call */
4790 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4791 /* pointer test (no array accepted) */
4792 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4793 vtop->type = *pointed_type(&vtop->type);
4794 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4795 goto error_func;
4796 } else {
4797 error_func:
4798 expect("function pointer");
4800 } else {
4801 vtop->r &= ~VT_LVAL; /* no lvalue */
4803 /* get return type */
4804 s = vtop->type.ref;
4805 next();
4806 sa = s->next; /* first parameter */
4807 nb_args = regsize = 0;
4808 ret.r2 = VT_CONST;
4809 /* compute first implicit argument if a structure is returned */
4810 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4811 variadic = (s->c == FUNC_ELLIPSIS);
4812 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4813 &ret_align, &regsize);
4814 if (!ret_nregs) {
4815 /* get some space for the returned structure */
4816 size = type_size(&s->type, &align);
4817 #ifdef TCC_TARGET_ARM64
4818 /* On arm64, a small struct is return in registers.
4819 It is much easier to write it to memory if we know
4820 that we are allowed to write some extra bytes, so
4821 round the allocated space up to a power of 2: */
4822 if (size < 16)
4823 while (size & (size - 1))
4824 size = (size | (size - 1)) + 1;
4825 #endif
4826 loc = (loc - size) & -align;
4827 ret.type = s->type;
4828 ret.r = VT_LOCAL | VT_LVAL;
4829 /* pass it as 'int' to avoid structure arg passing
4830 problems */
4831 vseti(VT_LOCAL, loc);
4832 ret.c = vtop->c;
4833 nb_args++;
4835 } else {
4836 ret_nregs = 1;
4837 ret.type = s->type;
4840 if (ret_nregs) {
4841 /* return in register */
4842 if (is_float(ret.type.t)) {
4843 ret.r = reg_fret(ret.type.t);
4844 #ifdef TCC_TARGET_X86_64
4845 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4846 ret.r2 = REG_QRET;
4847 #endif
4848 } else {
4849 #ifndef TCC_TARGET_ARM64
4850 #ifdef TCC_TARGET_X86_64
4851 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4852 #else
4853 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4854 #endif
4855 ret.r2 = REG_LRET;
4856 #endif
4857 ret.r = REG_IRET;
4859 ret.c.i = 0;
4861 if (tok != ')') {
4862 for(;;) {
4863 expr_eq();
4864 gfunc_param_typed(s, sa);
4865 nb_args++;
4866 if (sa)
4867 sa = sa->next;
4868 if (tok == ')')
4869 break;
4870 skip(',');
4873 if (sa)
4874 tcc_error("too few arguments to function");
4875 skip(')');
4876 gfunc_call(nb_args);
4878 /* return value */
4879 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4880 vsetc(&ret.type, r, &ret.c);
4881 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4884 /* handle packed struct return */
4885 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4886 int addr, offset;
4888 size = type_size(&s->type, &align);
4889 /* We're writing whole regs often, make sure there's enough
4890 space. Assume register size is power of 2. */
4891 if (regsize > align)
4892 align = regsize;
4893 loc = (loc - size) & -align;
4894 addr = loc;
4895 offset = 0;
4896 for (;;) {
4897 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4898 vswap();
4899 vstore();
4900 vtop--;
4901 if (--ret_nregs == 0)
4902 break;
4903 offset += regsize;
4905 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4907 } else {
4908 break;
4913 ST_FUNC void expr_prod(void)
4915 int t;
4917 unary();
4918 while (tok == '*' || tok == '/' || tok == '%') {
4919 t = tok;
4920 next();
4921 unary();
4922 gen_op(t);
4926 ST_FUNC void expr_sum(void)
4928 int t;
4930 expr_prod();
4931 while (tok == '+' || tok == '-') {
4932 t = tok;
4933 next();
4934 expr_prod();
4935 gen_op(t);
4939 static void expr_shift(void)
4941 int t;
4943 expr_sum();
4944 while (tok == TOK_SHL || tok == TOK_SAR) {
4945 t = tok;
4946 next();
4947 expr_sum();
4948 gen_op(t);
4952 static void expr_cmp(void)
4954 int t;
4956 expr_shift();
4957 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4958 tok == TOK_ULT || tok == TOK_UGE) {
4959 t = tok;
4960 next();
4961 expr_shift();
4962 gen_op(t);
4966 static void expr_cmpeq(void)
4968 int t;
4970 expr_cmp();
4971 while (tok == TOK_EQ || tok == TOK_NE) {
4972 t = tok;
4973 next();
4974 expr_cmp();
4975 gen_op(t);
4979 static void expr_and(void)
4981 expr_cmpeq();
4982 while (tok == '&') {
4983 next();
4984 expr_cmpeq();
4985 gen_op('&');
4989 static void expr_xor(void)
4991 expr_and();
4992 while (tok == '^') {
4993 next();
4994 expr_and();
4995 gen_op('^');
4999 static void expr_or(void)
5001 expr_xor();
5002 while (tok == '|') {
5003 next();
5004 expr_xor();
5005 gen_op('|');
5009 /* XXX: fix this mess */
5010 static void expr_land_const(void)
5012 expr_or();
5013 while (tok == TOK_LAND) {
5014 next();
5015 expr_or();
5016 gen_op(TOK_LAND);
5019 static void expr_lor_const(void)
5021 expr_land_const();
5022 while (tok == TOK_LOR) {
5023 next();
5024 expr_land_const();
5025 gen_op(TOK_LOR);
5029 static void expr_land(void)
5031 expr_or();
5032 if (tok == TOK_LAND) {
5033 int t = 0;
5034 for(;;) {
5035 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5036 CType ctb;
5037 ctb.t = VT_BOOL;
5038 gen_cast(&ctb);
5039 if (vtop->c.i) {
5040 vpop();
5041 } else {
5042 nocode_wanted++;
5043 while (tok == TOK_LAND) {
5044 next();
5045 expr_or();
5046 vpop();
5048 nocode_wanted--;
5049 if (t)
5050 gsym(t);
5051 gen_cast(&int_type);
5052 break;
5054 } else {
5055 if (!t)
5056 save_regs(1);
5057 t = gvtst(1, t);
5059 if (tok != TOK_LAND) {
5060 if (t)
5061 vseti(VT_JMPI, t);
5062 else
5063 vpushi(1);
5064 break;
5066 next();
5067 expr_or();
5072 static void expr_lor(void)
5074 expr_land();
5075 if (tok == TOK_LOR) {
5076 int t = 0;
5077 for(;;) {
5078 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5079 CType ctb;
5080 ctb.t = VT_BOOL;
5081 gen_cast(&ctb);
5082 if (!vtop->c.i) {
5083 vpop();
5084 } else {
5085 nocode_wanted++;
5086 while (tok == TOK_LOR) {
5087 next();
5088 expr_land();
5089 vpop();
5091 nocode_wanted--;
5092 if (t)
5093 gsym(t);
5094 gen_cast(&int_type);
5095 break;
5097 } else {
5098 if (!t)
5099 save_regs(1);
5100 t = gvtst(0, t);
5102 if (tok != TOK_LOR) {
5103 if (t)
5104 vseti(VT_JMP, t);
5105 else
5106 vpushi(0);
5107 break;
5109 next();
5110 expr_land();
5115 /* Assuming vtop is a value used in a conditional context
5116 (i.e. compared with zero) return 0 if it's false, 1 if
5117 true and -1 if it can't be statically determined. */
5118 static int condition_3way(void)
5120 int c = -1;
5121 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5122 (!(vtop->r & VT_SYM) ||
5123 !(vtop->sym->type.t & VT_WEAK))) {
5124 CType boolean;
5125 boolean.t = VT_BOOL;
5126 vdup();
5127 gen_cast(&boolean);
5128 c = vtop->c.i;
5129 vpop();
5131 return c;
5134 static void expr_cond(void)
5136 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5137 SValue sv;
5138 CType type, type1, type2;
5140 expr_lor();
5141 if (tok == '?') {
5142 next();
5143 c = condition_3way();
5144 g = (tok == ':' && gnu_ext);
5145 if (c < 0) {
5146 /* needed to avoid having different registers saved in
5147 each branch */
5148 if (is_float(vtop->type.t)) {
5149 rc = RC_FLOAT;
5150 #ifdef TCC_TARGET_X86_64
5151 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5152 rc = RC_ST0;
5154 #endif
5155 } else
5156 rc = RC_INT;
5157 gv(rc);
5158 save_regs(1);
5159 if (g)
5160 gv_dup();
5161 tt = gvtst(1, 0);
5163 } else {
5164 if (!g)
5165 vpop();
5166 tt = 0;
5169 if (1) {
5170 if (c == 0)
5171 nocode_wanted++;
5172 if (!g)
5173 gexpr();
5175 type1 = vtop->type;
5176 sv = *vtop; /* save value to handle it later */
5177 vtop--; /* no vpop so that FP stack is not flushed */
5178 skip(':');
5180 u = 0;
5181 if (c < 0)
5182 u = gjmp(0);
5183 gsym(tt);
5185 if (c == 0)
5186 nocode_wanted--;
5187 if (c == 1)
5188 nocode_wanted++;
5189 expr_cond();
5190 if (c == 1)
5191 nocode_wanted--;
5193 type2 = vtop->type;
5194 t1 = type1.t;
5195 bt1 = t1 & VT_BTYPE;
5196 t2 = type2.t;
5197 bt2 = t2 & VT_BTYPE;
5198 /* cast operands to correct type according to ISOC rules */
5199 if (is_float(bt1) || is_float(bt2)) {
5200 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5201 type.t = VT_LDOUBLE;
5203 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5204 type.t = VT_DOUBLE;
5205 } else {
5206 type.t = VT_FLOAT;
5208 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5209 /* cast to biggest op */
5210 type.t = VT_LLONG;
5211 /* convert to unsigned if it does not fit in a long long */
5212 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5213 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5214 type.t |= VT_UNSIGNED;
5215 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5216 /* If one is a null ptr constant the result type
5217 is the other. */
5218 if (is_null_pointer (vtop))
5219 type = type1;
5220 else if (is_null_pointer (&sv))
5221 type = type2;
5222 /* XXX: test pointer compatibility, C99 has more elaborate
5223 rules here. */
5224 else
5225 type = type1;
5226 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5227 /* XXX: test function pointer compatibility */
5228 type = bt1 == VT_FUNC ? type1 : type2;
5229 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5230 /* XXX: test structure compatibility */
5231 type = bt1 == VT_STRUCT ? type1 : type2;
5232 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5233 /* NOTE: as an extension, we accept void on only one side */
5234 type.t = VT_VOID;
5235 } else {
5236 /* integer operations */
5237 type.t = VT_INT;
5238 /* convert to unsigned if it does not fit in an integer */
5239 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5240 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5241 type.t |= VT_UNSIGNED;
5243 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5244 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5245 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5246 islv &= c < 0;
5248 /* now we convert second operand */
5249 if (c != 1) {
5250 gen_cast(&type);
5251 if (islv) {
5252 mk_pointer(&vtop->type);
5253 gaddrof();
5254 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5255 gaddrof();
5258 rc = RC_INT;
5259 if (is_float(type.t)) {
5260 rc = RC_FLOAT;
5261 #ifdef TCC_TARGET_X86_64
5262 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5263 rc = RC_ST0;
5265 #endif
5266 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5267 /* for long longs, we use fixed registers to avoid having
5268 to handle a complicated move */
5269 rc = RC_IRET;
5272 tt = r2 = 0;
5273 if (c < 0) {
5274 r2 = gv(rc);
5275 tt = gjmp(0);
5277 gsym(u);
5279 /* this is horrible, but we must also convert first
5280 operand */
5281 if (c != 0) {
5282 *vtop = sv;
5283 gen_cast(&type);
5284 if (islv) {
5285 mk_pointer(&vtop->type);
5286 gaddrof();
5287 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5288 gaddrof();
5291 if (c < 0) {
5292 r1 = gv(rc);
5293 move_reg(r2, r1, type.t);
5294 vtop->r = r2;
5295 gsym(tt);
5296 if (islv)
5297 indir();
5303 static void expr_eq(void)
5305 int t;
5307 expr_cond();
5308 if (tok == '=' ||
5309 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5310 tok == TOK_A_XOR || tok == TOK_A_OR ||
5311 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5312 test_lvalue();
5313 t = tok;
5314 next();
5315 if (t == '=') {
5316 expr_eq();
5317 } else {
5318 vdup();
5319 expr_eq();
5320 gen_op(t & 0x7f);
5322 vstore();
5326 ST_FUNC void gexpr(void)
5328 while (1) {
5329 expr_eq();
5330 if (tok != ',')
5331 break;
5332 vpop();
5333 next();
5337 /* parse an expression and return its type without any side effect. */
5338 static void expr_type(CType *type)
5341 nocode_wanted++;
5342 gexpr();
5343 *type = vtop->type;
5344 vpop();
5345 nocode_wanted--;
5348 /* parse a unary expression and return its type without any side
5349 effect. */
5350 static void unary_type(CType *type)
5352 nocode_wanted++;
5353 unary();
5354 *type = vtop->type;
5355 vpop();
5356 nocode_wanted--;
5359 /* parse a constant expression and return value in vtop. */
5360 static void expr_const1(void)
5362 const_wanted++;
5363 expr_cond();
5364 const_wanted--;
5367 /* parse an integer constant and return its value. */
5368 static inline int64_t expr_const64(void)
5370 int64_t c;
5371 expr_const1();
5372 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5373 expect("constant expression");
5374 c = vtop->c.i;
5375 vpop();
5376 return c;
5379 /* parse an integer constant and return its value.
5380 Complain if it doesn't fit 32bit (signed or unsigned). */
5381 ST_FUNC int expr_const(void)
5383 int c;
5384 int64_t wc = expr_const64();
5385 c = wc;
5386 if (c != wc && (unsigned)c != wc)
5387 tcc_error("constant exceeds 32 bit");
5388 return c;
5391 /* return the label token if current token is a label, otherwise
5392 return zero */
5393 static int is_label(void)
5395 int last_tok;
5397 /* fast test first */
5398 if (tok < TOK_UIDENT)
5399 return 0;
5400 /* no need to save tokc because tok is an identifier */
5401 last_tok = tok;
5402 next();
5403 if (tok == ':') {
5404 next();
5405 return last_tok;
5406 } else {
5407 unget_tok(last_tok);
5408 return 0;
5412 static void label_or_decl(int l)
5414 int last_tok;
5416 /* fast test first */
5417 if (tok >= TOK_UIDENT)
5419 /* no need to save tokc because tok is an identifier */
5420 last_tok = tok;
5421 next();
5422 if (tok == ':') {
5423 unget_tok(last_tok);
5424 return;
5426 unget_tok(last_tok);
5428 decl(l);
5431 #ifndef TCC_TARGET_ARM64
5432 static void gfunc_return(CType *func_type)
5434 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5435 CType type, ret_type;
5436 int ret_align, ret_nregs, regsize;
5437 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5438 &ret_align, &regsize);
5439 if (0 == ret_nregs) {
5440 /* if returning structure, must copy it to implicit
5441 first pointer arg location */
5442 type = *func_type;
5443 mk_pointer(&type);
5444 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5445 indir();
5446 vswap();
5447 /* copy structure value to pointer */
5448 vstore();
5449 } else {
5450 /* returning structure packed into registers */
5451 int r, size, addr, align;
5452 size = type_size(func_type,&align);
5453 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5454 (vtop->c.i & (ret_align-1)))
5455 && (align & (ret_align-1))) {
5456 loc = (loc - size) & -ret_align;
5457 addr = loc;
5458 type = *func_type;
5459 vset(&type, VT_LOCAL | VT_LVAL, addr);
5460 vswap();
5461 vstore();
5462 vpop();
5463 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5465 vtop->type = ret_type;
5466 if (is_float(ret_type.t))
5467 r = rc_fret(ret_type.t);
5468 else
5469 r = RC_IRET;
5471 if (ret_nregs == 1)
5472 gv(r);
5473 else {
5474 for (;;) {
5475 vdup();
5476 gv(r);
5477 vpop();
5478 if (--ret_nregs == 0)
5479 break;
5480 /* We assume that when a structure is returned in multiple
5481 registers, their classes are consecutive values of the
5482 suite s(n) = 2^n */
5483 r <<= 1;
5484 vtop->c.i += regsize;
5488 } else if (is_float(func_type->t)) {
5489 gv(rc_fret(func_type->t));
5490 } else {
5491 gv(RC_IRET);
5493 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5495 #endif
5497 static int case_cmp(const void *pa, const void *pb)
5499 int64_t a = (*(struct case_t**) pa)->v1;
5500 int64_t b = (*(struct case_t**) pb)->v1;
5501 return a < b ? -1 : a > b;
5504 static void gcase(struct case_t **base, int len, int *bsym)
5506 struct case_t *p;
5507 int e;
5508 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5509 gv(RC_INT);
5510 while (len > 4) {
5511 /* binary search */
5512 p = base[len/2];
5513 vdup();
5514 if (ll)
5515 vpushll(p->v2);
5516 else
5517 vpushi(p->v2);
5518 gen_op(TOK_LE);
5519 e = gtst(1, 0);
5520 vdup();
5521 if (ll)
5522 vpushll(p->v1);
5523 else
5524 vpushi(p->v1);
5525 gen_op(TOK_GE);
5526 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5527 /* x < v1 */
5528 gcase(base, len/2, bsym);
5529 if (cur_switch->def_sym)
5530 gjmp_addr(cur_switch->def_sym);
5531 else
5532 *bsym = gjmp(*bsym);
5533 /* x > v2 */
5534 gsym(e);
5535 e = len/2 + 1;
5536 base += e; len -= e;
5538 /* linear scan */
5539 while (len--) {
5540 p = *base++;
5541 vdup();
5542 if (ll)
5543 vpushll(p->v2);
5544 else
5545 vpushi(p->v2);
5546 if (p->v1 == p->v2) {
5547 gen_op(TOK_EQ);
5548 gtst_addr(0, p->sym);
5549 } else {
5550 gen_op(TOK_LE);
5551 e = gtst(1, 0);
5552 vdup();
5553 if (ll)
5554 vpushll(p->v1);
5555 else
5556 vpushi(p->v1);
5557 gen_op(TOK_GE);
5558 gtst_addr(0, p->sym);
5559 gsym(e);
5564 static void block(int *bsym, int *csym, int is_expr)
5566 int a, b, c, d, cond;
5567 Sym *s;
5569 /* generate line number info */
5570 if (tcc_state->do_debug &&
5571 (last_line_num != file->line_num || last_ind != ind)) {
5572 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
5573 last_ind = ind;
5574 last_line_num = file->line_num;
5577 if (is_expr) {
5578 /* default return value is (void) */
5579 vpushi(0);
5580 vtop->type.t = VT_VOID;
5583 if (tok == TOK_IF) {
5584 /* if test */
5585 int saved_nocode_wanted = nocode_wanted;
5586 next();
5587 skip('(');
5588 gexpr();
5589 skip(')');
5590 cond = condition_3way();
5591 if (cond == 1)
5592 a = 0, vpop();
5593 else
5594 a = gvtst(1, 0);
5595 if (cond == 0)
5596 nocode_wanted |= 0x20000000;
5597 block(bsym, csym, 0);
5598 if (cond != 1)
5599 nocode_wanted = saved_nocode_wanted;
5600 c = tok;
5601 if (c == TOK_ELSE) {
5602 next();
5603 d = gjmp(0);
5604 gsym(a);
5605 if (cond == 1)
5606 nocode_wanted |= 0x20000000;
5607 block(bsym, csym, 0);
5608 gsym(d); /* patch else jmp */
5609 if (cond != 0)
5610 nocode_wanted = saved_nocode_wanted;
5611 } else
5612 gsym(a);
5613 } else if (tok == TOK_WHILE) {
5614 int saved_nocode_wanted;
5615 nocode_wanted &= ~0x20000000;
5616 next();
5617 d = ind;
5618 vla_sp_restore();
5619 skip('(');
5620 gexpr();
5621 skip(')');
5622 a = gvtst(1, 0);
5623 b = 0;
5624 ++local_scope;
5625 saved_nocode_wanted = nocode_wanted;
5626 block(&a, &b, 0);
5627 nocode_wanted = saved_nocode_wanted;
5628 --local_scope;
5629 gjmp_addr(d);
5630 gsym(a);
5631 gsym_addr(b, d);
5632 } else if (tok == '{') {
5633 Sym *llabel;
5634 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5636 next();
5637 /* record local declaration stack position */
5638 s = local_stack;
5639 llabel = local_label_stack;
5640 ++local_scope;
5642 /* handle local labels declarations */
5643 if (tok == TOK_LABEL) {
5644 next();
5645 for(;;) {
5646 if (tok < TOK_UIDENT)
5647 expect("label identifier");
5648 label_push(&local_label_stack, tok, LABEL_DECLARED);
5649 next();
5650 if (tok == ',') {
5651 next();
5652 } else {
5653 skip(';');
5654 break;
5658 while (tok != '}') {
5659 label_or_decl(VT_LOCAL);
5660 if (tok != '}') {
5661 if (is_expr)
5662 vpop();
5663 block(bsym, csym, is_expr);
5666 /* pop locally defined labels */
5667 label_pop(&local_label_stack, llabel);
5668 /* pop locally defined symbols */
5669 --local_scope;
5670 /* In the is_expr case (a statement expression is finished here),
5671 vtop might refer to symbols on the local_stack. Either via the
5672 type or via vtop->sym. We can't pop those nor any that in turn
5673 might be referred to. To make it easier we don't roll back
5674 any symbols in that case; some upper level call to block() will
5675 do that. We do have to remove such symbols from the lookup
5676 tables, though. sym_pop will do that. */
5677 sym_pop(&local_stack, s, is_expr);
5679 /* Pop VLA frames and restore stack pointer if required */
5680 if (vlas_in_scope > saved_vlas_in_scope) {
5681 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5682 vla_sp_restore();
5684 vlas_in_scope = saved_vlas_in_scope;
5686 next();
5687 } else if (tok == TOK_RETURN) {
5688 next();
5689 if (tok != ';') {
5690 gexpr();
5691 gen_assign_cast(&func_vt);
5692 gfunc_return(&func_vt);
5694 skip(';');
5695 /* jump unless last stmt in top-level block */
5696 if (tok != '}' || local_scope != 1)
5697 rsym = gjmp(rsym);
5698 nocode_wanted |= 0x20000000;
5699 } else if (tok == TOK_BREAK) {
5700 /* compute jump */
5701 if (!bsym)
5702 tcc_error("cannot break");
5703 *bsym = gjmp(*bsym);
5704 next();
5705 skip(';');
5706 nocode_wanted |= 0x20000000;
5707 } else if (tok == TOK_CONTINUE) {
5708 /* compute jump */
5709 if (!csym)
5710 tcc_error("cannot continue");
5711 vla_sp_restore_root();
5712 *csym = gjmp(*csym);
5713 next();
5714 skip(';');
5715 } else if (tok == TOK_FOR) {
5716 int e;
5717 int saved_nocode_wanted;
5718 nocode_wanted &= ~0x20000000;
5719 next();
5720 skip('(');
5721 s = local_stack;
5722 ++local_scope;
5723 if (tok != ';') {
5724 /* c99 for-loop init decl? */
5725 if (!decl0(VT_LOCAL, 1)) {
5726 /* no, regular for-loop init expr */
5727 gexpr();
5728 vpop();
5731 skip(';');
5732 d = ind;
5733 c = ind;
5734 vla_sp_restore();
5735 a = 0;
5736 b = 0;
5737 if (tok != ';') {
5738 gexpr();
5739 a = gvtst(1, 0);
5741 skip(';');
5742 if (tok != ')') {
5743 e = gjmp(0);
5744 c = ind;
5745 vla_sp_restore();
5746 gexpr();
5747 vpop();
5748 gjmp_addr(d);
5749 gsym(e);
5751 skip(')');
5752 saved_nocode_wanted = nocode_wanted;
5753 block(&a, &b, 0);
5754 nocode_wanted = saved_nocode_wanted;
5755 gjmp_addr(c);
5756 gsym(a);
5757 gsym_addr(b, c);
5758 --local_scope;
5759 sym_pop(&local_stack, s, 0);
5761 } else
5762 if (tok == TOK_DO) {
5763 int saved_nocode_wanted;
5764 nocode_wanted &= ~0x20000000;
5765 next();
5766 a = 0;
5767 b = 0;
5768 d = ind;
5769 vla_sp_restore();
5770 saved_nocode_wanted = nocode_wanted;
5771 block(&a, &b, 0);
5772 skip(TOK_WHILE);
5773 skip('(');
5774 gsym(b);
5775 gexpr();
5776 c = gvtst(0, 0);
5777 gsym_addr(c, d);
5778 nocode_wanted = saved_nocode_wanted;
5779 skip(')');
5780 gsym(a);
5781 skip(';');
5782 } else
5783 if (tok == TOK_SWITCH) {
5784 struct switch_t *saved, sw;
5785 int saved_nocode_wanted = nocode_wanted;
5786 SValue switchval;
5787 next();
5788 skip('(');
5789 gexpr();
5790 skip(')');
5791 switchval = *vtop--;
5792 a = 0;
5793 b = gjmp(0); /* jump to first case */
5794 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
5795 saved = cur_switch;
5796 cur_switch = &sw;
5797 block(&a, csym, 0);
5798 nocode_wanted = saved_nocode_wanted;
5799 a = gjmp(a); /* add implicit break */
5800 /* case lookup */
5801 gsym(b);
5802 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
5803 for (b = 1; b < sw.n; b++)
5804 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
5805 tcc_error("duplicate case value");
5806 /* Our switch table sorting is signed, so the compared
5807 value needs to be as well when it's 64bit. */
5808 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
5809 switchval.type.t &= ~VT_UNSIGNED;
5810 vpushv(&switchval);
5811 gcase(sw.p, sw.n, &a);
5812 vpop();
5813 if (sw.def_sym)
5814 gjmp_addr(sw.def_sym);
5815 dynarray_reset(&sw.p, &sw.n);
5816 cur_switch = saved;
5817 /* break label */
5818 gsym(a);
5819 } else
5820 if (tok == TOK_CASE) {
5821 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
5822 if (!cur_switch)
5823 expect("switch");
5824 nocode_wanted &= ~0x20000000;
5825 next();
5826 cr->v1 = cr->v2 = expr_const64();
5827 if (gnu_ext && tok == TOK_DOTS) {
5828 next();
5829 cr->v2 = expr_const64();
5830 if (cr->v2 < cr->v1)
5831 tcc_warning("empty case range");
5833 cr->sym = ind;
5834 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
5835 skip(':');
5836 is_expr = 0;
5837 goto block_after_label;
5838 } else
5839 if (tok == TOK_DEFAULT) {
5840 next();
5841 skip(':');
5842 if (!cur_switch)
5843 expect("switch");
5844 if (cur_switch->def_sym)
5845 tcc_error("too many 'default'");
5846 cur_switch->def_sym = ind;
5847 is_expr = 0;
5848 goto block_after_label;
5849 } else
5850 if (tok == TOK_GOTO) {
5851 next();
5852 if (tok == '*' && gnu_ext) {
5853 /* computed goto */
5854 next();
5855 gexpr();
5856 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5857 expect("pointer");
5858 ggoto();
5859 } else if (tok >= TOK_UIDENT) {
5860 s = label_find(tok);
5861 /* put forward definition if needed */
5862 if (!s) {
5863 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5864 } else {
5865 if (s->r == LABEL_DECLARED)
5866 s->r = LABEL_FORWARD;
5868 vla_sp_restore_root();
5869 if (s->r & LABEL_FORWARD)
5870 s->jnext = gjmp(s->jnext);
5871 else
5872 gjmp_addr(s->jnext);
5873 next();
5874 } else {
5875 expect("label identifier");
5877 skip(';');
5878 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5879 asm_instr();
5880 } else {
5881 b = is_label();
5882 if (b) {
5883 /* label case */
5884 s = label_find(b);
5885 if (s) {
5886 if (s->r == LABEL_DEFINED)
5887 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5888 gsym(s->jnext);
5889 s->r = LABEL_DEFINED;
5890 } else {
5891 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5893 s->jnext = ind;
5894 vla_sp_restore();
5895 /* we accept this, but it is a mistake */
5896 block_after_label:
5897 nocode_wanted &= ~0x20000000;
5898 if (tok == '}') {
5899 tcc_warning("deprecated use of label at end of compound statement");
5900 } else {
5901 if (is_expr)
5902 vpop();
5903 block(bsym, csym, is_expr);
5905 } else {
5906 /* expression case */
5907 if (tok != ';') {
5908 if (is_expr) {
5909 vpop();
5910 gexpr();
5911 } else {
5912 gexpr();
5913 vpop();
5916 skip(';');
5921 #define EXPR_CONST 1
5922 #define EXPR_ANY 2
5924 static void parse_init_elem(int expr_type)
5926 int saved_global_expr;
5927 switch(expr_type) {
5928 case EXPR_CONST:
5929 /* compound literals must be allocated globally in this case */
5930 saved_global_expr = global_expr;
5931 global_expr = 1;
5932 expr_const1();
5933 global_expr = saved_global_expr;
5934 /* NOTE: symbols are accepted */
5935 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5936 tcc_error("initializer element is not constant");
5937 break;
5938 case EXPR_ANY:
5939 expr_eq();
5940 break;
5944 /* t is the array or struct type. c is the array or struct
5945 address. cur_field is the pointer to the current
5946 value, for arrays the 'c' member contains the current start
5947 index and the 'r' contains the end index (in case of range init).
5948 'size_only' is true if only size info is needed (only used
5949 in arrays) */
5950 static void decl_designator(CType *type, Section *sec, unsigned long c,
5951 Sym **cur_field, int size_only)
5953 Sym *s, *f;
5954 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5955 CType type1;
5957 notfirst = 0;
5958 elem_size = 0;
5959 nb_elems = 1;
5960 if (gnu_ext && (l = is_label()) != 0)
5961 goto struct_field;
5962 while (tok == '[' || tok == '.') {
5963 if (tok == '[') {
5964 if (!(type->t & VT_ARRAY))
5965 expect("array type");
5966 s = type->ref;
5967 next();
5968 index = expr_const();
5969 if (index < 0 || (s->c >= 0 && index >= s->c))
5970 tcc_error("invalid index");
5971 if (tok == TOK_DOTS && gnu_ext) {
5972 next();
5973 index_last = expr_const();
5974 if (index_last < 0 ||
5975 (s->c >= 0 && index_last >= s->c) ||
5976 index_last < index)
5977 tcc_error("invalid index");
5978 } else {
5979 index_last = index;
5981 skip(']');
5982 if (!notfirst) {
5983 (*cur_field)->c = index;
5984 (*cur_field)->r = index_last;
5986 type = pointed_type(type);
5987 elem_size = type_size(type, &align);
5988 c += index * elem_size;
5989 /* NOTE: we only support ranges for last designator */
5990 nb_elems = index_last - index + 1;
5991 if (nb_elems != 1) {
5992 notfirst = 1;
5993 break;
5995 } else {
5996 next();
5997 l = tok;
5998 next();
5999 struct_field:
6000 if ((type->t & VT_BTYPE) != VT_STRUCT)
6001 expect("struct/union type");
6002 f = find_field(type, l);
6003 if (!f)
6004 expect("field");
6005 if (!notfirst)
6006 *cur_field = f;
6007 /* XXX: fix this mess by using explicit storage field */
6008 type1 = f->type;
6009 type1.t |= (type->t & ~VT_TYPE);
6010 type = &type1;
6011 c += f->c;
6013 notfirst = 1;
6015 if (notfirst) {
6016 if (tok == '=') {
6017 next();
6018 } else {
6019 if (!gnu_ext)
6020 expect("=");
6022 } else {
6023 if (type->t & VT_ARRAY) {
6024 index = (*cur_field)->c;
6025 if (type->ref->c >= 0 && index >= type->ref->c)
6026 tcc_error("index too large");
6027 type = pointed_type(type);
6028 c += index * type_size(type, &align);
6029 } else {
6030 f = *cur_field;
6031 if (!f)
6032 tcc_error("too many field init");
6033 /* XXX: fix this mess by using explicit storage field */
6034 type1 = f->type;
6035 type1.t |= (type->t & ~VT_TYPE);
6036 type = &type1;
6037 c += f->c;
6040 decl_initializer(type, sec, c, 0, size_only);
6042 /* XXX: make it more general */
6043 if (!size_only && nb_elems > 1) {
6044 unsigned long c_end;
6045 uint8_t *src, *dst;
6046 int i;
6048 if (!sec) {
6049 vset(type, VT_LOCAL|VT_LVAL, c);
6050 for (i = 1; i < nb_elems; i++) {
6051 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6052 vswap();
6053 vstore();
6055 vpop();
6056 } else {
6057 c_end = c + nb_elems * elem_size;
6058 if (c_end > sec->data_allocated)
6059 section_realloc(sec, c_end);
6060 src = sec->data + c;
6061 dst = src;
6062 for(i = 1; i < nb_elems; i++) {
6063 dst += elem_size;
6064 memcpy(dst, src, elem_size);
6070 /* store a value or an expression directly in global data or in local array */
6071 static void init_putv(CType *type, Section *sec, unsigned long c)
6073 int bt, bit_pos, bit_size;
6074 void *ptr;
6075 unsigned long long bit_mask;
6076 CType dtype;
6078 dtype = *type;
6079 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6081 if (sec) {
6082 int size, align;
6083 /* XXX: not portable */
6084 /* XXX: generate error if incorrect relocation */
6085 gen_assign_cast(&dtype);
6086 bt = type->t & VT_BTYPE;
6087 size = type_size(type, &align);
6088 if (c + size > sec->data_allocated) {
6089 section_realloc(sec, c + size);
6091 ptr = sec->data + c;
6092 /* XXX: make code faster ? */
6093 if (!(type->t & VT_BITFIELD)) {
6094 bit_pos = 0;
6095 bit_size = PTR_SIZE * 8;
6096 bit_mask = -1LL;
6097 } else {
6098 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
6099 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6100 bit_mask = (1LL << bit_size) - 1;
6102 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6103 vtop->sym->v >= SYM_FIRST_ANOM &&
6104 /* XXX This rejects compount literals like
6105 '(void *){ptr}'. The problem is that '&sym' is
6106 represented the same way, which would be ruled out
6107 by the SYM_FIRST_ANOM check above, but also '"string"'
6108 in 'char *p = "string"' is represented the same
6109 with the type being VT_PTR and the symbol being an
6110 anonymous one. That is, there's no difference in vtop
6111 between '(void *){x}' and '&(void *){x}'. Ignore
6112 pointer typed entities here. Hopefully no real code
6113 will every use compound literals with scalar type. */
6114 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6115 /* These come from compound literals, memcpy stuff over. */
6116 Section *ssec;
6117 ElfW(Sym) *esym;
6118 ElfW_Rel *rel;
6119 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6120 ssec = tcc_state->sections[esym->st_shndx];
6121 memmove (ptr, ssec->data + esym->st_value, size);
6122 if (ssec->reloc) {
6123 /* We need to copy over all memory contents, and that
6124 includes relocations. Use the fact that relocs are
6125 created it order, so look from the end of relocs
6126 until we hit one before the copied region. */
6127 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6128 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6129 while (num_relocs--) {
6130 rel--;
6131 if (rel->r_offset >= esym->st_value + size)
6132 continue;
6133 if (rel->r_offset < esym->st_value)
6134 break;
6135 /* Note: if the same fields are initialized multiple
6136 times (possible with designators) then we possibly
6137 add multiple relocations for the same offset here.
6138 That would lead to wrong code, the last reloc needs
6139 to win. We clean this up later after the whole
6140 initializer is parsed. */
6141 put_elf_reloca(symtab_section, sec,
6142 c + rel->r_offset - esym->st_value,
6143 ELFW(R_TYPE)(rel->r_info),
6144 ELFW(R_SYM)(rel->r_info),
6145 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6146 rel->r_addend
6147 #else
6149 #endif
6153 } else {
6154 if ((vtop->r & VT_SYM) &&
6155 (bt == VT_BYTE ||
6156 bt == VT_SHORT ||
6157 bt == VT_DOUBLE ||
6158 bt == VT_LDOUBLE ||
6159 #if PTR_SIZE == 8
6160 (bt == VT_LLONG && bit_size != 64) ||
6161 bt == VT_INT
6162 #else
6163 bt == VT_LLONG ||
6164 (bt == VT_INT && bit_size != 32)
6165 #endif
6167 tcc_error("initializer element is not computable at load time");
6168 switch(bt) {
6169 /* XXX: when cross-compiling we assume that each type has the
6170 same representation on host and target, which is likely to
6171 be wrong in the case of long double */
6172 case VT_BOOL:
6173 vtop->c.i = (vtop->c.i != 0);
6174 case VT_BYTE:
6175 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6176 break;
6177 case VT_SHORT:
6178 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6179 break;
6180 case VT_DOUBLE:
6181 *(double *)ptr = vtop->c.d;
6182 break;
6183 case VT_LDOUBLE:
6184 if (sizeof(long double) == LDOUBLE_SIZE)
6185 *(long double *)ptr = vtop->c.ld;
6186 else if (sizeof(double) == LDOUBLE_SIZE)
6187 *(double *)ptr = vtop->c.ld;
6188 else
6189 tcc_error("can't cross compile long double constants");
6190 break;
6191 #if PTR_SIZE != 8
6192 case VT_LLONG:
6193 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6194 break;
6195 #else
6196 case VT_LLONG:
6197 #endif
6198 case VT_PTR:
6200 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
6201 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6202 if (vtop->r & VT_SYM)
6203 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6204 else
6205 *(addr_t *)ptr |= val;
6206 #else
6207 if (vtop->r & VT_SYM)
6208 greloc(sec, vtop->sym, c, R_DATA_PTR);
6209 *(addr_t *)ptr |= val;
6210 #endif
6211 break;
6213 default:
6215 int val = (vtop->c.i & bit_mask) << bit_pos;
6216 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6217 if (vtop->r & VT_SYM)
6218 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6219 else
6220 *(int *)ptr |= val;
6221 #else
6222 if (vtop->r & VT_SYM)
6223 greloc(sec, vtop->sym, c, R_DATA_PTR);
6224 *(int *)ptr |= val;
6225 #endif
6226 break;
6230 vtop--;
6231 } else {
6232 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6233 vswap();
6234 vstore();
6235 vpop();
6239 /* put zeros for variable based init */
6240 static void init_putz(Section *sec, unsigned long c, int size)
6242 if (sec) {
6243 /* nothing to do because globals are already set to zero */
6244 } else {
6245 vpush_global_sym(&func_old_type, TOK_memset);
6246 vseti(VT_LOCAL, c);
6247 #ifdef TCC_TARGET_ARM
6248 vpushs(size);
6249 vpushi(0);
6250 #else
6251 vpushi(0);
6252 vpushs(size);
6253 #endif
6254 gfunc_call(3);
6258 /* 't' contains the type and storage info. 'c' is the offset of the
6259 object in section 'sec'. If 'sec' is NULL, it means stack based
6260 allocation. 'first' is true if array '{' must be read (multi
6261 dimension implicit array init handling). 'size_only' is true if
6262 size only evaluation is wanted (only for arrays). */
6263 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6264 int first, int size_only)
6266 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
6267 int size1, align1;
6268 int have_elem;
6269 Sym *s, *f;
6270 Sym indexsym;
6271 CType *t1;
6273 /* If we currently are at an '}' or ',' we have read an initializer
6274 element in one of our callers, and not yet consumed it. */
6275 have_elem = tok == '}' || tok == ',';
6276 if (!have_elem && tok != '{' &&
6277 /* In case of strings we have special handling for arrays, so
6278 don't consume them as initializer value (which would commit them
6279 to some anonymous symbol). */
6280 tok != TOK_LSTR && tok != TOK_STR &&
6281 !size_only) {
6282 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6283 have_elem = 1;
6286 if (have_elem &&
6287 !(type->t & VT_ARRAY) &&
6288 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6289 The source type might have VT_CONSTANT set, which is
6290 of course assignable to non-const elements. */
6291 is_compatible_parameter_types(type, &vtop->type)) {
6292 init_putv(type, sec, c);
6293 } else if (type->t & VT_ARRAY) {
6294 s = type->ref;
6295 n = s->c;
6296 array_length = 0;
6297 t1 = pointed_type(type);
6298 size1 = type_size(t1, &align1);
6300 no_oblock = 1;
6301 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6302 tok == '{') {
6303 if (tok != '{')
6304 tcc_error("character array initializer must be a literal,"
6305 " optionally enclosed in braces");
6306 skip('{');
6307 no_oblock = 0;
6310 /* only parse strings here if correct type (otherwise: handle
6311 them as ((w)char *) expressions */
6312 if ((tok == TOK_LSTR &&
6313 #ifdef TCC_TARGET_PE
6314 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6315 #else
6316 (t1->t & VT_BTYPE) == VT_INT
6317 #endif
6318 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6319 while (tok == TOK_STR || tok == TOK_LSTR) {
6320 int cstr_len, ch;
6322 /* compute maximum number of chars wanted */
6323 if (tok == TOK_STR)
6324 cstr_len = tokc.str.size;
6325 else
6326 cstr_len = tokc.str.size / sizeof(nwchar_t);
6327 cstr_len--;
6328 nb = cstr_len;
6329 if (n >= 0 && nb > (n - array_length))
6330 nb = n - array_length;
6331 if (!size_only) {
6332 if (cstr_len > nb)
6333 tcc_warning("initializer-string for array is too long");
6334 /* in order to go faster for common case (char
6335 string in global variable, we handle it
6336 specifically */
6337 if (sec && tok == TOK_STR && size1 == 1) {
6338 memcpy(sec->data + c + array_length, tokc.str.data, nb);
6339 } else {
6340 for(i=0;i<nb;i++) {
6341 if (tok == TOK_STR)
6342 ch = ((unsigned char *)tokc.str.data)[i];
6343 else
6344 ch = ((nwchar_t *)tokc.str.data)[i];
6345 vpushi(ch);
6346 init_putv(t1, sec, c + (array_length + i) * size1);
6350 array_length += nb;
6351 next();
6353 /* only add trailing zero if enough storage (no
6354 warning in this case since it is standard) */
6355 if (n < 0 || array_length < n) {
6356 if (!size_only) {
6357 vpushi(0);
6358 init_putv(t1, sec, c + (array_length * size1));
6360 array_length++;
6362 } else {
6363 indexsym.c = 0;
6364 indexsym.r = 0;
6365 f = &indexsym;
6367 do_init_list:
6368 while (tok != '}' || have_elem) {
6369 decl_designator(type, sec, c, &f, size_only);
6370 have_elem = 0;
6371 index = f->c;
6372 /* must put zero in holes (note that doing it that way
6373 ensures that it even works with designators) */
6374 if (!size_only && array_length < index) {
6375 init_putz(sec, c + array_length * size1,
6376 (index - array_length) * size1);
6378 if (type->t & VT_ARRAY) {
6379 index = indexsym.c = ++indexsym.r;
6380 } else {
6381 index = index + type_size(&f->type, &align1);
6382 if (s->type.t == TOK_UNION)
6383 f = NULL;
6384 else
6385 f = f->next;
6387 if (index > array_length)
6388 array_length = index;
6390 if (type->t & VT_ARRAY) {
6391 /* special test for multi dimensional arrays (may not
6392 be strictly correct if designators are used at the
6393 same time) */
6394 if (no_oblock && index >= n)
6395 break;
6396 } else {
6397 if (no_oblock && f == NULL)
6398 break;
6400 if (tok == '}')
6401 break;
6402 skip(',');
6405 /* put zeros at the end */
6406 if (!size_only && array_length < n) {
6407 init_putz(sec, c + array_length * size1,
6408 (n - array_length) * size1);
6410 if (!no_oblock)
6411 skip('}');
6412 /* patch type size if needed, which happens only for array types */
6413 if (n < 0)
6414 s->c = array_length;
6415 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6416 size1 = 1;
6417 no_oblock = 1;
6418 if (first || tok == '{') {
6419 skip('{');
6420 no_oblock = 0;
6422 s = type->ref;
6423 f = s->next;
6424 array_length = 0;
6425 n = s->c;
6426 goto do_init_list;
6427 } else if (tok == '{') {
6428 next();
6429 decl_initializer(type, sec, c, first, size_only);
6430 skip('}');
6431 } else if (size_only) {
6432 /* If we supported only ISO C we wouldn't have to accept calling
6433 this on anything than an array size_only==1 (and even then
6434 only on the outermost level, so no recursion would be needed),
6435 because initializing a flex array member isn't supported.
6436 But GNU C supports it, so we need to recurse even into
6437 subfields of structs and arrays when size_only is set. */
6438 /* just skip expression */
6439 parlevel = parlevel1 = 0;
6440 while ((parlevel > 0 || parlevel1 > 0 ||
6441 (tok != '}' && tok != ',')) && tok != -1) {
6442 if (tok == '(')
6443 parlevel++;
6444 else if (tok == ')') {
6445 if (parlevel == 0 && parlevel1 == 0)
6446 break;
6447 parlevel--;
6449 else if (tok == '{')
6450 parlevel1++;
6451 else if (tok == '}') {
6452 if (parlevel == 0 && parlevel1 == 0)
6453 break;
6454 parlevel1--;
6456 next();
6458 } else {
6459 if (!have_elem) {
6460 /* This should happen only when we haven't parsed
6461 the init element above for fear of committing a
6462 string constant to memory too early. */
6463 if (tok != TOK_STR && tok != TOK_LSTR)
6464 expect("string constant");
6465 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6467 init_putv(type, sec, c);
6471 /* parse an initializer for type 't' if 'has_init' is non zero, and
6472 allocate space in local or global data space ('r' is either
6473 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6474 variable 'v' of scope 'scope' is declared before initializers
6475 are parsed. If 'v' is zero, then a reference to the new object
6476 is put in the value stack. If 'has_init' is 2, a special parsing
6477 is done to handle string constants. */
6478 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6479 int has_init, int v, int scope)
6481 int size, align, addr, data_offset;
6482 int level;
6483 ParseState saved_parse_state = {0};
6484 TokenString *init_str = NULL;
6485 Section *sec;
6486 Sym *flexible_array;
6488 flexible_array = NULL;
6489 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6490 Sym *field = type->ref->next;
6491 if (field) {
6492 while (field->next)
6493 field = field->next;
6494 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6495 flexible_array = field;
6499 size = type_size(type, &align);
6500 /* If unknown size, we must evaluate it before
6501 evaluating initializers because
6502 initializers can generate global data too
6503 (e.g. string pointers or ISOC99 compound
6504 literals). It also simplifies local
6505 initializers handling */
6506 if (size < 0 || (flexible_array && has_init)) {
6507 if (!has_init)
6508 tcc_error("unknown type size");
6509 /* get all init string */
6510 init_str = tok_str_alloc();
6511 if (has_init == 2) {
6512 /* only get strings */
6513 while (tok == TOK_STR || tok == TOK_LSTR) {
6514 tok_str_add_tok(init_str);
6515 next();
6517 } else {
6518 level = 0;
6519 while (level > 0 || (tok != ',' && tok != ';')) {
6520 if (tok < 0)
6521 tcc_error("unexpected end of file in initializer");
6522 tok_str_add_tok(init_str);
6523 if (tok == '{')
6524 level++;
6525 else if (tok == '}') {
6526 level--;
6527 if (level <= 0) {
6528 next();
6529 break;
6532 next();
6535 tok_str_add(init_str, -1);
6536 tok_str_add(init_str, 0);
6538 /* compute size */
6539 save_parse_state(&saved_parse_state);
6541 begin_macro(init_str, 1);
6542 next();
6543 decl_initializer(type, NULL, 0, 1, 1);
6544 /* prepare second initializer parsing */
6545 macro_ptr = init_str->str;
6546 next();
6548 /* if still unknown size, error */
6549 size = type_size(type, &align);
6550 if (size < 0)
6551 tcc_error("unknown type size");
6553 /* If there's a flex member and it was used in the initializer
6554 adjust size. */
6555 if (flexible_array &&
6556 flexible_array->type.ref->c > 0)
6557 size += flexible_array->type.ref->c
6558 * pointed_size(&flexible_array->type);
6559 /* take into account specified alignment if bigger */
6560 if (ad->a.aligned) {
6561 int speca = 1 << (ad->a.aligned - 1);
6562 if (speca > align)
6563 align = speca;
6564 } else if (ad->a.packed) {
6565 align = 1;
6567 if ((r & VT_VALMASK) == VT_LOCAL) {
6568 sec = NULL;
6569 #ifdef CONFIG_TCC_BCHECK
6570 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6571 loc--;
6573 #endif
6574 loc = (loc - size) & -align;
6575 addr = loc;
6576 #ifdef CONFIG_TCC_BCHECK
6577 /* handles bounds */
6578 /* XXX: currently, since we do only one pass, we cannot track
6579 '&' operators, so we add only arrays */
6580 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6581 addr_t *bounds_ptr;
6582 /* add padding between regions */
6583 loc--;
6584 /* then add local bound info */
6585 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6586 bounds_ptr[0] = addr;
6587 bounds_ptr[1] = size;
6589 #endif
6590 if (v) {
6591 /* local variable */
6592 #ifdef CONFIG_TCC_ASM
6593 if (ad->asm_label) {
6594 int reg = asm_parse_regvar(ad->asm_label);
6595 if (reg >= 0)
6596 r = (r & ~VT_VALMASK) | reg;
6598 #endif
6599 sym_push(v, type, r, addr);
6600 } else {
6601 /* push local reference */
6602 vset(type, r, addr);
6604 } else {
6605 Sym *sym;
6607 sym = NULL;
6608 if (v && scope == VT_CONST) {
6609 /* see if the symbol was already defined */
6610 sym = sym_find(v);
6611 if (sym) {
6612 if (!is_compatible_types(&sym->type, type))
6613 tcc_error("incompatible types for redefinition of '%s'",
6614 get_tok_str(v, NULL));
6615 if (sym->type.t & VT_EXTERN) {
6616 /* if the variable is extern, it was not allocated */
6617 sym->type.t &= ~VT_EXTERN;
6618 /* set array size if it was omitted in extern
6619 declaration */
6620 if ((sym->type.t & VT_ARRAY) &&
6621 sym->type.ref->c < 0 &&
6622 type->ref->c >= 0)
6623 sym->type.ref->c = type->ref->c;
6624 } else {
6625 /* we accept several definitions of the same
6626 global variable. this is tricky, because we
6627 must play with the SHN_COMMON type of the symbol */
6628 /* XXX: should check if the variable was already
6629 initialized. It is incorrect to initialized it
6630 twice */
6631 /* no init data, we won't add more to the symbol */
6632 if (!has_init)
6633 goto no_alloc;
6638 /* allocate symbol in corresponding section */
6639 sec = ad->section;
6640 if (!sec) {
6641 if (has_init)
6642 sec = data_section;
6643 else if (tcc_state->nocommon)
6644 sec = bss_section;
6646 if (sec) {
6647 data_offset = sec->data_offset;
6648 data_offset = (data_offset + align - 1) & -align;
6649 addr = data_offset;
6650 /* very important to increment global pointer at this time
6651 because initializers themselves can create new initializers */
6652 data_offset += size;
6653 #ifdef CONFIG_TCC_BCHECK
6654 /* add padding if bound check */
6655 if (tcc_state->do_bounds_check)
6656 data_offset++;
6657 #endif
6658 sec->data_offset = data_offset;
6659 /* allocate section space to put the data */
6660 if (sec->sh_type != SHT_NOBITS &&
6661 data_offset > sec->data_allocated)
6662 section_realloc(sec, data_offset);
6663 /* align section if needed */
6664 if (align > sec->sh_addralign)
6665 sec->sh_addralign = align;
6666 } else {
6667 addr = 0; /* avoid warning */
6670 if (v) {
6671 if (scope != VT_CONST || !sym) {
6672 sym = sym_push(v, type, r | VT_SYM, 0);
6673 sym->asm_label = ad->asm_label;
6675 /* update symbol definition */
6676 if (sec) {
6677 put_extern_sym(sym, sec, addr, size);
6678 } else {
6679 ElfW(Sym) *esym;
6680 /* put a common area */
6681 put_extern_sym(sym, NULL, align, size);
6682 /* XXX: find a nicer way */
6683 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6684 esym->st_shndx = SHN_COMMON;
6686 } else {
6687 /* push global reference */
6688 sym = get_sym_ref(type, sec, addr, size);
6689 vpushsym(type, sym);
6691 /* patch symbol weakness */
6692 if (type->t & VT_WEAK)
6693 weaken_symbol(sym);
6694 apply_visibility(sym, type);
6695 #ifdef CONFIG_TCC_BCHECK
6696 /* handles bounds now because the symbol must be defined
6697 before for the relocation */
6698 if (tcc_state->do_bounds_check) {
6699 addr_t *bounds_ptr;
6701 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6702 /* then add global bound info */
6703 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6704 bounds_ptr[0] = 0; /* relocated */
6705 bounds_ptr[1] = size;
6707 #endif
6709 if (type->t & VT_VLA) {
6710 int a;
6712 /* save current stack pointer */
6713 if (vlas_in_scope == 0) {
6714 if (vla_sp_root_loc == -1)
6715 vla_sp_root_loc = (loc -= PTR_SIZE);
6716 gen_vla_sp_save(vla_sp_root_loc);
6719 vla_runtime_type_size(type, &a);
6720 gen_vla_alloc(type, a);
6721 gen_vla_sp_save(addr);
6722 vla_sp_loc = addr;
6723 vlas_in_scope++;
6724 } else if (has_init) {
6725 size_t oldreloc_offset = 0;
6726 if (sec && sec->reloc)
6727 oldreloc_offset = sec->reloc->data_offset;
6728 decl_initializer(type, sec, addr, 1, 0);
6729 if (sec && sec->reloc)
6730 squeeze_multi_relocs(sec, oldreloc_offset);
6731 /* patch flexible array member size back to -1, */
6732 /* for possible subsequent similar declarations */
6733 if (flexible_array)
6734 flexible_array->type.ref->c = -1;
6736 no_alloc: ;
6737 /* restore parse state if needed */
6738 if (init_str) {
6739 end_macro();
6740 restore_parse_state(&saved_parse_state);
6744 static void put_func_debug(Sym *sym)
6746 char buf[512];
6748 /* stabs info */
6749 /* XXX: we put here a dummy type */
6750 snprintf(buf, sizeof(buf), "%s:%c1",
6751 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6752 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6753 cur_text_section, sym->c);
6754 /* //gr gdb wants a line at the function */
6755 put_stabn(N_SLINE, 0, file->line_num, 0);
6756 last_ind = 0;
6757 last_line_num = 0;
6760 /* parse an old style function declaration list */
6761 /* XXX: check multiple parameter */
6762 static void func_decl_list(Sym *func_sym)
6764 AttributeDef ad;
6765 int v;
6766 Sym *s;
6767 CType btype, type;
6769 /* parse each declaration */
6770 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6771 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6772 if (!parse_btype(&btype, &ad))
6773 expect("declaration list");
6774 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6775 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6776 tok == ';') {
6777 /* we accept no variable after */
6778 } else {
6779 for(;;) {
6780 type = btype;
6781 type_decl(&type, &ad, &v, TYPE_DIRECT);
6782 /* find parameter in function parameter list */
6783 s = func_sym->next;
6784 while (s != NULL) {
6785 if ((s->v & ~SYM_FIELD) == v)
6786 goto found;
6787 s = s->next;
6789 tcc_error("declaration for parameter '%s' but no such parameter",
6790 get_tok_str(v, NULL));
6791 found:
6792 /* check that no storage specifier except 'register' was given */
6793 if (type.t & VT_STORAGE)
6794 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6795 convert_parameter_type(&type);
6796 /* we can add the type (NOTE: it could be local to the function) */
6797 s->type = type;
6798 /* accept other parameters */
6799 if (tok == ',')
6800 next();
6801 else
6802 break;
6805 skip(';');
6809 /* parse a function defined by symbol 'sym' and generate its code in
6810 'cur_text_section' */
6811 static void gen_function(Sym *sym)
6813 nocode_wanted = 0;
6814 ind = cur_text_section->data_offset;
6815 /* NOTE: we patch the symbol size later */
6816 put_extern_sym(sym, cur_text_section, ind, 0);
6817 funcname = get_tok_str(sym->v, NULL);
6818 func_ind = ind;
6819 /* Initialize VLA state */
6820 vla_sp_loc = -1;
6821 vla_sp_root_loc = -1;
6822 /* put debug symbol */
6823 if (tcc_state->do_debug)
6824 put_func_debug(sym);
6826 /* push a dummy symbol to enable local sym storage */
6827 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6828 local_scope = 1; /* for function parameters */
6829 gfunc_prolog(&sym->type);
6830 local_scope = 0;
6832 rsym = 0;
6833 block(NULL, NULL, 0);
6834 nocode_wanted = 0;
6835 gsym(rsym);
6836 gfunc_epilog();
6837 cur_text_section->data_offset = ind;
6838 label_pop(&global_label_stack, NULL);
6839 /* reset local stack */
6840 local_scope = 0;
6841 sym_pop(&local_stack, NULL, 0);
6842 /* end of function */
6843 /* patch symbol size */
6844 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6845 ind - func_ind;
6846 /* patch symbol weakness (this definition overrules any prototype) */
6847 if (sym->type.t & VT_WEAK)
6848 weaken_symbol(sym);
6849 apply_visibility(sym, &sym->type);
6850 if (tcc_state->do_debug) {
6851 put_stabn(N_FUN, 0, 0, ind - func_ind);
6853 /* It's better to crash than to generate wrong code */
6854 cur_text_section = NULL;
6855 funcname = ""; /* for safety */
6856 func_vt.t = VT_VOID; /* for safety */
6857 func_var = 0; /* for safety */
6858 ind = 0; /* for safety */
6859 nocode_wanted = 1;
6860 check_vstack();
6863 static void gen_inline_functions(TCCState *s)
6865 Sym *sym;
6866 int inline_generated, i, ln;
6867 struct InlineFunc *fn;
6869 ln = file->line_num;
6870 /* iterate while inline function are referenced */
6871 for(;;) {
6872 inline_generated = 0;
6873 for (i = 0; i < s->nb_inline_fns; ++i) {
6874 fn = s->inline_fns[i];
6875 sym = fn->sym;
6876 if (sym && sym->c) {
6877 /* the function was used: generate its code and
6878 convert it to a normal function */
6879 fn->sym = NULL;
6880 if (file)
6881 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6882 sym->type.t &= ~VT_INLINE;
6884 begin_macro(fn->func_str, 1);
6885 next();
6886 cur_text_section = text_section;
6887 gen_function(sym);
6888 end_macro();
6890 inline_generated = 1;
6893 if (!inline_generated)
6894 break;
6896 file->line_num = ln;
6899 ST_FUNC void free_inline_functions(TCCState *s)
6901 int i;
6902 /* free tokens of unused inline functions */
6903 for (i = 0; i < s->nb_inline_fns; ++i) {
6904 struct InlineFunc *fn = s->inline_fns[i];
6905 if (fn->sym)
6906 tok_str_free(fn->func_str);
6908 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
6911 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6912 static int decl0(int l, int is_for_loop_init)
6914 int v, has_init, r;
6915 CType type, btype;
6916 Sym *sym;
6917 AttributeDef ad;
6919 while (1) {
6920 if (!parse_btype(&btype, &ad)) {
6921 if (is_for_loop_init)
6922 return 0;
6923 /* skip redundant ';' */
6924 /* XXX: find more elegant solution */
6925 if (tok == ';') {
6926 next();
6927 continue;
6929 if (l == VT_CONST &&
6930 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6931 /* global asm block */
6932 asm_global_instr();
6933 continue;
6935 /* special test for old K&R protos without explicit int
6936 type. Only accepted when defining global data */
6937 if (l == VT_LOCAL || tok < TOK_UIDENT)
6938 break;
6939 btype.t = VT_INT;
6941 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6942 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6943 tok == ';') {
6944 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6945 int v = btype.ref->v;
6946 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6947 tcc_warning("unnamed struct/union that defines no instances");
6949 next();
6950 continue;
6952 while (1) { /* iterate thru each declaration */
6953 type = btype;
6954 /* If the base type itself was an array type of unspecified
6955 size (like in 'typedef int arr[]; arr x = {1};') then
6956 we will overwrite the unknown size by the real one for
6957 this decl. We need to unshare the ref symbol holding
6958 that size. */
6959 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
6960 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
6962 type_decl(&type, &ad, &v, TYPE_DIRECT);
6963 #if 0
6965 char buf[500];
6966 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6967 printf("type = '%s'\n", buf);
6969 #endif
6970 if ((type.t & VT_BTYPE) == VT_FUNC) {
6971 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6972 tcc_error("function without file scope cannot be static");
6974 /* if old style function prototype, we accept a
6975 declaration list */
6976 sym = type.ref;
6977 if (sym->c == FUNC_OLD)
6978 func_decl_list(sym);
6981 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6982 ad.asm_label = asm_label_instr();
6983 /* parse one last attribute list, after asm label */
6984 parse_attribute(&ad);
6985 if (tok == '{')
6986 expect(";");
6989 if (ad.a.weak)
6990 type.t |= VT_WEAK;
6991 #ifdef TCC_TARGET_PE
6992 if (ad.a.func_import)
6993 type.t |= VT_IMPORT;
6994 if (ad.a.func_export)
6995 type.t |= VT_EXPORT;
6996 #endif
6997 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6999 if (tok == '{') {
7000 if (l == VT_LOCAL)
7001 tcc_error("cannot use local functions");
7002 if ((type.t & VT_BTYPE) != VT_FUNC)
7003 expect("function definition");
7005 /* reject abstract declarators in function definition */
7006 sym = type.ref;
7007 while ((sym = sym->next) != NULL)
7008 if (!(sym->v & ~SYM_FIELD))
7009 expect("identifier");
7011 /* XXX: cannot do better now: convert extern line to static inline */
7012 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
7013 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7015 sym = sym_find(v);
7016 if (sym) {
7017 Sym *ref;
7018 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
7019 goto func_error1;
7021 ref = sym->type.ref;
7023 /* use func_call from prototype if not defined */
7024 if (ref->a.func_call != FUNC_CDECL
7025 && type.ref->a.func_call == FUNC_CDECL)
7026 type.ref->a.func_call = ref->a.func_call;
7028 /* use export from prototype */
7029 if (ref->a.func_export)
7030 type.ref->a.func_export = 1;
7032 /* use static from prototype */
7033 if (sym->type.t & VT_STATIC)
7034 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7036 /* If the definition has no visibility use the
7037 one from prototype. */
7038 if (! (type.t & VT_VIS_MASK))
7039 type.t |= sym->type.t & VT_VIS_MASK;
7041 if (!is_compatible_types(&sym->type, &type)) {
7042 func_error1:
7043 tcc_error("incompatible types for redefinition of '%s'",
7044 get_tok_str(v, NULL));
7046 if (ref->a.func_body)
7047 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
7048 /* if symbol is already defined, then put complete type */
7049 sym->type = type;
7051 } else {
7052 /* put function symbol */
7053 sym = global_identifier_push(v, type.t, 0);
7054 sym->type.ref = type.ref;
7057 sym->type.ref->a.func_body = 1;
7058 sym->r = VT_SYM | VT_CONST;
7060 /* static inline functions are just recorded as a kind
7061 of macro. Their code will be emitted at the end of
7062 the compilation unit only if they are used */
7063 if ((type.t & (VT_INLINE | VT_STATIC)) ==
7064 (VT_INLINE | VT_STATIC)) {
7065 int block_level;
7066 struct InlineFunc *fn;
7067 const char *filename;
7069 filename = file ? file->filename : "";
7070 fn = tcc_malloc(sizeof *fn + strlen(filename));
7071 strcpy(fn->filename, filename);
7072 fn->sym = sym;
7073 fn->func_str = tok_str_alloc();
7075 block_level = 0;
7076 for(;;) {
7077 int t;
7078 if (tok == TOK_EOF)
7079 tcc_error("unexpected end of file");
7080 tok_str_add_tok(fn->func_str);
7081 t = tok;
7082 next();
7083 if (t == '{') {
7084 block_level++;
7085 } else if (t == '}') {
7086 block_level--;
7087 if (block_level == 0)
7088 break;
7091 tok_str_add(fn->func_str, -1);
7092 tok_str_add(fn->func_str, 0);
7093 dynarray_add(&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
7095 } else {
7096 /* compute text section */
7097 cur_text_section = ad.section;
7098 if (!cur_text_section)
7099 cur_text_section = text_section;
7100 gen_function(sym);
7102 break;
7103 } else {
7104 if (btype.t & VT_TYPEDEF) {
7105 /* save typedefed type */
7106 /* XXX: test storage specifiers ? */
7107 sym = sym_find(v);
7108 if (sym && sym->scope == local_scope) {
7109 if (!is_compatible_types(&sym->type, &type)
7110 || !(sym->type.t & VT_TYPEDEF))
7111 tcc_error("incompatible redefinition of '%s'",
7112 get_tok_str(v, NULL));
7113 sym->type = type;
7114 } else {
7115 sym = sym_push(v, &type, 0, 0);
7117 sym->a = ad.a;
7118 sym->type.t |= VT_TYPEDEF;
7119 } else {
7120 r = 0;
7121 if ((type.t & VT_BTYPE) == VT_FUNC) {
7122 /* external function definition */
7123 /* specific case for func_call attribute */
7124 type.ref->a = ad.a;
7125 } else if (!(type.t & VT_ARRAY)) {
7126 /* not lvalue if array */
7127 r |= lvalue_type(type.t);
7129 has_init = (tok == '=');
7130 if (has_init && (type.t & VT_VLA))
7131 tcc_error("variable length array cannot be initialized");
7132 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
7133 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7134 !has_init && l == VT_CONST && type.ref->c < 0)) {
7135 /* external variable or function */
7136 /* NOTE: as GCC, uninitialized global static
7137 arrays of null size are considered as
7138 extern */
7139 sym = external_sym(v, &type, r);
7140 sym->asm_label = ad.asm_label;
7142 if (ad.alias_target) {
7143 Section tsec;
7144 ElfW(Sym) *esym;
7145 Sym *alias_target;
7147 alias_target = sym_find(ad.alias_target);
7148 if (!alias_target || !alias_target->c)
7149 tcc_error("unsupported forward __alias__ attribute");
7150 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7151 tsec.sh_num = esym->st_shndx;
7152 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7154 } else {
7155 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
7156 if (type.t & VT_STATIC)
7157 r |= VT_CONST;
7158 else
7159 r |= l;
7160 if (has_init)
7161 next();
7162 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7165 if (tok != ',') {
7166 if (is_for_loop_init)
7167 return 1;
7168 skip(';');
7169 break;
7171 next();
7173 ad.a.aligned = 0;
7176 return 0;
7179 ST_FUNC void decl(int l)
7181 decl0(l, 0);
7184 /* ------------------------------------------------------------------------- */