Move (void) parameter detection into a separate function, simplify daisy chaining...
[cparser] / parser.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdbool.h>
25
26 #include "parser.h"
27 #include "diagnostic.h"
28 #include "format_check.h"
29 #include "lexer.h"
30 #include "symbol_t.h"
31 #include "token_t.h"
32 #include "types.h"
33 #include "type_t.h"
34 #include "type_hash.h"
35 #include "ast_t.h"
36 #include "entity_t.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
39 #include "warning.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
43
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 1
46
47 typedef struct {
48         entity_t           *old_entity;
49         symbol_t           *symbol;
50         entity_namespace_t  namespc;
51 } stack_entry_t;
52
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
55         long              argument;
56         argument_list_t  *next;
57 };
58
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61         gnu_attribute_kind_t kind;          /**< The kind of the GNU attribute. */
62         gnu_attribute_t     *next;
63         bool                 invalid;       /**< Set if this attribute had argument errors, */
64         bool                 has_arguments; /**< True, if this attribute has arguments. */
65         union {
66                 size_t              value;
67                 string_t            string;
68                 symbol_t           *symbol;
69                 long                argument;  /**< Single argument. */
70                 argument_list_t    *arguments; /**< List of argument expressions. */
71         } u;
72 };
73
74 typedef struct declaration_specifiers_t  declaration_specifiers_t;
75 struct declaration_specifiers_t {
76         source_position_t  source_position;
77         storage_class_t    storage_class;
78         unsigned char      alignment;         /**< Alignment, 0 if not set. */
79         bool               is_inline    : 1;
80         bool               thread_local : 1;  /**< GCC __thread */
81         bool               deprecated   : 1;
82         decl_modifiers_t   modifiers;         /**< declaration modifiers */
83         gnu_attribute_t   *gnu_attributes;    /**< list of GNU attributes */
84         const char        *deprecated_string; /**< can be set if declaration was marked deprecated. */
85         symbol_t          *get_property_sym;  /**< the name of the get property if set. */
86         symbol_t          *put_property_sym;  /**< the name of the put property if set. */
87         type_t            *type;
88 };
89
90 /**
91  * An environment for parsing initializers (and compound literals).
92  */
93 typedef struct parse_initializer_env_t {
94         type_t     *type;   /**< the type of the initializer. In case of an
95                                  array type with unspecified size this gets
96                                  adjusted to the actual size. */
97         entity_t   *entity; /**< the variable that is initialized if any */
98         bool        must_be_constant;
99 } parse_initializer_env_t;
100
101 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
102
103 /** The current token. */
104 static token_t              token;
105 /** The lookahead ring-buffer. */
106 static token_t              lookahead_buffer[MAX_LOOKAHEAD];
107 /** Position of the next token in the lookahead buffer. */
108 static size_t               lookahead_bufpos;
109 static stack_entry_t       *environment_stack = NULL;
110 static stack_entry_t       *label_stack       = NULL;
111 static scope_t             *file_scope        = NULL;
112 static scope_t             *current_scope     = NULL;
113 /** Point to the current function declaration if inside a function. */
114 static function_t          *current_function  = NULL;
115 static entity_t            *current_init_decl = NULL;
116 static switch_statement_t  *current_switch    = NULL;
117 static statement_t         *current_loop      = NULL;
118 static statement_t         *current_parent    = NULL;
119 static ms_try_statement_t  *current_try       = NULL;
120 static linkage_kind_t       current_linkage   = LINKAGE_INVALID;
121 static goto_statement_t    *goto_first        = NULL;
122 static goto_statement_t   **goto_anchor       = NULL;
123 static label_statement_t   *label_first       = NULL;
124 static label_statement_t  **label_anchor      = NULL;
125 /** current translation unit. */
126 static translation_unit_t  *unit              = NULL;
127 /** true if we are in a type property context (evaluation only for type. */
128 static bool                 in_type_prop      = false;
129 /** true in we are in a __extension__ context. */
130 static bool                 in_gcc_extension  = false;
131 static struct obstack       temp_obst;
132 static entity_t            *anonymous_entity;
133 static declaration_t      **incomplete_arrays;
134
135
136 #define PUSH_PARENT(stmt)                          \
137         statement_t *const prev_parent = current_parent; \
138         ((void)(current_parent = (stmt)))
139 #define POP_PARENT ((void)(current_parent = prev_parent))
140
141 /** special symbol used for anonymous entities. */
142 static const symbol_t *sym_anonymous = NULL;
143
144 /* symbols for Microsoft extended-decl-modifier */
145 static const symbol_t *sym_align         = NULL;
146 static const symbol_t *sym_allocate      = NULL;
147 static const symbol_t *sym_dllimport     = NULL;
148 static const symbol_t *sym_dllexport     = NULL;
149 static const symbol_t *sym_naked         = NULL;
150 static const symbol_t *sym_noinline      = NULL;
151 static const symbol_t *sym_returns_twice = NULL;
152 static const symbol_t *sym_noreturn      = NULL;
153 static const symbol_t *sym_nothrow       = NULL;
154 static const symbol_t *sym_novtable      = NULL;
155 static const symbol_t *sym_property      = NULL;
156 static const symbol_t *sym_get           = NULL;
157 static const symbol_t *sym_put           = NULL;
158 static const symbol_t *sym_selectany     = NULL;
159 static const symbol_t *sym_thread        = NULL;
160 static const symbol_t *sym_uuid          = NULL;
161 static const symbol_t *sym_deprecated    = NULL;
162 static const symbol_t *sym_restrict      = NULL;
163 static const symbol_t *sym_noalias       = NULL;
164
165 /** The token anchor set */
166 static unsigned char token_anchor_set[T_LAST_TOKEN];
167
168 /** The current source position. */
169 #define HERE (&token.source_position)
170
171 /** true if we are in GCC mode. */
172 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
173
174 static type_t *type_valist;
175
176 static statement_t *parse_compound_statement(bool inside_expression_statement);
177 static statement_t *parse_statement(void);
178
179 static expression_t *parse_sub_expression(precedence_t);
180 static expression_t *parse_expression(void);
181 static type_t       *parse_typename(void);
182 static void          parse_externals(void);
183 static void          parse_external(void);
184
185 static void parse_compound_type_entries(compound_t *compound_declaration);
186
187 typedef enum declarator_flags_t {
188         DECL_FLAGS_NONE             = 0,
189         DECL_MAY_BE_ABSTRACT        = 1U << 0,
190         DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
191         DECL_IS_PARAMETER           = 1U << 2
192 } declarator_flags_t;
193
194 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
195                                   declarator_flags_t flags);
196
197 static entity_t *record_entity(entity_t *entity, bool is_definition);
198
199 static void semantic_comparison(binary_expression_t *expression);
200
201 static void create_gnu_builtins(void);
202 static void create_microsoft_intrinsics(void);
203
204 #define STORAGE_CLASSES       \
205         STORAGE_CLASSES_NO_EXTERN \
206         case T_extern:
207
208 #define STORAGE_CLASSES_NO_EXTERN \
209         case T_typedef:         \
210         case T_static:          \
211         case T_auto:            \
212         case T_register:        \
213         case T___thread:
214
215 #define TYPE_QUALIFIERS     \
216         case T_const:           \
217         case T_restrict:        \
218         case T_volatile:        \
219         case T_inline:          \
220         case T__forceinline:    \
221         case T___attribute__:
222
223 #define COMPLEX_SPECIFIERS  \
224         case T__Complex:
225 #define IMAGINARY_SPECIFIERS \
226         case T__Imaginary:
227
228 #define TYPE_SPECIFIERS       \
229         case T__Bool:             \
230         case T___builtin_va_list: \
231         case T___typeof__:        \
232         case T__declspec:         \
233         case T_bool:              \
234         case T_char:              \
235         case T_double:            \
236         case T_enum:              \
237         case T_float:             \
238         case T_int:               \
239         case T_long:              \
240         case T_short:             \
241         case T_signed:            \
242         case T_struct:            \
243         case T_union:             \
244         case T_unsigned:          \
245         case T_void:              \
246         case T_wchar_t:           \
247         COMPLEX_SPECIFIERS        \
248         IMAGINARY_SPECIFIERS
249
250 #define DECLARATION_START   \
251         STORAGE_CLASSES         \
252         TYPE_QUALIFIERS         \
253         TYPE_SPECIFIERS
254
255 #define DECLARATION_START_NO_EXTERN \
256         STORAGE_CLASSES_NO_EXTERN       \
257         TYPE_QUALIFIERS                 \
258         TYPE_SPECIFIERS
259
260 #define TYPENAME_START      \
261         TYPE_QUALIFIERS         \
262         TYPE_SPECIFIERS
263
264 #define EXPRESSION_START           \
265         case '!':                        \
266         case '&':                        \
267         case '(':                        \
268         case '*':                        \
269         case '+':                        \
270         case '-':                        \
271         case '~':                        \
272         case T_ANDAND:                   \
273         case T_CHARACTER_CONSTANT:       \
274         case T_FLOATINGPOINT:            \
275         case T_INTEGER:                  \
276         case T_MINUSMINUS:               \
277         case T_PLUSPLUS:                 \
278         case T_STRING_LITERAL:           \
279         case T_WIDE_CHARACTER_CONSTANT:  \
280         case T_WIDE_STRING_LITERAL:      \
281         case T___FUNCDNAME__:            \
282         case T___FUNCSIG__:              \
283         case T___FUNCTION__:             \
284         case T___PRETTY_FUNCTION__:      \
285         case T___alignof__:              \
286         case T___builtin_classify_type:  \
287         case T___builtin_constant_p:     \
288         case T___builtin_isgreater:      \
289         case T___builtin_isgreaterequal: \
290         case T___builtin_isless:         \
291         case T___builtin_islessequal:    \
292         case T___builtin_islessgreater:  \
293         case T___builtin_isunordered:    \
294         case T___builtin_offsetof:       \
295         case T___builtin_va_arg:         \
296         case T___builtin_va_start:       \
297         case T___func__:                 \
298         case T___noop:                   \
299         case T__assume:                  \
300         case T_delete:                   \
301         case T_false:                    \
302         case T_sizeof:                   \
303         case T_throw:                    \
304         case T_true:
305
306 /**
307  * Allocate an AST node with given size and
308  * initialize all fields with zero.
309  */
310 static void *allocate_ast_zero(size_t size)
311 {
312         void *res = allocate_ast(size);
313         memset(res, 0, size);
314         return res;
315 }
316
317 /**
318  * Returns the size of an entity node.
319  *
320  * @param kind  the entity kind
321  */
322 static size_t get_entity_struct_size(entity_kind_t kind)
323 {
324         static const size_t sizes[] = {
325                 [ENTITY_VARIABLE]        = sizeof(variable_t),
326                 [ENTITY_PARAMETER]       = sizeof(parameter_t),
327                 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
328                 [ENTITY_FUNCTION]        = sizeof(function_t),
329                 [ENTITY_TYPEDEF]         = sizeof(typedef_t),
330                 [ENTITY_STRUCT]          = sizeof(compound_t),
331                 [ENTITY_UNION]           = sizeof(compound_t),
332                 [ENTITY_ENUM]            = sizeof(enum_t),
333                 [ENTITY_ENUM_VALUE]      = sizeof(enum_value_t),
334                 [ENTITY_LABEL]           = sizeof(label_t),
335                 [ENTITY_LOCAL_LABEL]     = sizeof(label_t),
336                 [ENTITY_NAMESPACE]       = sizeof(namespace_t)
337         };
338         assert(kind < lengthof(sizes));
339         assert(sizes[kind] != 0);
340         return sizes[kind];
341 }
342
343 /**
344  * Allocate an entity of given kind and initialize all
345  * fields with zero.
346  */
347 static entity_t *allocate_entity_zero(entity_kind_t kind)
348 {
349         size_t    size   = get_entity_struct_size(kind);
350         entity_t *entity = allocate_ast_zero(size);
351         entity->kind     = kind;
352         return entity;
353 }
354
355 /**
356  * Returns the size of a statement node.
357  *
358  * @param kind  the statement kind
359  */
360 static size_t get_statement_struct_size(statement_kind_t kind)
361 {
362         static const size_t sizes[] = {
363                 [STATEMENT_INVALID]     = sizeof(invalid_statement_t),
364                 [STATEMENT_EMPTY]       = sizeof(empty_statement_t),
365                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
366                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
367                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
368                 [STATEMENT_IF]          = sizeof(if_statement_t),
369                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
370                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
371                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
372                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
373                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
374                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
375                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
376                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
377                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
378                 [STATEMENT_FOR]         = sizeof(for_statement_t),
379                 [STATEMENT_ASM]         = sizeof(asm_statement_t),
380                 [STATEMENT_MS_TRY]      = sizeof(ms_try_statement_t),
381                 [STATEMENT_LEAVE]       = sizeof(leave_statement_t)
382         };
383         assert(kind < lengthof(sizes));
384         assert(sizes[kind] != 0);
385         return sizes[kind];
386 }
387
388 /**
389  * Returns the size of an expression node.
390  *
391  * @param kind  the expression kind
392  */
393 static size_t get_expression_struct_size(expression_kind_t kind)
394 {
395         static const size_t sizes[] = {
396                 [EXPR_INVALID]                    = sizeof(expression_base_t),
397                 [EXPR_REFERENCE]                  = sizeof(reference_expression_t),
398                 [EXPR_REFERENCE_ENUM_VALUE]       = sizeof(reference_expression_t),
399                 [EXPR_CONST]                      = sizeof(const_expression_t),
400                 [EXPR_CHARACTER_CONSTANT]         = sizeof(const_expression_t),
401                 [EXPR_WIDE_CHARACTER_CONSTANT]    = sizeof(const_expression_t),
402                 [EXPR_STRING_LITERAL]             = sizeof(string_literal_expression_t),
403                 [EXPR_WIDE_STRING_LITERAL]        = sizeof(wide_string_literal_expression_t),
404                 [EXPR_COMPOUND_LITERAL]           = sizeof(compound_literal_expression_t),
405                 [EXPR_CALL]                       = sizeof(call_expression_t),
406                 [EXPR_UNARY_FIRST]                = sizeof(unary_expression_t),
407                 [EXPR_BINARY_FIRST]               = sizeof(binary_expression_t),
408                 [EXPR_CONDITIONAL]                = sizeof(conditional_expression_t),
409                 [EXPR_SELECT]                     = sizeof(select_expression_t),
410                 [EXPR_ARRAY_ACCESS]               = sizeof(array_access_expression_t),
411                 [EXPR_SIZEOF]                     = sizeof(typeprop_expression_t),
412                 [EXPR_ALIGNOF]                    = sizeof(typeprop_expression_t),
413                 [EXPR_CLASSIFY_TYPE]              = sizeof(classify_type_expression_t),
414                 [EXPR_FUNCNAME]                   = sizeof(funcname_expression_t),
415                 [EXPR_BUILTIN_CONSTANT_P]         = sizeof(builtin_constant_expression_t),
416                 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
417                 [EXPR_OFFSETOF]                   = sizeof(offsetof_expression_t),
418                 [EXPR_VA_START]                   = sizeof(va_start_expression_t),
419                 [EXPR_VA_ARG]                     = sizeof(va_arg_expression_t),
420                 [EXPR_STATEMENT]                  = sizeof(statement_expression_t),
421                 [EXPR_LABEL_ADDRESS]              = sizeof(label_address_expression_t),
422         };
423         if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
424                 return sizes[EXPR_UNARY_FIRST];
425         }
426         if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
427                 return sizes[EXPR_BINARY_FIRST];
428         }
429         assert(kind < lengthof(sizes));
430         assert(sizes[kind] != 0);
431         return sizes[kind];
432 }
433
434 /**
435  * Allocate a statement node of given kind and initialize all
436  * fields with zero. Sets its source position to the position
437  * of the current token.
438  */
439 static statement_t *allocate_statement_zero(statement_kind_t kind)
440 {
441         size_t       size = get_statement_struct_size(kind);
442         statement_t *res  = allocate_ast_zero(size);
443
444         res->base.kind            = kind;
445         res->base.parent          = current_parent;
446         res->base.source_position = token.source_position;
447         return res;
448 }
449
450 /**
451  * Allocate an expression node of given kind and initialize all
452  * fields with zero.
453  */
454 static expression_t *allocate_expression_zero(expression_kind_t kind)
455 {
456         size_t        size = get_expression_struct_size(kind);
457         expression_t *res  = allocate_ast_zero(size);
458
459         res->base.kind            = kind;
460         res->base.type            = type_error_type;
461         res->base.source_position = token.source_position;
462         return res;
463 }
464
465 /**
466  * Creates a new invalid expression at the source position
467  * of the current token.
468  */
469 static expression_t *create_invalid_expression(void)
470 {
471         return allocate_expression_zero(EXPR_INVALID);
472 }
473
474 /**
475  * Creates a new invalid statement.
476  */
477 static statement_t *create_invalid_statement(void)
478 {
479         return allocate_statement_zero(STATEMENT_INVALID);
480 }
481
482 /**
483  * Allocate a new empty statement.
484  */
485 static statement_t *create_empty_statement(void)
486 {
487         return allocate_statement_zero(STATEMENT_EMPTY);
488 }
489
490 /**
491  * Returns the size of a type node.
492  *
493  * @param kind  the type kind
494  */
495 static size_t get_type_struct_size(type_kind_t kind)
496 {
497         static const size_t sizes[] = {
498                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
499                 [TYPE_COMPLEX]         = sizeof(complex_type_t),
500                 [TYPE_IMAGINARY]       = sizeof(imaginary_type_t),
501                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
502                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
503                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
504                 [TYPE_ENUM]            = sizeof(enum_type_t),
505                 [TYPE_FUNCTION]        = sizeof(function_type_t),
506                 [TYPE_POINTER]         = sizeof(pointer_type_t),
507                 [TYPE_ARRAY]           = sizeof(array_type_t),
508                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
509                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
510                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
511         };
512         assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
513         assert(kind <= TYPE_TYPEOF);
514         assert(sizes[kind] != 0);
515         return sizes[kind];
516 }
517
518 /**
519  * Allocate a type node of given kind and initialize all
520  * fields with zero.
521  *
522  * @param kind             type kind to allocate
523  */
524 static type_t *allocate_type_zero(type_kind_t kind)
525 {
526         size_t  size = get_type_struct_size(kind);
527         type_t *res  = obstack_alloc(type_obst, size);
528         memset(res, 0, size);
529         res->base.kind = kind;
530
531         return res;
532 }
533
534 static function_parameter_t *allocate_parameter(type_t *const type)
535 {
536         function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
537         memset(param, 0, sizeof(*param));
538         param->type = type;
539         return param;
540 }
541
542 /**
543  * Returns the size of an initializer node.
544  *
545  * @param kind  the initializer kind
546  */
547 static size_t get_initializer_size(initializer_kind_t kind)
548 {
549         static const size_t sizes[] = {
550                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
551                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
552                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
553                 [INITIALIZER_LIST]        = sizeof(initializer_list_t),
554                 [INITIALIZER_DESIGNATOR]  = sizeof(initializer_designator_t)
555         };
556         assert(kind < lengthof(sizes));
557         assert(sizes[kind] != 0);
558         return sizes[kind];
559 }
560
561 /**
562  * Allocate an initializer node of given kind and initialize all
563  * fields with zero.
564  */
565 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
566 {
567         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
568         result->kind          = kind;
569
570         return result;
571 }
572
573 /**
574  * Returns the index of the top element of the environment stack.
575  */
576 static size_t environment_top(void)
577 {
578         return ARR_LEN(environment_stack);
579 }
580
581 /**
582  * Returns the index of the top element of the global label stack.
583  */
584 static size_t label_top(void)
585 {
586         return ARR_LEN(label_stack);
587 }
588
589 /**
590  * Return the next token.
591  */
592 static inline void next_token(void)
593 {
594         token                              = lookahead_buffer[lookahead_bufpos];
595         lookahead_buffer[lookahead_bufpos] = lexer_token;
596         lexer_next_token();
597
598         lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
599
600 #ifdef PRINT_TOKENS
601         print_token(stderr, &token);
602         fprintf(stderr, "\n");
603 #endif
604 }
605
606 /**
607  * Return the next token with a given lookahead.
608  */
609 static inline const token_t *look_ahead(size_t num)
610 {
611         assert(0 < num && num <= MAX_LOOKAHEAD);
612         size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
613         return &lookahead_buffer[pos];
614 }
615
616 /**
617  * Adds a token type to the token type anchor set (a multi-set).
618  */
619 static void add_anchor_token(int token_type)
620 {
621         assert(0 <= token_type && token_type < T_LAST_TOKEN);
622         ++token_anchor_set[token_type];
623 }
624
625 /**
626  * Set the number of tokens types of the given type
627  * to zero and return the old count.
628  */
629 static int save_and_reset_anchor_state(int token_type)
630 {
631         assert(0 <= token_type && token_type < T_LAST_TOKEN);
632         int count = token_anchor_set[token_type];
633         token_anchor_set[token_type] = 0;
634         return count;
635 }
636
637 /**
638  * Restore the number of token types to the given count.
639  */
640 static void restore_anchor_state(int token_type, int count)
641 {
642         assert(0 <= token_type && token_type < T_LAST_TOKEN);
643         token_anchor_set[token_type] = count;
644 }
645
646 /**
647  * Remove a token type from the token type anchor set (a multi-set).
648  */
649 static void rem_anchor_token(int token_type)
650 {
651         assert(0 <= token_type && token_type < T_LAST_TOKEN);
652         assert(token_anchor_set[token_type] != 0);
653         --token_anchor_set[token_type];
654 }
655
656 /**
657  * Return true if the token type of the current token is
658  * in the anchor set.
659  */
660 static bool at_anchor(void)
661 {
662         if (token.type < 0)
663                 return false;
664         return token_anchor_set[token.type];
665 }
666
667 /**
668  * Eat tokens until a matching token type is found.
669  */
670 static void eat_until_matching_token(int type)
671 {
672         int end_token;
673         switch (type) {
674                 case '(': end_token = ')';  break;
675                 case '{': end_token = '}';  break;
676                 case '[': end_token = ']';  break;
677                 default:  end_token = type; break;
678         }
679
680         unsigned parenthesis_count = 0;
681         unsigned brace_count       = 0;
682         unsigned bracket_count     = 0;
683         while (token.type        != end_token ||
684                parenthesis_count != 0         ||
685                brace_count       != 0         ||
686                bracket_count     != 0) {
687                 switch (token.type) {
688                 case T_EOF: return;
689                 case '(': ++parenthesis_count; break;
690                 case '{': ++brace_count;       break;
691                 case '[': ++bracket_count;     break;
692
693                 case ')':
694                         if (parenthesis_count > 0)
695                                 --parenthesis_count;
696                         goto check_stop;
697
698                 case '}':
699                         if (brace_count > 0)
700                                 --brace_count;
701                         goto check_stop;
702
703                 case ']':
704                         if (bracket_count > 0)
705                                 --bracket_count;
706 check_stop:
707                         if (token.type        == end_token &&
708                             parenthesis_count == 0         &&
709                             brace_count       == 0         &&
710                             bracket_count     == 0)
711                                 return;
712                         break;
713
714                 default:
715                         break;
716                 }
717                 next_token();
718         }
719 }
720
721 /**
722  * Eat input tokens until an anchor is found.
723  */
724 static void eat_until_anchor(void)
725 {
726         while (token_anchor_set[token.type] == 0) {
727                 if (token.type == '(' || token.type == '{' || token.type == '[')
728                         eat_until_matching_token(token.type);
729                 next_token();
730         }
731 }
732
733 /**
734  * Eat a whole block from input tokens.
735  */
736 static void eat_block(void)
737 {
738         eat_until_matching_token('{');
739         if (token.type == '}')
740                 next_token();
741 }
742
743 #define eat(token_type) (assert(token.type == (token_type)), next_token())
744
745 /**
746  * Report a parse error because an expected token was not found.
747  */
748 static
749 #if defined __GNUC__ && __GNUC__ >= 4
750 __attribute__((sentinel))
751 #endif
752 void parse_error_expected(const char *message, ...)
753 {
754         if (message != NULL) {
755                 errorf(HERE, "%s", message);
756         }
757         va_list ap;
758         va_start(ap, message);
759         errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
760         va_end(ap);
761 }
762
763 /**
764  * Report an incompatible type.
765  */
766 static void type_error_incompatible(const char *msg,
767                 const source_position_t *source_position, type_t *type1, type_t *type2)
768 {
769         errorf(source_position, "%s, incompatible types: '%T' - '%T'",
770                msg, type1, type2);
771 }
772
773 /**
774  * Expect the current token is the expected token.
775  * If not, generate an error, eat the current statement,
776  * and goto the end_error label.
777  */
778 #define expect(expected, error_label)                     \
779         do {                                                  \
780                 if (UNLIKELY(token.type != (expected))) {         \
781                         parse_error_expected(NULL, (expected), NULL); \
782                         add_anchor_token(expected);                   \
783                         eat_until_anchor();                           \
784                         if (token.type == expected)                   \
785                                 next_token();                             \
786                         rem_anchor_token(expected);                   \
787                         goto error_label;                             \
788                 }                                                 \
789                 next_token();                                     \
790         } while (0)
791
792 /**
793  * Push a given scope on the scope stack and make it the
794  * current scope
795  */
796 static scope_t *scope_push(scope_t *new_scope)
797 {
798         if (current_scope != NULL) {
799                 new_scope->depth = current_scope->depth + 1;
800         }
801
802         scope_t *old_scope = current_scope;
803         current_scope      = new_scope;
804         return old_scope;
805 }
806
807 /**
808  * Pop the current scope from the scope stack.
809  */
810 static void scope_pop(scope_t *old_scope)
811 {
812         current_scope = old_scope;
813 }
814
815 /**
816  * Search an entity by its symbol in a given namespace.
817  */
818 static entity_t *get_entity(const symbol_t *const symbol,
819                             namespace_tag_t namespc)
820 {
821         entity_t *entity = symbol->entity;
822         for (; entity != NULL; entity = entity->base.symbol_next) {
823                 if (entity->base.namespc == namespc)
824                         return entity;
825         }
826
827         return NULL;
828 }
829
830 /**
831  * pushs an entity on the environment stack and links the corresponding symbol
832  * it.
833  */
834 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
835 {
836         symbol_t           *symbol  = entity->base.symbol;
837         entity_namespace_t  namespc = entity->base.namespc;
838         assert(namespc != NAMESPACE_INVALID);
839
840         /* replace/add entity into entity list of the symbol */
841         entity_t **anchor;
842         entity_t  *iter;
843         for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
844                 iter = *anchor;
845                 if (iter == NULL)
846                         break;
847
848                 /* replace an entry? */
849                 if (iter->base.namespc == namespc) {
850                         entity->base.symbol_next = iter->base.symbol_next;
851                         break;
852                 }
853         }
854         *anchor = entity;
855
856         /* remember old declaration */
857         stack_entry_t entry;
858         entry.symbol     = symbol;
859         entry.old_entity = iter;
860         entry.namespc    = namespc;
861         ARR_APP1(stack_entry_t, *stack_ptr, entry);
862 }
863
864 /**
865  * Push an entity on the environment stack.
866  */
867 static void environment_push(entity_t *entity)
868 {
869         assert(entity->base.source_position.input_name != NULL);
870         assert(entity->base.parent_scope != NULL);
871         stack_push(&environment_stack, entity);
872 }
873
874 /**
875  * Push a declaration on the global label stack.
876  *
877  * @param declaration  the declaration
878  */
879 static void label_push(entity_t *label)
880 {
881         /* we abuse the parameters scope as parent for the labels */
882         label->base.parent_scope = &current_function->parameters;
883         stack_push(&label_stack, label);
884 }
885
886 /**
887  * pops symbols from the environment stack until @p new_top is the top element
888  */
889 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
890 {
891         stack_entry_t *stack = *stack_ptr;
892         size_t         top   = ARR_LEN(stack);
893         size_t         i;
894
895         assert(new_top <= top);
896         if (new_top == top)
897                 return;
898
899         for (i = top; i > new_top; --i) {
900                 stack_entry_t *entry = &stack[i - 1];
901
902                 entity_t           *old_entity = entry->old_entity;
903                 symbol_t           *symbol     = entry->symbol;
904                 entity_namespace_t  namespc    = entry->namespc;
905
906                 /* replace with old_entity/remove */
907                 entity_t **anchor;
908                 entity_t  *iter;
909                 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
910                         iter = *anchor;
911                         assert(iter != NULL);
912                         /* replace an entry? */
913                         if (iter->base.namespc == namespc)
914                                 break;
915                 }
916
917                 /* restore definition from outer scopes (if there was one) */
918                 if (old_entity != NULL) {
919                         old_entity->base.symbol_next = iter->base.symbol_next;
920                         *anchor                      = old_entity;
921                 } else {
922                         /* remove entry from list */
923                         *anchor = iter->base.symbol_next;
924                 }
925         }
926
927         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
928 }
929
930 /**
931  * Pop all entries from the environment stack until the new_top
932  * is reached.
933  *
934  * @param new_top  the new stack top
935  */
936 static void environment_pop_to(size_t new_top)
937 {
938         stack_pop_to(&environment_stack, new_top);
939 }
940
941 /**
942  * Pop all entries from the global label stack until the new_top
943  * is reached.
944  *
945  * @param new_top  the new stack top
946  */
947 static void label_pop_to(size_t new_top)
948 {
949         stack_pop_to(&label_stack, new_top);
950 }
951
952 static int get_akind_rank(atomic_type_kind_t akind)
953 {
954         return (int) akind;
955 }
956
957 /**
958  * Return the type rank for an atomic type.
959  */
960 static int get_rank(const type_t *type)
961 {
962         assert(!is_typeref(type));
963         if (type->kind == TYPE_ENUM)
964                 return get_akind_rank(type->enumt.akind);
965
966         assert(type->kind == TYPE_ATOMIC);
967         return get_akind_rank(type->atomic.akind);
968 }
969
970 /**
971  * Do integer promotion for a given type.
972  *
973  * @param type  the type to promote
974  * @return the promoted type
975  */
976 static type_t *promote_integer(type_t *type)
977 {
978         if (type->kind == TYPE_BITFIELD)
979                 type = type->bitfield.base_type;
980
981         if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
982                 type = type_int;
983
984         return type;
985 }
986
987 /**
988  * Create a cast expression.
989  *
990  * @param expression  the expression to cast
991  * @param dest_type   the destination type
992  */
993 static expression_t *create_cast_expression(expression_t *expression,
994                                             type_t *dest_type)
995 {
996         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
997
998         cast->unary.value = expression;
999         cast->base.type   = dest_type;
1000
1001         return cast;
1002 }
1003
1004 /**
1005  * Check if a given expression represents a null pointer constant.
1006  *
1007  * @param expression  the expression to check
1008  */
1009 static bool is_null_pointer_constant(const expression_t *expression)
1010 {
1011         /* skip void* cast */
1012         if (expression->kind == EXPR_UNARY_CAST ||
1013                         expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1014                 type_t *const type = skip_typeref(expression->base.type);
1015                 if (types_compatible(type, type_void_ptr))
1016                         expression = expression->unary.value;
1017         }
1018
1019         type_t *const type = skip_typeref(expression->base.type);
1020         return
1021                 is_type_integer(type)              &&
1022                 is_constant_expression(expression) &&
1023                 fold_constant(expression) == 0;
1024 }
1025
1026 /**
1027  * Create an implicit cast expression.
1028  *
1029  * @param expression  the expression to cast
1030  * @param dest_type   the destination type
1031  */
1032 static expression_t *create_implicit_cast(expression_t *expression,
1033                                           type_t *dest_type)
1034 {
1035         type_t *const source_type = expression->base.type;
1036
1037         if (source_type == dest_type)
1038                 return expression;
1039
1040         return create_cast_expression(expression, dest_type);
1041 }
1042
1043 typedef enum assign_error_t {
1044         ASSIGN_SUCCESS,
1045         ASSIGN_ERROR_INCOMPATIBLE,
1046         ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1047         ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1048         ASSIGN_WARNING_POINTER_FROM_INT,
1049         ASSIGN_WARNING_INT_FROM_POINTER
1050 } assign_error_t;
1051
1052 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1053                                 const expression_t *const right,
1054                                 const char *context,
1055                                 const source_position_t *source_position)
1056 {
1057         type_t *const orig_type_right = right->base.type;
1058         type_t *const type_left       = skip_typeref(orig_type_left);
1059         type_t *const type_right      = skip_typeref(orig_type_right);
1060
1061         switch (error) {
1062         case ASSIGN_SUCCESS:
1063                 return;
1064         case ASSIGN_ERROR_INCOMPATIBLE:
1065                 errorf(source_position,
1066                        "destination type '%T' in %s is incompatible with type '%T'",
1067                        orig_type_left, context, orig_type_right);
1068                 return;
1069
1070         case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1071                 if (warning.other) {
1072                         type_t *points_to_left  = skip_typeref(type_left->pointer.points_to);
1073                         type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1074
1075                         /* the left type has all qualifiers from the right type */
1076                         unsigned missing_qualifiers
1077                                 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1078                         warningf(source_position,
1079                                         "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1080                                         orig_type_left, context, orig_type_right, missing_qualifiers);
1081                 }
1082                 return;
1083         }
1084
1085         case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1086                 if (warning.other) {
1087                         warningf(source_position,
1088                                         "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1089                                         orig_type_left, context, right, orig_type_right);
1090                 }
1091                 return;
1092
1093         case ASSIGN_WARNING_POINTER_FROM_INT:
1094                 if (warning.other) {
1095                         warningf(source_position,
1096                                         "%s makes pointer '%T' from integer '%T' without a cast",
1097                                         context, orig_type_left, orig_type_right);
1098                 }
1099                 return;
1100
1101         case ASSIGN_WARNING_INT_FROM_POINTER:
1102                 if (warning.other) {
1103                         warningf(source_position,
1104                                         "%s makes integer '%T' from pointer '%T' without a cast",
1105                                         context, orig_type_left, orig_type_right);
1106                 }
1107                 return;
1108
1109         default:
1110                 panic("invalid error value");
1111         }
1112 }
1113
1114 /** Implements the rules from §6.5.16.1 */
1115 static assign_error_t semantic_assign(type_t *orig_type_left,
1116                                       const expression_t *const right)
1117 {
1118         type_t *const orig_type_right = right->base.type;
1119         type_t *const type_left       = skip_typeref(orig_type_left);
1120         type_t *const type_right      = skip_typeref(orig_type_right);
1121
1122         if (is_type_pointer(type_left)) {
1123                 if (is_null_pointer_constant(right)) {
1124                         return ASSIGN_SUCCESS;
1125                 } else if (is_type_pointer(type_right)) {
1126                         type_t *points_to_left
1127                                 = skip_typeref(type_left->pointer.points_to);
1128                         type_t *points_to_right
1129                                 = skip_typeref(type_right->pointer.points_to);
1130                         assign_error_t res = ASSIGN_SUCCESS;
1131
1132                         /* the left type has all qualifiers from the right type */
1133                         unsigned missing_qualifiers
1134                                 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1135                         if (missing_qualifiers != 0) {
1136                                 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1137                         }
1138
1139                         points_to_left  = get_unqualified_type(points_to_left);
1140                         points_to_right = get_unqualified_type(points_to_right);
1141
1142                         if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1143                                 return res;
1144
1145                         if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1146                                 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1147                                 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1148                         }
1149
1150                         if (!types_compatible(points_to_left, points_to_right)) {
1151                                 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1152                         }
1153
1154                         return res;
1155                 } else if (is_type_integer(type_right)) {
1156                         return ASSIGN_WARNING_POINTER_FROM_INT;
1157                 }
1158         } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1159             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1160                 && is_type_pointer(type_right))) {
1161                 return ASSIGN_SUCCESS;
1162         } else if ((is_type_compound(type_left)  && is_type_compound(type_right))
1163                         || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1164                 type_t *const unqual_type_left  = get_unqualified_type(type_left);
1165                 type_t *const unqual_type_right = get_unqualified_type(type_right);
1166                 if (types_compatible(unqual_type_left, unqual_type_right)) {
1167                         return ASSIGN_SUCCESS;
1168                 }
1169         } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1170                 return ASSIGN_WARNING_INT_FROM_POINTER;
1171         }
1172
1173         if (!is_type_valid(type_left) || !is_type_valid(type_right))
1174                 return ASSIGN_SUCCESS;
1175
1176         return ASSIGN_ERROR_INCOMPATIBLE;
1177 }
1178
1179 static expression_t *parse_constant_expression(void)
1180 {
1181         expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1182
1183         if (!is_constant_expression(result)) {
1184                 errorf(&result->base.source_position,
1185                        "expression '%E' is not constant", result);
1186         }
1187
1188         return result;
1189 }
1190
1191 static expression_t *parse_assignment_expression(void)
1192 {
1193         return parse_sub_expression(PREC_ASSIGNMENT);
1194 }
1195
1196 static string_t parse_string_literals(void)
1197 {
1198         assert(token.type == T_STRING_LITERAL);
1199         string_t result = token.v.string;
1200
1201         next_token();
1202
1203         while (token.type == T_STRING_LITERAL) {
1204                 result = concat_strings(&result, &token.v.string);
1205                 next_token();
1206         }
1207
1208         return result;
1209 }
1210
1211 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1212         [GNU_AK_CONST]                  = "const",
1213         [GNU_AK_VOLATILE]               = "volatile",
1214         [GNU_AK_CDECL]                  = "cdecl",
1215         [GNU_AK_STDCALL]                = "stdcall",
1216         [GNU_AK_FASTCALL]               = "fastcall",
1217         [GNU_AK_DEPRECATED]             = "deprecated",
1218         [GNU_AK_NOINLINE]               = "noinline",
1219         [GNU_AK_RETURNS_TWICE]          = "returns_twice",
1220         [GNU_AK_NORETURN]               = "noreturn",
1221         [GNU_AK_NAKED]                  = "naked",
1222         [GNU_AK_PURE]                   = "pure",
1223         [GNU_AK_ALWAYS_INLINE]          = "always_inline",
1224         [GNU_AK_MALLOC]                 = "malloc",
1225         [GNU_AK_WEAK]                   = "weak",
1226         [GNU_AK_CONSTRUCTOR]            = "constructor",
1227         [GNU_AK_DESTRUCTOR]             = "destructor",
1228         [GNU_AK_NOTHROW]                = "nothrow",
1229         [GNU_AK_TRANSPARENT_UNION]      = "transparent_union",
1230         [GNU_AK_COMMON]                 = "common",
1231         [GNU_AK_NOCOMMON]               = "nocommon",
1232         [GNU_AK_PACKED]                 = "packed",
1233         [GNU_AK_SHARED]                 = "shared",
1234         [GNU_AK_NOTSHARED]              = "notshared",
1235         [GNU_AK_USED]                   = "used",
1236         [GNU_AK_UNUSED]                 = "unused",
1237         [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1238         [GNU_AK_WARN_UNUSED_RESULT]     = "warn_unused_result",
1239         [GNU_AK_LONGCALL]               = "longcall",
1240         [GNU_AK_SHORTCALL]              = "shortcall",
1241         [GNU_AK_LONG_CALL]              = "long_call",
1242         [GNU_AK_SHORT_CALL]             = "short_call",
1243         [GNU_AK_FUNCTION_VECTOR]        = "function_vector",
1244         [GNU_AK_INTERRUPT]              = "interrupt",
1245         [GNU_AK_INTERRUPT_HANDLER]      = "interrupt_handler",
1246         [GNU_AK_NMI_HANDLER]            = "nmi_handler",
1247         [GNU_AK_NESTING]                = "nesting",
1248         [GNU_AK_NEAR]                   = "near",
1249         [GNU_AK_FAR]                    = "far",
1250         [GNU_AK_SIGNAL]                 = "signal",
1251         [GNU_AK_EIGTHBIT_DATA]          = "eightbit_data",
1252         [GNU_AK_TINY_DATA]              = "tiny_data",
1253         [GNU_AK_SAVEALL]                = "saveall",
1254         [GNU_AK_FLATTEN]                = "flatten",
1255         [GNU_AK_SSEREGPARM]             = "sseregparm",
1256         [GNU_AK_EXTERNALLY_VISIBLE]     = "externally_visible",
1257         [GNU_AK_RETURN_TWICE]           = "return_twice",
1258         [GNU_AK_MAY_ALIAS]              = "may_alias",
1259         [GNU_AK_MS_STRUCT]              = "ms_struct",
1260         [GNU_AK_GCC_STRUCT]             = "gcc_struct",
1261         [GNU_AK_DLLIMPORT]              = "dllimport",
1262         [GNU_AK_DLLEXPORT]              = "dllexport",
1263         [GNU_AK_ALIGNED]                = "aligned",
1264         [GNU_AK_ALIAS]                  = "alias",
1265         [GNU_AK_SECTION]                = "section",
1266         [GNU_AK_FORMAT]                 = "format",
1267         [GNU_AK_FORMAT_ARG]             = "format_arg",
1268         [GNU_AK_WEAKREF]                = "weakref",
1269         [GNU_AK_NONNULL]                = "nonnull",
1270         [GNU_AK_TLS_MODEL]              = "tls_model",
1271         [GNU_AK_VISIBILITY]             = "visibility",
1272         [GNU_AK_REGPARM]                = "regparm",
1273         [GNU_AK_MODE]                   = "mode",
1274         [GNU_AK_MODEL]                  = "model",
1275         [GNU_AK_TRAP_EXIT]              = "trap_exit",
1276         [GNU_AK_SP_SWITCH]              = "sp_switch",
1277         [GNU_AK_SENTINEL]               = "sentinel"
1278 };
1279
1280 /**
1281  * compare two string, ignoring double underscores on the second.
1282  */
1283 static int strcmp_underscore(const char *s1, const char *s2)
1284 {
1285         if (s2[0] == '_' && s2[1] == '_') {
1286                 size_t len2 = strlen(s2);
1287                 size_t len1 = strlen(s1);
1288                 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1289                         return strncmp(s1, s2+2, len2-4);
1290                 }
1291         }
1292
1293         return strcmp(s1, s2);
1294 }
1295
1296 /**
1297  * Allocate a new gnu temporal attribute of given kind.
1298  */
1299 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1300 {
1301         gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1302         attribute->kind            = kind;
1303         attribute->next            = NULL;
1304         attribute->invalid         = false;
1305         attribute->has_arguments   = false;
1306
1307         return attribute;
1308 }
1309
1310 /**
1311  * Parse one constant expression argument of the given attribute.
1312  */
1313 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1314 {
1315         expression_t *expression;
1316         add_anchor_token(')');
1317         expression = parse_constant_expression();
1318         rem_anchor_token(')');
1319         expect(')', end_error);
1320         attribute->u.argument = fold_constant(expression);
1321         return;
1322 end_error:
1323         attribute->invalid = true;
1324 }
1325
1326 /**
1327  * Parse a list of constant expressions arguments of the given attribute.
1328  */
1329 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1330 {
1331         argument_list_t **list = &attribute->u.arguments;
1332         argument_list_t  *entry;
1333         expression_t     *expression;
1334         add_anchor_token(')');
1335         add_anchor_token(',');
1336         while (true) {
1337                 expression = parse_constant_expression();
1338                 entry = obstack_alloc(&temp_obst, sizeof(entry));
1339                 entry->argument = fold_constant(expression);
1340                 entry->next     = NULL;
1341                 *list = entry;
1342                 list = &entry->next;
1343                 if (token.type != ',')
1344                         break;
1345                 next_token();
1346         }
1347         rem_anchor_token(',');
1348         rem_anchor_token(')');
1349         expect(')', end_error);
1350         return;
1351 end_error:
1352         attribute->invalid = true;
1353 }
1354
1355 /**
1356  * Parse one string literal argument of the given attribute.
1357  */
1358 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1359                                            string_t *string)
1360 {
1361         add_anchor_token('(');
1362         if (token.type != T_STRING_LITERAL) {
1363                 parse_error_expected("while parsing attribute directive",
1364                                      T_STRING_LITERAL, NULL);
1365                 goto end_error;
1366         }
1367         *string = parse_string_literals();
1368         rem_anchor_token('(');
1369         expect(')', end_error);
1370         return;
1371 end_error:
1372         attribute->invalid = true;
1373 }
1374
1375 /**
1376  * Parse one tls model of the given attribute.
1377  */
1378 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1379 {
1380         static const char *const tls_models[] = {
1381                 "global-dynamic",
1382                 "local-dynamic",
1383                 "initial-exec",
1384                 "local-exec"
1385         };
1386         string_t string = { NULL, 0 };
1387         parse_gnu_attribute_string_arg(attribute, &string);
1388         if (string.begin != NULL) {
1389                 for (size_t i = 0; i < 4; ++i) {
1390                         if (strcmp(tls_models[i], string.begin) == 0) {
1391                                 attribute->u.value = i;
1392                                 return;
1393                         }
1394                 }
1395                 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1396         }
1397         attribute->invalid = true;
1398 }
1399
1400 /**
1401  * Parse one tls model of the given attribute.
1402  */
1403 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1404 {
1405         static const char *const visibilities[] = {
1406                 "default",
1407                 "protected",
1408                 "hidden",
1409                 "internal"
1410         };
1411         string_t string = { NULL, 0 };
1412         parse_gnu_attribute_string_arg(attribute, &string);
1413         if (string.begin != NULL) {
1414                 for (size_t i = 0; i < 4; ++i) {
1415                         if (strcmp(visibilities[i], string.begin) == 0) {
1416                                 attribute->u.value = i;
1417                                 return;
1418                         }
1419                 }
1420                 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1421         }
1422         attribute->invalid = true;
1423 }
1424
1425 /**
1426  * Parse one (code) model of the given attribute.
1427  */
1428 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1429 {
1430         static const char *const visibilities[] = {
1431                 "small",
1432                 "medium",
1433                 "large"
1434         };
1435         string_t string = { NULL, 0 };
1436         parse_gnu_attribute_string_arg(attribute, &string);
1437         if (string.begin != NULL) {
1438                 for (int i = 0; i < 3; ++i) {
1439                         if (strcmp(visibilities[i], string.begin) == 0) {
1440                                 attribute->u.value = i;
1441                                 return;
1442                         }
1443                 }
1444                 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1445         }
1446         attribute->invalid = true;
1447 }
1448
1449 /**
1450  * Parse one mode of the given attribute.
1451  */
1452 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1453 {
1454         add_anchor_token(')');
1455
1456         if (token.type != T_IDENTIFIER) {
1457                 expect(T_IDENTIFIER, end_error);
1458         }
1459
1460         attribute->u.symbol = token.v.symbol;
1461         next_token();
1462
1463         rem_anchor_token(')');
1464         expect(')', end_error);
1465         return;
1466 end_error:
1467         attribute->invalid = true;
1468 }
1469
1470 /**
1471  * Parse one interrupt argument of the given attribute.
1472  */
1473 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1474 {
1475         static const char *const interrupts[] = {
1476                 "IRQ",
1477                 "FIQ",
1478                 "SWI",
1479                 "ABORT",
1480                 "UNDEF"
1481         };
1482         string_t string = { NULL, 0 };
1483         parse_gnu_attribute_string_arg(attribute, &string);
1484         if (string.begin != NULL) {
1485                 for (size_t i = 0; i < 5; ++i) {
1486                         if (strcmp(interrupts[i], string.begin) == 0) {
1487                                 attribute->u.value = i;
1488                                 return;
1489                         }
1490                 }
1491                 errorf(HERE, "'%s' is not an interrupt", string.begin);
1492         }
1493         attribute->invalid = true;
1494 }
1495
1496 /**
1497  * Parse ( identifier, const expression, const expression )
1498  */
1499 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1500 {
1501         static const char *const format_names[] = {
1502                 "printf",
1503                 "scanf",
1504                 "strftime",
1505                 "strfmon"
1506         };
1507         int i;
1508
1509         if (token.type != T_IDENTIFIER) {
1510                 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1511                 goto end_error;
1512         }
1513         const char *name = token.v.symbol->string;
1514         for (i = 0; i < 4; ++i) {
1515                 if (strcmp_underscore(format_names[i], name) == 0)
1516                         break;
1517         }
1518         if (i >= 4) {
1519                 if (warning.attribute)
1520                         warningf(HERE, "'%s' is an unrecognized format function type", name);
1521         }
1522         next_token();
1523
1524         expect(',', end_error);
1525         add_anchor_token(')');
1526         add_anchor_token(',');
1527         parse_constant_expression();
1528         rem_anchor_token(',');
1529         rem_anchor_token(')');
1530
1531         expect(',', end_error);
1532         add_anchor_token(')');
1533         parse_constant_expression();
1534         rem_anchor_token(')');
1535         expect(')', end_error);
1536         return;
1537 end_error:
1538         attribute->u.value = true;
1539 }
1540
1541 /**
1542  * Check that a given GNU attribute has no arguments.
1543  */
1544 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1545 {
1546         if (!attribute->has_arguments)
1547                 return;
1548
1549         /* should have no arguments */
1550         errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1551         eat_until_matching_token('(');
1552         /* we have already consumed '(', so we stop before ')', eat it */
1553         eat(')');
1554         attribute->invalid = true;
1555 }
1556
1557 /**
1558  * Parse one GNU attribute.
1559  *
1560  * Note that attribute names can be specified WITH or WITHOUT
1561  * double underscores, ie const or __const__.
1562  *
1563  * The following attributes are parsed without arguments
1564  *  const
1565  *  volatile
1566  *  cdecl
1567  *  stdcall
1568  *  fastcall
1569  *  deprecated
1570  *  noinline
1571  *  noreturn
1572  *  naked
1573  *  pure
1574  *  always_inline
1575  *  malloc
1576  *  weak
1577  *  constructor
1578  *  destructor
1579  *  nothrow
1580  *  transparent_union
1581  *  common
1582  *  nocommon
1583  *  packed
1584  *  shared
1585  *  notshared
1586  *  used
1587  *  unused
1588  *  no_instrument_function
1589  *  warn_unused_result
1590  *  longcall
1591  *  shortcall
1592  *  long_call
1593  *  short_call
1594  *  function_vector
1595  *  interrupt_handler
1596  *  nmi_handler
1597  *  nesting
1598  *  near
1599  *  far
1600  *  signal
1601  *  eightbit_data
1602  *  tiny_data
1603  *  saveall
1604  *  flatten
1605  *  sseregparm
1606  *  externally_visible
1607  *  return_twice
1608  *  may_alias
1609  *  ms_struct
1610  *  gcc_struct
1611  *  dllimport
1612  *  dllexport
1613  *
1614  * The following attributes are parsed with arguments
1615  *  aligned( const expression )
1616  *  alias( string literal )
1617  *  section( string literal )
1618  *  format( identifier, const expression, const expression )
1619  *  format_arg( const expression )
1620  *  tls_model( string literal )
1621  *  visibility( string literal )
1622  *  regparm( const expression )
1623  *  model( string leteral )
1624  *  trap_exit( const expression )
1625  *  sp_switch( string literal )
1626  *
1627  * The following attributes might have arguments
1628  *  weak_ref( string literal )
1629  *  non_null( const expression // ',' )
1630  *  interrupt( string literal )
1631  *  sentinel( constant expression )
1632  */
1633 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1634 {
1635         gnu_attribute_t *head      = *attributes;
1636         gnu_attribute_t *last      = *attributes;
1637         decl_modifiers_t modifiers = 0;
1638         gnu_attribute_t *attribute;
1639
1640         eat(T___attribute__);
1641         expect('(', end_error);
1642         expect('(', end_error);
1643
1644         if (token.type != ')') {
1645                 /* find the end of the list */
1646                 if (last != NULL) {
1647                         while (last->next != NULL)
1648                                 last = last->next;
1649                 }
1650
1651                 /* non-empty attribute list */
1652                 while (true) {
1653                         const char *name;
1654                         if (token.type == T_const) {
1655                                 name = "const";
1656                         } else if (token.type == T_volatile) {
1657                                 name = "volatile";
1658                         } else if (token.type == T_cdecl) {
1659                                 /* __attribute__((cdecl)), WITH ms mode */
1660                                 name = "cdecl";
1661                         } else if (token.type == T_IDENTIFIER) {
1662                                 const symbol_t *sym = token.v.symbol;
1663                                 name = sym->string;
1664                         } else {
1665                                 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1666                                 break;
1667                         }
1668
1669                         next_token();
1670
1671                         int i;
1672                         for (i = 0; i < GNU_AK_LAST; ++i) {
1673                                 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1674                                         break;
1675                         }
1676                         gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1677
1678                         attribute = NULL;
1679                         if (kind == GNU_AK_LAST) {
1680                                 if (warning.attribute)
1681                                         warningf(HERE, "'%s' attribute directive ignored", name);
1682
1683                                 /* skip possible arguments */
1684                                 if (token.type == '(') {
1685                                         eat_until_matching_token(')');
1686                                 }
1687                         } else {
1688                                 /* check for arguments */
1689                                 attribute = allocate_gnu_attribute(kind);
1690                                 if (token.type == '(') {
1691                                         next_token();
1692                                         if (token.type == ')') {
1693                                                 /* empty args are allowed */
1694                                                 next_token();
1695                                         } else
1696                                                 attribute->has_arguments = true;
1697                                 }
1698
1699                                 switch (kind) {
1700                                 case GNU_AK_VOLATILE:
1701                                 case GNU_AK_NAKED:
1702                                 case GNU_AK_MALLOC:
1703                                 case GNU_AK_WEAK:
1704                                 case GNU_AK_COMMON:
1705                                 case GNU_AK_NOCOMMON:
1706                                 case GNU_AK_SHARED:
1707                                 case GNU_AK_NOTSHARED:
1708                                 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1709                                 case GNU_AK_WARN_UNUSED_RESULT:
1710                                 case GNU_AK_LONGCALL:
1711                                 case GNU_AK_SHORTCALL:
1712                                 case GNU_AK_LONG_CALL:
1713                                 case GNU_AK_SHORT_CALL:
1714                                 case GNU_AK_FUNCTION_VECTOR:
1715                                 case GNU_AK_INTERRUPT_HANDLER:
1716                                 case GNU_AK_NMI_HANDLER:
1717                                 case GNU_AK_NESTING:
1718                                 case GNU_AK_NEAR:
1719                                 case GNU_AK_FAR:
1720                                 case GNU_AK_SIGNAL:
1721                                 case GNU_AK_EIGTHBIT_DATA:
1722                                 case GNU_AK_TINY_DATA:
1723                                 case GNU_AK_SAVEALL:
1724                                 case GNU_AK_FLATTEN:
1725                                 case GNU_AK_SSEREGPARM:
1726                                 case GNU_AK_EXTERNALLY_VISIBLE:
1727                                 case GNU_AK_RETURN_TWICE:
1728                                 case GNU_AK_MAY_ALIAS:
1729                                 case GNU_AK_MS_STRUCT:
1730                                 case GNU_AK_GCC_STRUCT:
1731                                         goto no_arg;
1732
1733                                 case GNU_AK_CDECL:             modifiers |= DM_CDECL;             goto no_arg;
1734                                 case GNU_AK_FASTCALL:          modifiers |= DM_FASTCALL;          goto no_arg;
1735                                 case GNU_AK_STDCALL:           modifiers |= DM_STDCALL;           goto no_arg;
1736                                 case GNU_AK_UNUSED:            modifiers |= DM_UNUSED;            goto no_arg;
1737                                 case GNU_AK_USED:              modifiers |= DM_USED;              goto no_arg;
1738                                 case GNU_AK_PURE:              modifiers |= DM_PURE;              goto no_arg;
1739                                 case GNU_AK_CONST:             modifiers |= DM_CONST;             goto no_arg;
1740                                 case GNU_AK_ALWAYS_INLINE:     modifiers |= DM_FORCEINLINE;       goto no_arg;
1741                                 case GNU_AK_DLLIMPORT:         modifiers |= DM_DLLIMPORT;         goto no_arg;
1742                                 case GNU_AK_DLLEXPORT:         modifiers |= DM_DLLEXPORT;         goto no_arg;
1743                                 case GNU_AK_PACKED:            modifiers |= DM_PACKED;            goto no_arg;
1744                                 case GNU_AK_NOINLINE:          modifiers |= DM_NOINLINE;          goto no_arg;
1745                                 case GNU_AK_RETURNS_TWICE:     modifiers |= DM_RETURNS_TWICE;     goto no_arg;
1746                                 case GNU_AK_NORETURN:          modifiers |= DM_NORETURN;          goto no_arg;
1747                                 case GNU_AK_NOTHROW:           modifiers |= DM_NOTHROW;           goto no_arg;
1748                                 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1749                                 case GNU_AK_CONSTRUCTOR:       modifiers |= DM_CONSTRUCTOR;       goto no_arg;
1750                                 case GNU_AK_DESTRUCTOR:        modifiers |= DM_DESTRUCTOR;        goto no_arg;
1751                                 case GNU_AK_DEPRECATED:        modifiers |= DM_DEPRECATED;        goto no_arg;
1752
1753                                 case GNU_AK_ALIGNED:
1754                                         /* __align__ may be used without an argument */
1755                                         if (attribute->has_arguments) {
1756                                                 parse_gnu_attribute_const_arg(attribute);
1757                                         }
1758                                         break;
1759
1760                                 case GNU_AK_FORMAT_ARG:
1761                                 case GNU_AK_REGPARM:
1762                                 case GNU_AK_TRAP_EXIT:
1763                                         if (!attribute->has_arguments) {
1764                                                 /* should have arguments */
1765                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1766                                                 attribute->invalid = true;
1767                                         } else
1768                                                 parse_gnu_attribute_const_arg(attribute);
1769                                         break;
1770                                 case GNU_AK_ALIAS:
1771                                 case GNU_AK_SECTION:
1772                                 case GNU_AK_SP_SWITCH:
1773                                         if (!attribute->has_arguments) {
1774                                                 /* should have arguments */
1775                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1776                                                 attribute->invalid = true;
1777                                         } else
1778                                                 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1779                                         break;
1780                                 case GNU_AK_FORMAT:
1781                                         if (!attribute->has_arguments) {
1782                                                 /* should have arguments */
1783                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1784                                                 attribute->invalid = true;
1785                                         } else
1786                                                 parse_gnu_attribute_format_args(attribute);
1787                                         break;
1788                                 case GNU_AK_WEAKREF:
1789                                         /* may have one string argument */
1790                                         if (attribute->has_arguments)
1791                                                 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1792                                         break;
1793                                 case GNU_AK_NONNULL:
1794                                         if (attribute->has_arguments)
1795                                                 parse_gnu_attribute_const_arg_list(attribute);
1796                                         break;
1797                                 case GNU_AK_TLS_MODEL:
1798                                         if (!attribute->has_arguments) {
1799                                                 /* should have arguments */
1800                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1801                                         } else
1802                                                 parse_gnu_attribute_tls_model_arg(attribute);
1803                                         break;
1804                                 case GNU_AK_VISIBILITY:
1805                                         if (!attribute->has_arguments) {
1806                                                 /* should have arguments */
1807                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1808                                         } else
1809                                                 parse_gnu_attribute_visibility_arg(attribute);
1810                                         break;
1811                                 case GNU_AK_MODEL:
1812                                         if (!attribute->has_arguments) {
1813                                                 /* should have arguments */
1814                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1815                                         } else {
1816                                                 parse_gnu_attribute_model_arg(attribute);
1817                                         }
1818                                         break;
1819                                 case GNU_AK_MODE:
1820                                         if (!attribute->has_arguments) {
1821                                                 /* should have arguments */
1822                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1823                                         } else {
1824                                                 parse_gnu_attribute_mode_arg(attribute);
1825                                         }
1826                                         break;
1827                                 case GNU_AK_INTERRUPT:
1828                                         /* may have one string argument */
1829                                         if (attribute->has_arguments)
1830                                                 parse_gnu_attribute_interrupt_arg(attribute);
1831                                         break;
1832                                 case GNU_AK_SENTINEL:
1833                                         /* may have one string argument */
1834                                         if (attribute->has_arguments)
1835                                                 parse_gnu_attribute_const_arg(attribute);
1836                                         break;
1837                                 case GNU_AK_LAST:
1838                                         /* already handled */
1839                                         break;
1840
1841 no_arg:
1842                                         check_no_argument(attribute, name);
1843                                 }
1844                         }
1845                         if (attribute != NULL) {
1846                                 if (last != NULL) {
1847                                         last->next = attribute;
1848                                         last       = attribute;
1849                                 } else {
1850                                         head = last = attribute;
1851                                 }
1852                         }
1853
1854                         if (token.type != ',')
1855                                 break;
1856                         next_token();
1857                 }
1858         }
1859         expect(')', end_error);
1860         expect(')', end_error);
1861 end_error:
1862         *attributes = head;
1863
1864         return modifiers;
1865 }
1866
1867 /**
1868  * Parse GNU attributes.
1869  */
1870 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1871 {
1872         decl_modifiers_t modifiers = 0;
1873
1874         while (true) {
1875                 switch (token.type) {
1876                 case T___attribute__:
1877                         modifiers |= parse_gnu_attribute(attributes);
1878                         continue;
1879
1880                 case T_asm:
1881                         next_token();
1882                         expect('(', end_error);
1883                         if (token.type != T_STRING_LITERAL) {
1884                                 parse_error_expected("while parsing assembler attribute",
1885                                                      T_STRING_LITERAL, NULL);
1886                                 eat_until_matching_token('(');
1887                                 break;
1888                         } else {
1889                                 parse_string_literals();
1890                         }
1891                         expect(')', end_error);
1892                         continue;
1893
1894                 case T_cdecl:     modifiers |= DM_CDECL;    break;
1895                 case T__fastcall: modifiers |= DM_FASTCALL; break;
1896                 case T__stdcall:  modifiers |= DM_STDCALL;  break;
1897
1898                 case T___thiscall:
1899                         /* TODO record modifier */
1900                         if (warning.other)
1901                                 warningf(HERE, "Ignoring declaration modifier %K", &token);
1902                         break;
1903
1904 end_error:
1905                 default: return modifiers;
1906                 }
1907
1908                 next_token();
1909         }
1910 }
1911
1912 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1913
1914 static entity_t *determine_lhs_ent(expression_t *const expr,
1915                                    entity_t *lhs_ent)
1916 {
1917         switch (expr->kind) {
1918                 case EXPR_REFERENCE: {
1919                         entity_t *const entity = expr->reference.entity;
1920                         /* we should only find variables as lvalues... */
1921                         if (entity->base.kind != ENTITY_VARIABLE
1922                                         && entity->base.kind != ENTITY_PARAMETER)
1923                                 return NULL;
1924
1925                         return entity;
1926                 }
1927
1928                 case EXPR_ARRAY_ACCESS: {
1929                         expression_t *const ref = expr->array_access.array_ref;
1930                         entity_t     *      ent = NULL;
1931                         if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1932                                 ent     = determine_lhs_ent(ref, lhs_ent);
1933                                 lhs_ent = ent;
1934                         } else {
1935                                 mark_vars_read(expr->select.compound, lhs_ent);
1936                         }
1937                         mark_vars_read(expr->array_access.index, lhs_ent);
1938                         return ent;
1939                 }
1940
1941                 case EXPR_SELECT: {
1942                         if (is_type_compound(skip_typeref(expr->base.type))) {
1943                                 return determine_lhs_ent(expr->select.compound, lhs_ent);
1944                         } else {
1945                                 mark_vars_read(expr->select.compound, lhs_ent);
1946                                 return NULL;
1947                         }
1948                 }
1949
1950                 case EXPR_UNARY_DEREFERENCE: {
1951                         expression_t *const val = expr->unary.value;
1952                         if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1953                                 /* *&x is a NOP */
1954                                 return determine_lhs_ent(val->unary.value, lhs_ent);
1955                         } else {
1956                                 mark_vars_read(val, NULL);
1957                                 return NULL;
1958                         }
1959                 }
1960
1961                 default:
1962                         mark_vars_read(expr, NULL);
1963                         return NULL;
1964         }
1965 }
1966
1967 #define ENT_ANY ((entity_t*)-1)
1968
1969 /**
1970  * Mark declarations, which are read.  This is used to detect variables, which
1971  * are never read.
1972  * Example:
1973  * x = x + 1;
1974  *   x is not marked as "read", because it is only read to calculate its own new
1975  *   value.
1976  *
1977  * x += y; y += x;
1978  *   x and y are not detected as "not read", because multiple variables are
1979  *   involved.
1980  */
1981 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1982 {
1983         switch (expr->kind) {
1984                 case EXPR_REFERENCE: {
1985                         entity_t *const entity = expr->reference.entity;
1986                         if (entity->kind != ENTITY_VARIABLE
1987                                         && entity->kind != ENTITY_PARAMETER)
1988                                 return;
1989
1990                         if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1991                                 if (entity->kind == ENTITY_VARIABLE) {
1992                                         entity->variable.read = true;
1993                                 } else {
1994                                         entity->parameter.read = true;
1995                                 }
1996                         }
1997                         return;
1998                 }
1999
2000                 case EXPR_CALL:
2001                         // TODO respect pure/const
2002                         mark_vars_read(expr->call.function, NULL);
2003                         for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2004                                 mark_vars_read(arg->expression, NULL);
2005                         }
2006                         return;
2007
2008                 case EXPR_CONDITIONAL:
2009                         // TODO lhs_decl should depend on whether true/false have an effect
2010                         mark_vars_read(expr->conditional.condition, NULL);
2011                         if (expr->conditional.true_expression != NULL)
2012                                 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2013                         mark_vars_read(expr->conditional.false_expression, lhs_ent);
2014                         return;
2015
2016                 case EXPR_SELECT:
2017                         if (lhs_ent == ENT_ANY
2018                                         && !is_type_compound(skip_typeref(expr->base.type)))
2019                                 lhs_ent = NULL;
2020                         mark_vars_read(expr->select.compound, lhs_ent);
2021                         return;
2022
2023                 case EXPR_ARRAY_ACCESS: {
2024                         expression_t *const ref = expr->array_access.array_ref;
2025                         mark_vars_read(ref, lhs_ent);
2026                         lhs_ent = determine_lhs_ent(ref, lhs_ent);
2027                         mark_vars_read(expr->array_access.index, lhs_ent);
2028                         return;
2029                 }
2030
2031                 case EXPR_VA_ARG:
2032                         mark_vars_read(expr->va_arge.ap, lhs_ent);
2033                         return;
2034
2035                 case EXPR_UNARY_CAST:
2036                         /* Special case: Use void cast to mark a variable as "read" */
2037                         if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2038                                 lhs_ent = NULL;
2039                         goto unary;
2040
2041
2042                 case EXPR_UNARY_THROW:
2043                         if (expr->unary.value == NULL)
2044                                 return;
2045                         /* FALLTHROUGH */
2046                 case EXPR_UNARY_DEREFERENCE:
2047                 case EXPR_UNARY_DELETE:
2048                 case EXPR_UNARY_DELETE_ARRAY:
2049                         if (lhs_ent == ENT_ANY)
2050                                 lhs_ent = NULL;
2051                         goto unary;
2052
2053                 case EXPR_UNARY_NEGATE:
2054                 case EXPR_UNARY_PLUS:
2055                 case EXPR_UNARY_BITWISE_NEGATE:
2056                 case EXPR_UNARY_NOT:
2057                 case EXPR_UNARY_TAKE_ADDRESS:
2058                 case EXPR_UNARY_POSTFIX_INCREMENT:
2059                 case EXPR_UNARY_POSTFIX_DECREMENT:
2060                 case EXPR_UNARY_PREFIX_INCREMENT:
2061                 case EXPR_UNARY_PREFIX_DECREMENT:
2062                 case EXPR_UNARY_CAST_IMPLICIT:
2063                 case EXPR_UNARY_ASSUME:
2064 unary:
2065                         mark_vars_read(expr->unary.value, lhs_ent);
2066                         return;
2067
2068                 case EXPR_BINARY_ADD:
2069                 case EXPR_BINARY_SUB:
2070                 case EXPR_BINARY_MUL:
2071                 case EXPR_BINARY_DIV:
2072                 case EXPR_BINARY_MOD:
2073                 case EXPR_BINARY_EQUAL:
2074                 case EXPR_BINARY_NOTEQUAL:
2075                 case EXPR_BINARY_LESS:
2076                 case EXPR_BINARY_LESSEQUAL:
2077                 case EXPR_BINARY_GREATER:
2078                 case EXPR_BINARY_GREATEREQUAL:
2079                 case EXPR_BINARY_BITWISE_AND:
2080                 case EXPR_BINARY_BITWISE_OR:
2081                 case EXPR_BINARY_BITWISE_XOR:
2082                 case EXPR_BINARY_LOGICAL_AND:
2083                 case EXPR_BINARY_LOGICAL_OR:
2084                 case EXPR_BINARY_SHIFTLEFT:
2085                 case EXPR_BINARY_SHIFTRIGHT:
2086                 case EXPR_BINARY_COMMA:
2087                 case EXPR_BINARY_ISGREATER:
2088                 case EXPR_BINARY_ISGREATEREQUAL:
2089                 case EXPR_BINARY_ISLESS:
2090                 case EXPR_BINARY_ISLESSEQUAL:
2091                 case EXPR_BINARY_ISLESSGREATER:
2092                 case EXPR_BINARY_ISUNORDERED:
2093                         mark_vars_read(expr->binary.left,  lhs_ent);
2094                         mark_vars_read(expr->binary.right, lhs_ent);
2095                         return;
2096
2097                 case EXPR_BINARY_ASSIGN:
2098                 case EXPR_BINARY_MUL_ASSIGN:
2099                 case EXPR_BINARY_DIV_ASSIGN:
2100                 case EXPR_BINARY_MOD_ASSIGN:
2101                 case EXPR_BINARY_ADD_ASSIGN:
2102                 case EXPR_BINARY_SUB_ASSIGN:
2103                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2104                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2105                 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2106                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2107                 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2108                         if (lhs_ent == ENT_ANY)
2109                                 lhs_ent = NULL;
2110                         lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2111                         mark_vars_read(expr->binary.right, lhs_ent);
2112                         return;
2113                 }
2114
2115                 case EXPR_VA_START:
2116                         determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2117                         return;
2118
2119                 case EXPR_UNKNOWN:
2120                 case EXPR_INVALID:
2121                 case EXPR_CONST:
2122                 case EXPR_CHARACTER_CONSTANT:
2123                 case EXPR_WIDE_CHARACTER_CONSTANT:
2124                 case EXPR_STRING_LITERAL:
2125                 case EXPR_WIDE_STRING_LITERAL:
2126                 case EXPR_COMPOUND_LITERAL: // TODO init?
2127                 case EXPR_SIZEOF:
2128                 case EXPR_CLASSIFY_TYPE:
2129                 case EXPR_ALIGNOF:
2130                 case EXPR_FUNCNAME:
2131                 case EXPR_BUILTIN_CONSTANT_P:
2132                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
2133                 case EXPR_OFFSETOF:
2134                 case EXPR_STATEMENT: // TODO
2135                 case EXPR_LABEL_ADDRESS:
2136                 case EXPR_REFERENCE_ENUM_VALUE:
2137                         return;
2138         }
2139
2140         panic("unhandled expression");
2141 }
2142
2143 static designator_t *parse_designation(void)
2144 {
2145         designator_t *result = NULL;
2146         designator_t *last   = NULL;
2147
2148         while (true) {
2149                 designator_t *designator;
2150                 switch (token.type) {
2151                 case '[':
2152                         designator = allocate_ast_zero(sizeof(designator[0]));
2153                         designator->source_position = token.source_position;
2154                         next_token();
2155                         add_anchor_token(']');
2156                         designator->array_index = parse_constant_expression();
2157                         rem_anchor_token(']');
2158                         expect(']', end_error);
2159                         break;
2160                 case '.':
2161                         designator = allocate_ast_zero(sizeof(designator[0]));
2162                         designator->source_position = token.source_position;
2163                         next_token();
2164                         if (token.type != T_IDENTIFIER) {
2165                                 parse_error_expected("while parsing designator",
2166                                                      T_IDENTIFIER, NULL);
2167                                 return NULL;
2168                         }
2169                         designator->symbol = token.v.symbol;
2170                         next_token();
2171                         break;
2172                 default:
2173                         expect('=', end_error);
2174                         return result;
2175                 }
2176
2177                 assert(designator != NULL);
2178                 if (last != NULL) {
2179                         last->next = designator;
2180                 } else {
2181                         result = designator;
2182                 }
2183                 last = designator;
2184         }
2185 end_error:
2186         return NULL;
2187 }
2188
2189 static initializer_t *initializer_from_string(array_type_t *type,
2190                                               const string_t *const string)
2191 {
2192         /* TODO: check len vs. size of array type */
2193         (void) type;
2194
2195         initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2196         initializer->string.string = *string;
2197
2198         return initializer;
2199 }
2200
2201 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2202                                                    wide_string_t *const string)
2203 {
2204         /* TODO: check len vs. size of array type */
2205         (void) type;
2206
2207         initializer_t *const initializer =
2208                 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2209         initializer->wide_string.string = *string;
2210
2211         return initializer;
2212 }
2213
2214 /**
2215  * Build an initializer from a given expression.
2216  */
2217 static initializer_t *initializer_from_expression(type_t *orig_type,
2218                                                   expression_t *expression)
2219 {
2220         /* TODO check that expression is a constant expression */
2221
2222         /* §6.7.8.14/15 char array may be initialized by string literals */
2223         type_t *type           = skip_typeref(orig_type);
2224         type_t *expr_type_orig = expression->base.type;
2225         type_t *expr_type      = skip_typeref(expr_type_orig);
2226         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2227                 array_type_t *const array_type   = &type->array;
2228                 type_t       *const element_type = skip_typeref(array_type->element_type);
2229
2230                 if (element_type->kind == TYPE_ATOMIC) {
2231                         atomic_type_kind_t akind = element_type->atomic.akind;
2232                         switch (expression->kind) {
2233                                 case EXPR_STRING_LITERAL:
2234                                         if (akind == ATOMIC_TYPE_CHAR
2235                                                         || akind == ATOMIC_TYPE_SCHAR
2236                                                         || akind == ATOMIC_TYPE_UCHAR) {
2237                                                 return initializer_from_string(array_type,
2238                                                         &expression->string.value);
2239                                         }
2240                                         break;
2241
2242                                 case EXPR_WIDE_STRING_LITERAL: {
2243                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2244                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
2245                                                 return initializer_from_wide_string(array_type,
2246                                                         &expression->wide_string.value);
2247                                         }
2248                                         break;
2249                                 }
2250
2251                                 default:
2252                                         break;
2253                         }
2254                 }
2255         }
2256
2257         assign_error_t error = semantic_assign(type, expression);
2258         if (error == ASSIGN_ERROR_INCOMPATIBLE)
2259                 return NULL;
2260         report_assign_error(error, type, expression, "initializer",
2261                             &expression->base.source_position);
2262
2263         initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2264 #if 0
2265         if (type->kind == TYPE_BITFIELD) {
2266                 type = type->bitfield.base_type;
2267         }
2268 #endif
2269         result->value.value = create_implicit_cast(expression, type);
2270
2271         return result;
2272 }
2273
2274 /**
2275  * Checks if a given expression can be used as an constant initializer.
2276  */
2277 static bool is_initializer_constant(const expression_t *expression)
2278 {
2279         return is_constant_expression(expression)
2280                 || is_address_constant(expression);
2281 }
2282
2283 /**
2284  * Parses an scalar initializer.
2285  *
2286  * §6.7.8.11; eat {} without warning
2287  */
2288 static initializer_t *parse_scalar_initializer(type_t *type,
2289                                                bool must_be_constant)
2290 {
2291         /* there might be extra {} hierarchies */
2292         int braces = 0;
2293         if (token.type == '{') {
2294                 if (warning.other)
2295                         warningf(HERE, "extra curly braces around scalar initializer");
2296                 do {
2297                         ++braces;
2298                         next_token();
2299                 } while (token.type == '{');
2300         }
2301
2302         expression_t *expression = parse_assignment_expression();
2303         mark_vars_read(expression, NULL);
2304         if (must_be_constant && !is_initializer_constant(expression)) {
2305                 errorf(&expression->base.source_position,
2306                        "Initialisation expression '%E' is not constant",
2307                        expression);
2308         }
2309
2310         initializer_t *initializer = initializer_from_expression(type, expression);
2311
2312         if (initializer == NULL) {
2313                 errorf(&expression->base.source_position,
2314                        "expression '%E' (type '%T') doesn't match expected type '%T'",
2315                        expression, expression->base.type, type);
2316                 /* TODO */
2317                 return NULL;
2318         }
2319
2320         bool additional_warning_displayed = false;
2321         while (braces > 0) {
2322                 if (token.type == ',') {
2323                         next_token();
2324                 }
2325                 if (token.type != '}') {
2326                         if (!additional_warning_displayed && warning.other) {
2327                                 warningf(HERE, "additional elements in scalar initializer");
2328                                 additional_warning_displayed = true;
2329                         }
2330                 }
2331                 eat_block();
2332                 braces--;
2333         }
2334
2335         return initializer;
2336 }
2337
2338 /**
2339  * An entry in the type path.
2340  */
2341 typedef struct type_path_entry_t type_path_entry_t;
2342 struct type_path_entry_t {
2343         type_t *type;       /**< the upper top type. restored to path->top_tye if this entry is popped. */
2344         union {
2345                 size_t         index;          /**< For array types: the current index. */
2346                 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2347         } v;
2348 };
2349
2350 /**
2351  * A type path expression a position inside compound or array types.
2352  */
2353 typedef struct type_path_t type_path_t;
2354 struct type_path_t {
2355         type_path_entry_t *path;         /**< An flexible array containing the current path. */
2356         type_t            *top_type;     /**< type of the element the path points */
2357         size_t             max_index;    /**< largest index in outermost array */
2358 };
2359
2360 /**
2361  * Prints a type path for debugging.
2362  */
2363 static __attribute__((unused)) void debug_print_type_path(
2364                 const type_path_t *path)
2365 {
2366         size_t len = ARR_LEN(path->path);
2367
2368         for (size_t i = 0; i < len; ++i) {
2369                 const type_path_entry_t *entry = & path->path[i];
2370
2371                 type_t *type = skip_typeref(entry->type);
2372                 if (is_type_compound(type)) {
2373                         /* in gcc mode structs can have no members */
2374                         if (entry->v.compound_entry == NULL) {
2375                                 assert(i == len-1);
2376                                 continue;
2377                         }
2378                         fprintf(stderr, ".%s",
2379                                 entry->v.compound_entry->base.symbol->string);
2380                 } else if (is_type_array(type)) {
2381                         fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2382                 } else {
2383                         fprintf(stderr, "-INVALID-");
2384                 }
2385         }
2386         if (path->top_type != NULL) {
2387                 fprintf(stderr, "  (");
2388                 print_type(path->top_type);
2389                 fprintf(stderr, ")");
2390         }
2391 }
2392
2393 /**
2394  * Return the top type path entry, ie. in a path
2395  * (type).a.b returns the b.
2396  */
2397 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2398 {
2399         size_t len = ARR_LEN(path->path);
2400         assert(len > 0);
2401         return &path->path[len-1];
2402 }
2403
2404 /**
2405  * Enlarge the type path by an (empty) element.
2406  */
2407 static type_path_entry_t *append_to_type_path(type_path_t *path)
2408 {
2409         size_t len = ARR_LEN(path->path);
2410         ARR_RESIZE(type_path_entry_t, path->path, len+1);
2411
2412         type_path_entry_t *result = & path->path[len];
2413         memset(result, 0, sizeof(result[0]));
2414         return result;
2415 }
2416
2417 /**
2418  * Descending into a sub-type. Enter the scope of the current top_type.
2419  */
2420 static void descend_into_subtype(type_path_t *path)
2421 {
2422         type_t *orig_top_type = path->top_type;
2423         type_t *top_type      = skip_typeref(orig_top_type);
2424
2425         type_path_entry_t *top = append_to_type_path(path);
2426         top->type              = top_type;
2427
2428         if (is_type_compound(top_type)) {
2429                 compound_t *compound  = top_type->compound.compound;
2430                 entity_t   *entry     = compound->members.entities;
2431
2432                 if (entry != NULL) {
2433                         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2434                         top->v.compound_entry = &entry->declaration;
2435                         path->top_type = entry->declaration.type;
2436                 } else {
2437                         path->top_type = NULL;
2438                 }
2439         } else if (is_type_array(top_type)) {
2440                 top->v.index   = 0;
2441                 path->top_type = top_type->array.element_type;
2442         } else {
2443                 assert(!is_type_valid(top_type));
2444         }
2445 }
2446
2447 /**
2448  * Pop an entry from the given type path, ie. returning from
2449  * (type).a.b to (type).a
2450  */
2451 static void ascend_from_subtype(type_path_t *path)
2452 {
2453         type_path_entry_t *top = get_type_path_top(path);
2454
2455         path->top_type = top->type;
2456
2457         size_t len = ARR_LEN(path->path);
2458         ARR_RESIZE(type_path_entry_t, path->path, len-1);
2459 }
2460
2461 /**
2462  * Pop entries from the given type path until the given
2463  * path level is reached.
2464  */
2465 static void ascend_to(type_path_t *path, size_t top_path_level)
2466 {
2467         size_t len = ARR_LEN(path->path);
2468
2469         while (len > top_path_level) {
2470                 ascend_from_subtype(path);
2471                 len = ARR_LEN(path->path);
2472         }
2473 }
2474
2475 static bool walk_designator(type_path_t *path, const designator_t *designator,
2476                             bool used_in_offsetof)
2477 {
2478         for (; designator != NULL; designator = designator->next) {
2479                 type_path_entry_t *top       = get_type_path_top(path);
2480                 type_t            *orig_type = top->type;
2481
2482                 type_t *type = skip_typeref(orig_type);
2483
2484                 if (designator->symbol != NULL) {
2485                         symbol_t *symbol = designator->symbol;
2486                         if (!is_type_compound(type)) {
2487                                 if (is_type_valid(type)) {
2488                                         errorf(&designator->source_position,
2489                                                "'.%Y' designator used for non-compound type '%T'",
2490                                                symbol, orig_type);
2491                                 }
2492
2493                                 top->type             = type_error_type;
2494                                 top->v.compound_entry = NULL;
2495                                 orig_type             = type_error_type;
2496                         } else {
2497                                 compound_t *compound = type->compound.compound;
2498                                 entity_t   *iter     = compound->members.entities;
2499                                 for (; iter != NULL; iter = iter->base.next) {
2500                                         if (iter->base.symbol == symbol) {
2501                                                 break;
2502                                         }
2503                                 }
2504                                 if (iter == NULL) {
2505                                         errorf(&designator->source_position,
2506                                                "'%T' has no member named '%Y'", orig_type, symbol);
2507                                         goto failed;
2508                                 }
2509                                 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2510                                 if (used_in_offsetof) {
2511                                         type_t *real_type = skip_typeref(iter->declaration.type);
2512                                         if (real_type->kind == TYPE_BITFIELD) {
2513                                                 errorf(&designator->source_position,
2514                                                        "offsetof designator '%Y' may not specify bitfield",
2515                                                        symbol);
2516                                                 goto failed;
2517                                         }
2518                                 }
2519
2520                                 top->type             = orig_type;
2521                                 top->v.compound_entry = &iter->declaration;
2522                                 orig_type             = iter->declaration.type;
2523                         }
2524                 } else {
2525                         expression_t *array_index = designator->array_index;
2526                         assert(designator->array_index != NULL);
2527
2528                         if (!is_type_array(type)) {
2529                                 if (is_type_valid(type)) {
2530                                         errorf(&designator->source_position,
2531                                                "[%E] designator used for non-array type '%T'",
2532                                                array_index, orig_type);
2533                                 }
2534                                 goto failed;
2535                         }
2536
2537                         long index = fold_constant(array_index);
2538                         if (!used_in_offsetof) {
2539                                 if (index < 0) {
2540                                         errorf(&designator->source_position,
2541                                                "array index [%E] must be positive", array_index);
2542                                 } else if (type->array.size_constant) {
2543                                         long array_size = type->array.size;
2544                                         if (index >= array_size) {
2545                                                 errorf(&designator->source_position,
2546                                                        "designator [%E] (%d) exceeds array size %d",
2547                                                        array_index, index, array_size);
2548                                         }
2549                                 }
2550                         }
2551
2552                         top->type    = orig_type;
2553                         top->v.index = (size_t) index;
2554                         orig_type    = type->array.element_type;
2555                 }
2556                 path->top_type = orig_type;
2557
2558                 if (designator->next != NULL) {
2559                         descend_into_subtype(path);
2560                 }
2561         }
2562         return true;
2563
2564 failed:
2565         return false;
2566 }
2567
2568 static void advance_current_object(type_path_t *path, size_t top_path_level)
2569 {
2570         type_path_entry_t *top = get_type_path_top(path);
2571
2572         type_t *type = skip_typeref(top->type);
2573         if (is_type_union(type)) {
2574                 /* in unions only the first element is initialized */
2575                 top->v.compound_entry = NULL;
2576         } else if (is_type_struct(type)) {
2577                 declaration_t *entry = top->v.compound_entry;
2578
2579                 entity_t *next_entity = entry->base.next;
2580                 if (next_entity != NULL) {
2581                         assert(is_declaration(next_entity));
2582                         entry = &next_entity->declaration;
2583                 } else {
2584                         entry = NULL;
2585                 }
2586
2587                 top->v.compound_entry = entry;
2588                 if (entry != NULL) {
2589                         path->top_type = entry->type;
2590                         return;
2591                 }
2592         } else if (is_type_array(type)) {
2593                 assert(is_type_array(type));
2594
2595                 top->v.index++;
2596
2597                 if (!type->array.size_constant || top->v.index < type->array.size) {
2598                         return;
2599                 }
2600         } else {
2601                 assert(!is_type_valid(type));
2602                 return;
2603         }
2604
2605         /* we're past the last member of the current sub-aggregate, try if we
2606          * can ascend in the type hierarchy and continue with another subobject */
2607         size_t len = ARR_LEN(path->path);
2608
2609         if (len > top_path_level) {
2610                 ascend_from_subtype(path);
2611                 advance_current_object(path, top_path_level);
2612         } else {
2613                 path->top_type = NULL;
2614         }
2615 }
2616
2617 /**
2618  * skip until token is found.
2619  */
2620 static void skip_until(int type)
2621 {
2622         while (token.type != type) {
2623                 if (token.type == T_EOF)
2624                         return;
2625                 next_token();
2626         }
2627 }
2628
2629 /**
2630  * skip any {...} blocks until a closing bracket is reached.
2631  */
2632 static void skip_initializers(void)
2633 {
2634         if (token.type == '{')
2635                 next_token();
2636
2637         while (token.type != '}') {
2638                 if (token.type == T_EOF)
2639                         return;
2640                 if (token.type == '{') {
2641                         eat_block();
2642                         continue;
2643                 }
2644                 next_token();
2645         }
2646 }
2647
2648 static initializer_t *create_empty_initializer(void)
2649 {
2650         static initializer_t empty_initializer
2651                 = { .list = { { INITIALIZER_LIST }, 0 } };
2652         return &empty_initializer;
2653 }
2654
2655 /**
2656  * Parse a part of an initialiser for a struct or union,
2657  */
2658 static initializer_t *parse_sub_initializer(type_path_t *path,
2659                 type_t *outer_type, size_t top_path_level,
2660                 parse_initializer_env_t *env)
2661 {
2662         if (token.type == '}') {
2663                 /* empty initializer */
2664                 return create_empty_initializer();
2665         }
2666
2667         type_t *orig_type = path->top_type;
2668         type_t *type      = NULL;
2669
2670         if (orig_type == NULL) {
2671                 /* We are initializing an empty compound. */
2672         } else {
2673                 type = skip_typeref(orig_type);
2674         }
2675
2676         initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2677
2678         while (true) {
2679                 designator_t *designator = NULL;
2680                 if (token.type == '.' || token.type == '[') {
2681                         designator = parse_designation();
2682                         goto finish_designator;
2683                 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2684                         /* GNU-style designator ("identifier: value") */
2685                         designator = allocate_ast_zero(sizeof(designator[0]));
2686                         designator->source_position = token.source_position;
2687                         designator->symbol          = token.v.symbol;
2688                         eat(T_IDENTIFIER);
2689                         eat(':');
2690
2691 finish_designator:
2692                         /* reset path to toplevel, evaluate designator from there */
2693                         ascend_to(path, top_path_level);
2694                         if (!walk_designator(path, designator, false)) {
2695                                 /* can't continue after designation error */
2696                                 goto end_error;
2697                         }
2698
2699                         initializer_t *designator_initializer
2700                                 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2701                         designator_initializer->designator.designator = designator;
2702                         ARR_APP1(initializer_t*, initializers, designator_initializer);
2703
2704                         orig_type = path->top_type;
2705                         type      = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2706                 }
2707
2708                 initializer_t *sub;
2709
2710                 if (token.type == '{') {
2711                         if (type != NULL && is_type_scalar(type)) {
2712                                 sub = parse_scalar_initializer(type, env->must_be_constant);
2713                         } else {
2714                                 eat('{');
2715                                 if (type == NULL) {
2716                                         if (env->entity != NULL) {
2717                                                 errorf(HERE,
2718                                                      "extra brace group at end of initializer for '%Y'",
2719                                                      env->entity->base.symbol);
2720                                         } else {
2721                                                 errorf(HERE, "extra brace group at end of initializer");
2722                                         }
2723                                 } else
2724                                         descend_into_subtype(path);
2725
2726                                 add_anchor_token('}');
2727                                 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2728                                                             env);
2729                                 rem_anchor_token('}');
2730
2731                                 if (type != NULL) {
2732                                         ascend_from_subtype(path);
2733                                         expect('}', end_error);
2734                                 } else {
2735                                         expect('}', end_error);
2736                                         goto error_parse_next;
2737                                 }
2738                         }
2739                 } else {
2740                         /* must be an expression */
2741                         expression_t *expression = parse_assignment_expression();
2742                         mark_vars_read(expression, NULL);
2743
2744                         if (env->must_be_constant && !is_initializer_constant(expression)) {
2745                                 errorf(&expression->base.source_position,
2746                                        "Initialisation expression '%E' is not constant",
2747                                        expression);
2748                         }
2749
2750                         if (type == NULL) {
2751                                 /* we are already outside, ... */
2752                                 type_t *const outer_type_skip = skip_typeref(outer_type);
2753                                 if (is_type_compound(outer_type_skip) &&
2754                                     !outer_type_skip->compound.compound->complete) {
2755                                         goto error_parse_next;
2756                                 }
2757                                 goto error_excess;
2758                         }
2759
2760                         /* handle { "string" } special case */
2761                         if ((expression->kind == EXPR_STRING_LITERAL
2762                                         || expression->kind == EXPR_WIDE_STRING_LITERAL)
2763                                         && outer_type != NULL) {
2764                                 sub = initializer_from_expression(outer_type, expression);
2765                                 if (sub != NULL) {
2766                                         if (token.type == ',') {
2767                                                 next_token();
2768                                         }
2769                                         if (token.type != '}' && warning.other) {
2770                                                 warningf(HERE, "excessive elements in initializer for type '%T'",
2771                                                                  orig_type);
2772                                         }
2773                                         /* TODO: eat , ... */
2774                                         return sub;
2775                                 }
2776                         }
2777
2778                         /* descend into subtypes until expression matches type */
2779                         while (true) {
2780                                 orig_type = path->top_type;
2781                                 type      = skip_typeref(orig_type);
2782
2783                                 sub = initializer_from_expression(orig_type, expression);
2784                                 if (sub != NULL) {
2785                                         break;
2786                                 }
2787                                 if (!is_type_valid(type)) {
2788                                         goto end_error;
2789                                 }
2790                                 if (is_type_scalar(type)) {
2791                                         errorf(&expression->base.source_position,
2792                                                         "expression '%E' doesn't match expected type '%T'",
2793                                                         expression, orig_type);
2794                                         goto end_error;
2795                                 }
2796
2797                                 descend_into_subtype(path);
2798                         }
2799                 }
2800
2801                 /* update largest index of top array */
2802                 const type_path_entry_t *first      = &path->path[0];
2803                 type_t                  *first_type = first->type;
2804                 first_type                          = skip_typeref(first_type);
2805                 if (is_type_array(first_type)) {
2806                         size_t index = first->v.index;
2807                         if (index > path->max_index)
2808                                 path->max_index = index;
2809                 }
2810
2811                 if (type != NULL) {
2812                         /* append to initializers list */
2813                         ARR_APP1(initializer_t*, initializers, sub);
2814                 } else {
2815 error_excess:
2816                         if (warning.other) {
2817                                 if (env->entity != NULL) {
2818                                         warningf(HERE, "excess elements in struct initializer for '%Y'",
2819                                            env->entity->base.symbol);
2820                                 } else {
2821                                         warningf(HERE, "excess elements in struct initializer");
2822                                 }
2823                         }
2824                 }
2825
2826 error_parse_next:
2827                 if (token.type == '}') {
2828                         break;
2829                 }
2830                 expect(',', end_error);
2831                 if (token.type == '}') {
2832                         break;
2833                 }
2834
2835                 if (type != NULL) {
2836                         /* advance to the next declaration if we are not at the end */
2837                         advance_current_object(path, top_path_level);
2838                         orig_type = path->top_type;
2839                         if (orig_type != NULL)
2840                                 type = skip_typeref(orig_type);
2841                         else
2842                                 type = NULL;
2843                 }
2844         }
2845
2846         size_t len  = ARR_LEN(initializers);
2847         size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2848         initializer_t *result = allocate_ast_zero(size);
2849         result->kind          = INITIALIZER_LIST;
2850         result->list.len      = len;
2851         memcpy(&result->list.initializers, initializers,
2852                len * sizeof(initializers[0]));
2853
2854         DEL_ARR_F(initializers);
2855         ascend_to(path, top_path_level+1);
2856
2857         return result;
2858
2859 end_error:
2860         skip_initializers();
2861         DEL_ARR_F(initializers);
2862         ascend_to(path, top_path_level+1);
2863         return NULL;
2864 }
2865
2866 /**
2867  * Parses an initializer. Parsers either a compound literal
2868  * (env->declaration == NULL) or an initializer of a declaration.
2869  */
2870 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2871 {
2872         type_t        *type      = skip_typeref(env->type);
2873         size_t         max_index = 0xdeadbeaf;   // TODO: Resolve this uninitialized variable problem
2874         initializer_t *result;
2875
2876         if (is_type_scalar(type)) {
2877                 result = parse_scalar_initializer(type, env->must_be_constant);
2878         } else if (token.type == '{') {
2879                 eat('{');
2880
2881                 type_path_t path;
2882                 memset(&path, 0, sizeof(path));
2883                 path.top_type = env->type;
2884                 path.path     = NEW_ARR_F(type_path_entry_t, 0);
2885
2886                 descend_into_subtype(&path);
2887
2888                 add_anchor_token('}');
2889                 result = parse_sub_initializer(&path, env->type, 1, env);
2890                 rem_anchor_token('}');
2891
2892                 max_index = path.max_index;
2893                 DEL_ARR_F(path.path);
2894
2895                 expect('}', end_error);
2896         } else {
2897                 /* parse_scalar_initializer() also works in this case: we simply
2898                  * have an expression without {} around it */
2899                 result = parse_scalar_initializer(type, env->must_be_constant);
2900         }
2901
2902         /* §6.7.8:22 array initializers for arrays with unknown size determine
2903          * the array type size */
2904         if (is_type_array(type) && type->array.size_expression == NULL
2905                         && result != NULL) {
2906                 size_t size;
2907                 switch (result->kind) {
2908                 case INITIALIZER_LIST:
2909                         assert(max_index != 0xdeadbeaf);
2910                         size = max_index + 1;
2911                         break;
2912
2913                 case INITIALIZER_STRING:
2914                         size = result->string.string.size;
2915                         break;
2916
2917                 case INITIALIZER_WIDE_STRING:
2918                         size = result->wide_string.string.size;
2919                         break;
2920
2921                 case INITIALIZER_DESIGNATOR:
2922                 case INITIALIZER_VALUE:
2923                         /* can happen for parse errors */
2924                         size = 0;
2925                         break;
2926
2927                 default:
2928                         internal_errorf(HERE, "invalid initializer type");
2929                 }
2930
2931                 expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2932                 cnst->base.type          = type_size_t;
2933                 cnst->conste.v.int_value = size;
2934
2935                 type_t *new_type = duplicate_type(type);
2936
2937                 new_type->array.size_expression   = cnst;
2938                 new_type->array.size_constant     = true;
2939                 new_type->array.has_implicit_size = true;
2940                 new_type->array.size              = size;
2941                 env->type = new_type;
2942         }
2943
2944         return result;
2945 end_error:
2946         return NULL;
2947 }
2948
2949 static void append_entity(scope_t *scope, entity_t *entity)
2950 {
2951         if (scope->last_entity != NULL) {
2952                 scope->last_entity->base.next = entity;
2953         } else {
2954                 scope->entities = entity;
2955         }
2956         scope->last_entity = entity;
2957 }
2958
2959
2960 static compound_t *parse_compound_type_specifier(bool is_struct)
2961 {
2962         gnu_attribute_t  *attributes = NULL;
2963         decl_modifiers_t  modifiers  = 0;
2964         if (is_struct) {
2965                 eat(T_struct);
2966         } else {
2967                 eat(T_union);
2968         }
2969
2970         symbol_t   *symbol   = NULL;
2971         compound_t *compound = NULL;
2972
2973         if (token.type == T___attribute__) {
2974                 modifiers |= parse_attributes(&attributes);
2975         }
2976
2977         if (token.type == T_IDENTIFIER) {
2978                 symbol = token.v.symbol;
2979                 next_token();
2980
2981                 namespace_tag_t const namespc =
2982                         is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2983                 entity_t *entity = get_entity(symbol, namespc);
2984                 if (entity != NULL) {
2985                         assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2986                         compound = &entity->compound;
2987                         if (compound->base.parent_scope != current_scope &&
2988                             (token.type == '{' || token.type == ';')) {
2989                                 /* we're in an inner scope and have a definition. Shadow
2990                                  * existing definition in outer scope */
2991                                 compound = NULL;
2992                         } else if (compound->complete && token.type == '{') {
2993                                 assert(symbol != NULL);
2994                                 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2995                                        is_struct ? "struct" : "union", symbol,
2996                                        &compound->base.source_position);
2997                                 /* clear members in the hope to avoid further errors */
2998                                 compound->members.entities = NULL;
2999                         }
3000                 }
3001         } else if (token.type != '{') {
3002                 if (is_struct) {
3003                         parse_error_expected("while parsing struct type specifier",
3004                                              T_IDENTIFIER, '{', NULL);
3005                 } else {
3006                         parse_error_expected("while parsing union type specifier",
3007                                              T_IDENTIFIER, '{', NULL);
3008                 }
3009
3010                 return NULL;
3011         }
3012
3013         if (compound == NULL) {
3014                 entity_kind_t  kind   = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3015                 entity_t      *entity = allocate_entity_zero(kind);
3016                 compound              = &entity->compound;
3017
3018                 compound->base.namespc =
3019                         (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3020                 compound->base.source_position = token.source_position;
3021                 compound->base.symbol          = symbol;
3022                 compound->base.parent_scope    = current_scope;
3023                 if (symbol != NULL) {
3024                         environment_push(entity);
3025                 }
3026                 append_entity(current_scope, entity);
3027         }
3028
3029         if (token.type == '{') {
3030                 parse_compound_type_entries(compound);
3031                 modifiers |= parse_attributes(&attributes);
3032
3033                 if (symbol == NULL) {
3034                         assert(anonymous_entity == NULL);
3035                         anonymous_entity = (entity_t*)compound;
3036                 }
3037         }
3038
3039         compound->modifiers |= modifiers;
3040         return compound;
3041 }
3042
3043 static void parse_enum_entries(type_t *const enum_type)
3044 {
3045         eat('{');
3046
3047         if (token.type == '}') {
3048                 errorf(HERE, "empty enum not allowed");
3049                 next_token();
3050                 return;
3051         }
3052
3053         add_anchor_token('}');
3054         do {
3055                 if (token.type != T_IDENTIFIER) {
3056                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3057                         eat_block();
3058                         rem_anchor_token('}');
3059                         return;
3060                 }
3061
3062                 entity_t *entity             = allocate_entity_zero(ENTITY_ENUM_VALUE);
3063                 entity->enum_value.enum_type = enum_type;
3064                 entity->base.symbol          = token.v.symbol;
3065                 entity->base.source_position = token.source_position;
3066                 next_token();
3067
3068                 if (token.type == '=') {
3069                         next_token();
3070                         expression_t *value = parse_constant_expression();
3071
3072                         value = create_implicit_cast(value, enum_type);
3073                         entity->enum_value.value = value;
3074
3075                         /* TODO semantic */
3076                 }
3077
3078                 record_entity(entity, false);
3079
3080                 if (token.type != ',')
3081                         break;
3082                 next_token();
3083         } while (token.type != '}');
3084         rem_anchor_token('}');
3085
3086         expect('}', end_error);
3087
3088 end_error:
3089         ;
3090 }
3091
3092 static type_t *parse_enum_specifier(void)
3093 {
3094         gnu_attribute_t *attributes = NULL;
3095         entity_t        *entity;
3096         symbol_t        *symbol;
3097
3098         eat(T_enum);
3099         if (token.type == T_IDENTIFIER) {
3100                 symbol = token.v.symbol;
3101                 next_token();
3102
3103                 entity = get_entity(symbol, NAMESPACE_ENUM);
3104                 if (entity != NULL) {
3105                         assert(entity->kind == ENTITY_ENUM);
3106                         if (entity->base.parent_scope != current_scope &&
3107                                         (token.type == '{' || token.type == ';')) {
3108                                 /* we're in an inner scope and have a definition. Shadow
3109                                  * existing definition in outer scope */
3110                                 entity = NULL;
3111                         } else if (entity->enume.complete && token.type == '{') {
3112                                 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3113                                                 symbol, &entity->base.source_position);
3114                         }
3115                 }
3116         } else if (token.type != '{') {
3117                 parse_error_expected("while parsing enum type specifier",
3118                                      T_IDENTIFIER, '{', NULL);
3119                 return NULL;
3120         } else {
3121                 entity  = NULL;
3122                 symbol  = NULL;
3123         }
3124
3125         if (entity == NULL) {
3126                 entity                       = allocate_entity_zero(ENTITY_ENUM);
3127                 entity->base.namespc         = NAMESPACE_ENUM;
3128                 entity->base.source_position = token.source_position;
3129                 entity->base.symbol          = symbol;
3130                 entity->base.parent_scope    = current_scope;
3131         }
3132
3133         type_t *const type = allocate_type_zero(TYPE_ENUM);
3134         type->enumt.enume  = &entity->enume;
3135         type->enumt.akind  = ATOMIC_TYPE_INT;
3136
3137         if (token.type == '{') {
3138                 if (symbol != NULL) {
3139                         environment_push(entity);
3140                 }
3141                 append_entity(current_scope, entity);
3142                 entity->enume.complete = true;
3143
3144                 parse_enum_entries(type);
3145                 parse_attributes(&attributes);
3146
3147                 if (symbol == NULL) {
3148                         assert(anonymous_entity == NULL);
3149                         anonymous_entity = entity;
3150                 }
3151         } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3152                 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3153                        symbol);
3154         }
3155
3156         return type;
3157 }
3158
3159 /**
3160  * if a symbol is a typedef to another type, return true
3161  */
3162 static bool is_typedef_symbol(symbol_t *symbol)
3163 {
3164         const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3165         return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3166 }
3167
3168 static type_t *parse_typeof(void)
3169 {
3170         eat(T___typeof__);
3171
3172         type_t *type;
3173
3174         expect('(', end_error);
3175         add_anchor_token(')');
3176
3177         expression_t *expression  = NULL;
3178
3179         bool old_type_prop     = in_type_prop;
3180         bool old_gcc_extension = in_gcc_extension;
3181         in_type_prop           = true;
3182
3183         while (token.type == T___extension__) {
3184                 /* This can be a prefix to a typename or an expression. */
3185                 next_token();
3186                 in_gcc_extension = true;
3187         }
3188         switch (token.type) {
3189         case T_IDENTIFIER:
3190                 if (is_typedef_symbol(token.v.symbol)) {
3191                         type = parse_typename();
3192                 } else {
3193                         expression = parse_expression();
3194                         type       = revert_automatic_type_conversion(expression);
3195                 }
3196                 break;
3197
3198         TYPENAME_START
3199                 type = parse_typename();
3200                 break;
3201
3202         default:
3203                 expression = parse_expression();
3204                 type       = expression->base.type;
3205                 break;
3206         }
3207         in_type_prop     = old_type_prop;
3208         in_gcc_extension = old_gcc_extension;
3209
3210         rem_anchor_token(')');
3211         expect(')', end_error);
3212
3213         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF);
3214         typeof_type->typeoft.expression  = expression;
3215         typeof_type->typeoft.typeof_type = type;
3216
3217         return typeof_type;
3218 end_error:
3219         return NULL;
3220 }
3221
3222 typedef enum specifiers_t {
3223         SPECIFIER_SIGNED    = 1 << 0,
3224         SPECIFIER_UNSIGNED  = 1 << 1,
3225         SPECIFIER_LONG      = 1 << 2,
3226         SPECIFIER_INT       = 1 << 3,
3227         SPECIFIER_DOUBLE    = 1 << 4,
3228         SPECIFIER_CHAR      = 1 << 5,
3229         SPECIFIER_WCHAR_T   = 1 << 6,
3230         SPECIFIER_SHORT     = 1 << 7,
3231         SPECIFIER_LONG_LONG = 1 << 8,
3232         SPECIFIER_FLOAT     = 1 << 9,
3233         SPECIFIER_BOOL      = 1 << 10,
3234         SPECIFIER_VOID      = 1 << 11,
3235         SPECIFIER_INT8      = 1 << 12,
3236         SPECIFIER_INT16     = 1 << 13,
3237         SPECIFIER_INT32     = 1 << 14,
3238         SPECIFIER_INT64     = 1 << 15,
3239         SPECIFIER_INT128    = 1 << 16,
3240         SPECIFIER_COMPLEX   = 1 << 17,
3241         SPECIFIER_IMAGINARY = 1 << 18,
3242 } specifiers_t;
3243
3244 static type_t *create_builtin_type(symbol_t *const symbol,
3245                                    type_t *const real_type)
3246 {
3247         type_t *type            = allocate_type_zero(TYPE_BUILTIN);
3248         type->builtin.symbol    = symbol;
3249         type->builtin.real_type = real_type;
3250         return identify_new_type(type);
3251 }
3252
3253 static type_t *get_typedef_type(symbol_t *symbol)
3254 {
3255         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3256         if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3257                 return NULL;
3258
3259         type_t *type            = allocate_type_zero(TYPE_TYPEDEF);
3260         type->typedeft.typedefe = &entity->typedefe;
3261
3262         return type;
3263 }
3264
3265 /**
3266  * check for the allowed MS alignment values.
3267  */
3268 static bool check_alignment_value(long long intvalue)
3269 {
3270         if (intvalue < 1 || intvalue > 8192) {
3271                 errorf(HERE, "illegal alignment value");
3272                 return false;
3273         }
3274         unsigned v = (unsigned)intvalue;
3275         for (unsigned i = 1; i <= 8192; i += i) {
3276                 if (i == v)
3277                         return true;
3278         }
3279         errorf(HERE, "alignment must be power of two");
3280         return false;
3281 }
3282
3283 #define DET_MOD(name, tag) do { \
3284         if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3285         *modifiers |= tag; \
3286 } while (0)
3287
3288 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3289 {
3290         decl_modifiers_t *modifiers = &specifiers->modifiers;
3291
3292         while (true) {
3293                 if (token.type == T_restrict) {
3294                         next_token();
3295                         DET_MOD(restrict, DM_RESTRICT);
3296                         goto end_loop;
3297                 } else if (token.type != T_IDENTIFIER)
3298                         break;
3299                 symbol_t *symbol = token.v.symbol;
3300                 if (symbol == sym_align) {
3301                         next_token();
3302                         expect('(', end_error);
3303                         if (token.type != T_INTEGER)
3304                                 goto end_error;
3305                         if (check_alignment_value(token.v.intvalue)) {
3306                                 if (specifiers->alignment != 0 && warning.other)
3307                                         warningf(HERE, "align used more than once");
3308                                 specifiers->alignment = (unsigned char)token.v.intvalue;
3309                         }
3310                         next_token();
3311                         expect(')', end_error);
3312                 } else if (symbol == sym_allocate) {
3313                         next_token();
3314                         expect('(', end_error);
3315                         if (token.type != T_IDENTIFIER)
3316                                 goto end_error;
3317                         (void)token.v.symbol;
3318                         expect(')', end_error);
3319                 } else if (symbol == sym_dllimport) {
3320                         next_token();
3321                         DET_MOD(dllimport, DM_DLLIMPORT);
3322                 } else if (symbol == sym_dllexport) {
3323                         next_token();
3324                         DET_MOD(dllexport, DM_DLLEXPORT);
3325                 } else if (symbol == sym_thread) {
3326                         next_token();
3327                         DET_MOD(thread, DM_THREAD);
3328                 } else if (symbol == sym_naked) {
3329                         next_token();
3330                         DET_MOD(naked, DM_NAKED);
3331                 } else if (symbol == sym_noinline) {
3332                         next_token();
3333                         DET_MOD(noinline, DM_NOINLINE);
3334                 } else if (symbol == sym_returns_twice) {
3335                         next_token();
3336                         DET_MOD(returns_twice, DM_RETURNS_TWICE);
3337                 } else if (symbol == sym_noreturn) {
3338                         next_token();
3339                         DET_MOD(noreturn, DM_NORETURN);
3340                 } else if (symbol == sym_nothrow) {
3341                         next_token();
3342                         DET_MOD(nothrow, DM_NOTHROW);
3343                 } else if (symbol == sym_novtable) {
3344                         next_token();
3345                         DET_MOD(novtable, DM_NOVTABLE);
3346                 } else if (symbol == sym_property) {
3347                         next_token();
3348                         expect('(', end_error);
3349                         for (;;) {
3350                                 bool is_get = false;
3351                                 if (token.type != T_IDENTIFIER)
3352                                         goto end_error;
3353                                 if (token.v.symbol == sym_get) {
3354                                         is_get = true;
3355                                 } else if (token.v.symbol == sym_put) {
3356                                 } else {
3357                                         errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3358                                         goto end_error;
3359                                 }
3360                                 next_token();
3361                                 expect('=', end_error);
3362                                 if (token.type != T_IDENTIFIER)
3363                                         goto end_error;
3364                                 if (is_get) {
3365                                         if (specifiers->get_property_sym != NULL) {
3366                                                 errorf(HERE, "get property name already specified");
3367                                         } else {
3368                                                 specifiers->get_property_sym = token.v.symbol;
3369                                         }
3370                                 } else {
3371                                         if (specifiers->put_property_sym != NULL) {
3372                                                 errorf(HERE, "put property name already specified");
3373                                         } else {
3374                                                 specifiers->put_property_sym = token.v.symbol;
3375                                         }
3376                                 }
3377                                 next_token();
3378                                 if (token.type == ',') {
3379                                         next_token();
3380                                         continue;
3381                                 }
3382                                 break;
3383                         }
3384                         expect(')', end_error);
3385                 } else if (symbol == sym_selectany) {
3386                         next_token();
3387                         DET_MOD(selectany, DM_SELECTANY);
3388                 } else if (symbol == sym_uuid) {
3389                         next_token();
3390                         expect('(', end_error);
3391                         if (token.type != T_STRING_LITERAL)
3392                                 goto end_error;
3393                         next_token();
3394                         expect(')', end_error);
3395                 } else if (symbol == sym_deprecated) {
3396                         next_token();
3397                         if (specifiers->deprecated != 0 && warning.other)
3398                                 warningf(HERE, "deprecated used more than once");
3399                         specifiers->deprecated = true;
3400                         if (token.type == '(') {
3401                                 next_token();
3402                                 if (token.type == T_STRING_LITERAL) {
3403                                         specifiers->deprecated_string = token.v.string.begin;
3404                                         next_token();
3405                                 } else {
3406                                         errorf(HERE, "string literal expected");
3407                                 }
3408                                 expect(')', end_error);
3409                         }
3410                 } else if (symbol == sym_noalias) {
3411                         next_token();
3412                         DET_MOD(noalias, DM_NOALIAS);
3413                 } else {
3414                         if (warning.other)
3415                                 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3416                         next_token();
3417                         if (token.type == '(')
3418                                 skip_until(')');
3419                 }
3420 end_loop:
3421                 if (token.type == ',')
3422                         next_token();
3423         }
3424 end_error:
3425         return;
3426 }
3427
3428 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3429 {
3430         entity_t *entity             = allocate_entity_zero(kind);
3431         entity->base.source_position = *HERE;
3432         entity->base.symbol          = symbol;
3433         if (is_declaration(entity)) {
3434                 entity->declaration.type     = type_error_type;
3435                 entity->declaration.implicit = true;
3436         } else if (kind == ENTITY_TYPEDEF) {
3437                 entity->typedefe.type    = type_error_type;
3438                 entity->typedefe.builtin = true;
3439         }
3440         if (kind != ENTITY_COMPOUND_MEMBER)
3441                 record_entity(entity, false);
3442         return entity;
3443 }
3444
3445 static variable_t *parse_microsoft_based(void)
3446 {
3447         if (token.type != T_IDENTIFIER) {
3448                 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3449                 return NULL;
3450         }
3451         symbol_t *symbol = token.v.symbol;
3452         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3453
3454         variable_t *variable;
3455         if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3456                 errorf(HERE, "'%Y' is not a variable name.", symbol);
3457                 variable = &create_error_entity(symbol, ENTITY_VARIABLE)->variable;
3458         } else {
3459                 variable = &entity->variable;
3460
3461                 type_t *const type = variable->base.type;
3462                 if (is_type_valid(type)) {
3463                         if (! is_type_pointer(skip_typeref(type))) {
3464                                 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3465                         }
3466                         if (variable->base.base.parent_scope != file_scope) {
3467                                 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3468                         }
3469                 }
3470         }
3471         next_token();
3472         return variable;
3473 }
3474
3475 /**
3476  * Finish the construction of a struct type by calculating
3477  * its size, offsets, alignment.
3478  */
3479 static void finish_struct_type(compound_type_t *type)
3480 {
3481         assert(type->compound != NULL);
3482
3483         compound_t *compound = type->compound;
3484         if (!compound->complete)
3485                 return;
3486
3487         il_size_t      size           = 0;
3488         il_size_t      offset;
3489         il_alignment_t alignment      = 1;
3490         bool           need_pad       = false;
3491
3492         entity_t *entry = compound->members.entities;
3493         for (; entry != NULL; entry = entry->base.next) {
3494                 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3495                         continue;
3496
3497                 type_t *m_type = skip_typeref(entry->declaration.type);
3498                 if (! is_type_valid(m_type)) {
3499                         /* simply ignore errors here */
3500                         continue;
3501                 }
3502                 il_alignment_t m_alignment = m_type->base.alignment;
3503                 if (m_alignment > alignment)
3504                         alignment = m_alignment;
3505
3506                 offset = (size + m_alignment - 1) & -m_alignment;
3507
3508                 if (offset > size)
3509                         need_pad = true;
3510                 entry->compound_member.offset = offset;
3511                 size = offset + m_type->base.size;
3512         }
3513         if (type->base.alignment != 0) {
3514                 alignment = type->base.alignment;
3515         }
3516
3517         offset = (size + alignment - 1) & -alignment;
3518         if (offset > size)
3519                 need_pad = true;
3520
3521         if (need_pad) {
3522                 if (warning.padded) {
3523                         warningf(&compound->base.source_position, "'%T' needs padding", type);
3524                 }
3525         } else {
3526                 if (compound->modifiers & DM_PACKED && warning.packed) {
3527                         warningf(&compound->base.source_position,
3528                                         "superfluous packed attribute on '%T'", type);
3529                 }
3530         }
3531
3532         type->base.size      = offset;
3533         type->base.alignment = alignment;
3534 }
3535
3536 /**
3537  * Finish the construction of an union type by calculating
3538  * its size and alignment.
3539  */
3540 static void finish_union_type(compound_type_t *type)
3541 {
3542         assert(type->compound != NULL);
3543
3544         compound_t *compound = type->compound;
3545         if (! compound->complete)
3546                 return;
3547
3548         il_size_t      size      = 0;
3549         il_alignment_t alignment = 1;
3550
3551         entity_t *entry = compound->members.entities;
3552         for (; entry != NULL; entry = entry->base.next) {
3553                 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3554                         continue;
3555
3556                 type_t *m_type = skip_typeref(entry->declaration.type);
3557                 if (! is_type_valid(m_type))
3558                         continue;
3559
3560                 entry->compound_member.offset = 0;
3561                 if (m_type->base.size > size)
3562                         size = m_type->base.size;
3563                 if (m_type->base.alignment > alignment)
3564                         alignment = m_type->base.alignment;
3565         }
3566         if (type->base.alignment != 0) {
3567                 alignment = type->base.alignment;
3568         }
3569         size = (size + alignment - 1) & -alignment;
3570         type->base.size      = size;
3571         type->base.alignment = alignment;
3572 }
3573
3574 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3575                                      type_t *orig_type)
3576 {
3577         type_t *type = skip_typeref(orig_type);
3578
3579         /* at least: byte, word, pointer, list of machine modes
3580          * __XXX___ is interpreted as XXX */
3581
3582         /* This isn't really correct, the backend should provide a list of machine
3583          * specific modes (according to gcc philosophy that is...) */
3584         const char         *symbol_str = attribute->u.symbol->string;
3585         bool                sign       = is_type_signed(type);
3586         atomic_type_kind_t  akind;
3587         if (strcmp_underscore("QI",   symbol_str) == 0 ||
3588             strcmp_underscore("byte", symbol_str) == 0) {
3589                 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3590         } else if (strcmp_underscore("HI", symbol_str) == 0) {
3591                 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3592         } else if (strcmp_underscore("SI",      symbol_str) == 0
3593                 || strcmp_underscore("word",    symbol_str) == 0
3594                 || strcmp_underscore("pointer", symbol_str) == 0) {
3595                 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3596         } else if (strcmp_underscore("DI", symbol_str) == 0) {
3597                 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3598         } else {
3599                 if (warning.other)
3600                         warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3601                 return orig_type;
3602         }
3603
3604         if (type->kind == TYPE_ATOMIC) {
3605                 type_t *copy       = duplicate_type(type);
3606                 copy->atomic.akind = akind;
3607                 return identify_new_type(copy);
3608         } else if (type->kind == TYPE_ENUM) {
3609                 type_t *copy      = duplicate_type(type);
3610                 copy->enumt.akind = akind;
3611                 return identify_new_type(copy);
3612         } else if (is_type_pointer(type)) {
3613                 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3614                 return type;
3615         }
3616
3617         errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3618         return orig_type;
3619 }
3620
3621 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3622                                       type_t *type)
3623 {
3624         const gnu_attribute_t *attribute = attributes;
3625         for ( ; attribute != NULL; attribute = attribute->next) {
3626                 if (attribute->invalid)
3627                         continue;
3628
3629                 if (attribute->kind == GNU_AK_MODE) {
3630                         type = handle_attribute_mode(attribute, type);
3631                 } else if (attribute->kind == GNU_AK_ALIGNED) {
3632                         int alignment = 32; /* TODO: fill in maximum useful alignment for
3633                                                target machine */
3634                         if (attribute->has_arguments)
3635                                 alignment = attribute->u.argument;
3636
3637                         type_t *copy         = duplicate_type(type);
3638                         copy->base.alignment = attribute->u.argument;
3639                         type                 = identify_new_type(copy);
3640                 }
3641         }
3642
3643         return type;
3644 }
3645
3646 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3647 {
3648         type_t            *type              = NULL;
3649         type_qualifiers_t  qualifiers        = TYPE_QUALIFIER_NONE;
3650         type_modifiers_t   modifiers         = TYPE_MODIFIER_NONE;
3651         unsigned           type_specifiers   = 0;
3652         bool               newtype           = false;
3653         bool               saw_error         = false;
3654         bool               old_gcc_extension = in_gcc_extension;
3655
3656         specifiers->source_position = token.source_position;
3657
3658         while (true) {
3659                 specifiers->modifiers
3660                         |= parse_attributes(&specifiers->gnu_attributes);
3661
3662                 switch (token.type) {
3663                 /* storage class */
3664 #define MATCH_STORAGE_CLASS(token, class)                                  \
3665                 case token:                                                        \
3666                         if (specifiers->storage_class != STORAGE_CLASS_NONE) {         \
3667                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3668                         }                                                              \
3669                         specifiers->storage_class = class;                             \
3670                         if (specifiers->thread_local)                                  \
3671                                 goto check_thread_storage_class;                           \
3672                         next_token();                                                  \
3673                         break;
3674
3675                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
3676                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
3677                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
3678                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
3679                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3680
3681                 case T__declspec:
3682                         next_token();
3683                         expect('(', end_error);
3684                         add_anchor_token(')');
3685                         parse_microsoft_extended_decl_modifier(specifiers);
3686                         rem_anchor_token(')');
3687                         expect(')', end_error);
3688                         break;
3689
3690                 case T___thread:
3691                         if (specifiers->thread_local) {
3692                                 errorf(HERE, "duplicate '__thread'");
3693                         } else {
3694                                 specifiers->thread_local = true;
3695 check_thread_storage_class:
3696                                 switch (specifiers->storage_class) {
3697                                         case STORAGE_CLASS_EXTERN:
3698                                         case STORAGE_CLASS_NONE:
3699                                         case STORAGE_CLASS_STATIC:
3700                                                 break;
3701
3702                                                 char const* wrong;
3703                                         case STORAGE_CLASS_AUTO:     wrong = "auto";     goto wrong_thread_stoarge_class;
3704                                         case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3705                                         case STORAGE_CLASS_TYPEDEF:  wrong = "typedef";  goto wrong_thread_stoarge_class;
3706 wrong_thread_stoarge_class:
3707                                                 errorf(HERE, "'__thread' used with '%s'", wrong);
3708                                                 break;
3709                                 }
3710                         }
3711                         next_token();
3712                         break;
3713
3714                 /* type qualifiers */
3715 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
3716                 case token:                                                     \
3717                         qualifiers |= qualifier;                                    \
3718                         next_token();                                               \
3719                         break
3720
3721                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3722                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3723                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3724                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3725                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3726                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3727                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3728                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3729
3730                 case T___extension__:
3731                         next_token();
3732                         in_gcc_extension = true;
3733                         break;
3734
3735                 /* type specifiers */
3736 #define MATCH_SPECIFIER(token, specifier, name)                         \
3737                 case token:                                                     \
3738                         if (type_specifiers & specifier) {                           \
3739                                 errorf(HERE, "multiple " name " type specifiers given"); \
3740                         } else {                                                    \
3741                                 type_specifiers |= specifier;                           \
3742                         }                                                           \
3743                         next_token();                                               \
3744                         break
3745
3746                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool");
3747                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex");
3748                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3749                 MATCH_SPECIFIER(T__int128,    SPECIFIER_INT128,    "_int128");
3750                 MATCH_SPECIFIER(T__int16,     SPECIFIER_INT16,     "_int16");
3751                 MATCH_SPECIFIER(T__int32,     SPECIFIER_INT32,     "_int32");
3752                 MATCH_SPECIFIER(T__int64,     SPECIFIER_INT64,     "_int64");
3753                 MATCH_SPECIFIER(T__int8,      SPECIFIER_INT8,      "_int8");
3754                 MATCH_SPECIFIER(T_bool,       SPECIFIER_BOOL,      "bool");
3755                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char");
3756                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double");
3757                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float");
3758                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int");
3759                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short");
3760                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed");
3761                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned");
3762                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void");
3763                 MATCH_SPECIFIER(T_wchar_t,    SPECIFIER_WCHAR_T,   "wchar_t");
3764
3765                 case T__forceinline:
3766                         /* only in microsoft mode */
3767                         specifiers->modifiers |= DM_FORCEINLINE;
3768                         /* FALLTHROUGH */
3769
3770                 case T_inline:
3771                         next_token();
3772                         specifiers->is_inline = true;
3773                         break;
3774
3775                 case T_long:
3776                         if (type_specifiers & SPECIFIER_LONG_LONG) {
3777                                 errorf(HERE, "multiple type specifiers given");
3778                         } else if (type_specifiers & SPECIFIER_LONG) {
3779                                 type_specifiers |= SPECIFIER_LONG_LONG;
3780                         } else {
3781                                 type_specifiers |= SPECIFIER_LONG;
3782                         }
3783                         next_token();
3784                         break;
3785
3786                 case T_struct: {
3787                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3788
3789                         type->compound.compound = parse_compound_type_specifier(true);
3790                         finish_struct_type(&type->compound);
3791                         break;
3792                 }
3793                 case T_union: {
3794                         type = allocate_type_zero(TYPE_COMPOUND_UNION);
3795                         type->compound.compound = parse_compound_type_specifier(false);
3796                         if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3797                                 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3798                         finish_union_type(&type->compound);
3799                         break;
3800                 }
3801                 case T_enum:
3802                         type = parse_enum_specifier();
3803                         break;
3804                 case T___typeof__:
3805                         type = parse_typeof();
3806                         break;
3807                 case T___builtin_va_list:
3808                         type = duplicate_type(type_valist);
3809                         next_token();
3810                         break;
3811
3812                 case T_IDENTIFIER: {
3813                         /* only parse identifier if we haven't found a type yet */
3814                         if (type != NULL || type_specifiers != 0) {
3815                                 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3816                                  * declaration, so it doesn't generate errors about expecting '(' or
3817                                  * '{' later on. */
3818                                 switch (look_ahead(1)->type) {
3819                                         STORAGE_CLASSES
3820                                         TYPE_SPECIFIERS
3821                                         case T_const:
3822                                         case T_restrict:
3823                                         case T_volatile:
3824                                         case T_inline:
3825                                         case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3826                                         case T_IDENTIFIER:
3827                                         case '&':
3828                                         case '*':
3829                                                 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3830                                                 next_token();
3831                                                 continue;
3832
3833                                         default:
3834                                                 goto finish_specifiers;
3835                                 }
3836                         }
3837
3838                         type_t *const typedef_type = get_typedef_type(token.v.symbol);
3839                         if (typedef_type == NULL) {
3840                                 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3841                                  * declaration, so it doesn't generate 'implicit int' followed by more
3842                                  * errors later on. */
3843                                 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3844                                 switch (la1_type) {
3845                                         DECLARATION_START
3846                                         case T_IDENTIFIER:
3847                                         case '&':
3848                                         case '*': {
3849                                                 errorf(HERE, "%K does not name a type", &token);
3850
3851                                                 entity_t *entity =
3852                                                         create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3853
3854                                                 type = allocate_type_zero(TYPE_TYPEDEF);
3855                                                 type->typedeft.typedefe = &entity->typedefe;
3856
3857                                                 next_token();
3858                                                 saw_error = true;
3859                                                 if (la1_type == '&' || la1_type == '*')
3860                                                         goto finish_specifiers;
3861                                                 continue;
3862                                         }
3863
3864                                         default:
3865                                                 goto finish_specifiers;
3866                                 }
3867                         }
3868
3869                         next_token();
3870                         type = typedef_type;
3871                         break;
3872                 }
3873
3874                 /* function specifier */
3875                 default:
3876                         goto finish_specifiers;
3877                 }
3878         }
3879
3880 finish_specifiers:
3881         specifiers->modifiers
3882                 |= parse_attributes(&specifiers->gnu_attributes);
3883
3884         in_gcc_extension = old_gcc_extension;
3885
3886         if (type == NULL || (saw_error && type_specifiers != 0)) {
3887                 atomic_type_kind_t atomic_type;
3888
3889                 /* match valid basic types */
3890                 switch (type_specifiers) {
3891                 case SPECIFIER_VOID:
3892                         atomic_type = ATOMIC_TYPE_VOID;
3893                         break;
3894                 case SPECIFIER_WCHAR_T:
3895                         atomic_type = ATOMIC_TYPE_WCHAR_T;
3896                         break;
3897                 case SPECIFIER_CHAR:
3898                         atomic_type = ATOMIC_TYPE_CHAR;
3899                         break;
3900                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3901                         atomic_type = ATOMIC_TYPE_SCHAR;
3902                         break;
3903                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3904                         atomic_type = ATOMIC_TYPE_UCHAR;
3905                         break;
3906                 case SPECIFIER_SHORT:
3907                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3908                 case SPECIFIER_SHORT | SPECIFIER_INT:
3909                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3910                         atomic_type = ATOMIC_TYPE_SHORT;
3911                         break;
3912                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3913                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3914                         atomic_type = ATOMIC_TYPE_USHORT;
3915                         break;
3916                 case SPECIFIER_INT:
3917                 case SPECIFIER_SIGNED:
3918                 case SPECIFIER_SIGNED | SPECIFIER_INT:
3919                         atomic_type = ATOMIC_TYPE_INT;
3920                         break;
3921                 case SPECIFIER_UNSIGNED:
3922                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3923                         atomic_type = ATOMIC_TYPE_UINT;
3924                         break;
3925                 case SPECIFIER_LONG:
3926                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3927                 case SPECIFIER_LONG | SPECIFIER_INT:
3928                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3929                         atomic_type = ATOMIC_TYPE_LONG;
3930                         break;
3931                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3932                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3933                         atomic_type = ATOMIC_TYPE_ULONG;
3934                         break;
3935
3936                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3937                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3938                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3939                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3940                         | SPECIFIER_INT:
3941                         atomic_type = ATOMIC_TYPE_LONGLONG;
3942                         goto warn_about_long_long;
3943
3944                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3945                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3946                         | SPECIFIER_INT:
3947                         atomic_type = ATOMIC_TYPE_ULONGLONG;
3948 warn_about_long_long:
3949                         if (warning.long_long) {
3950                                 warningf(&specifiers->source_position,
3951                                          "ISO C90 does not support 'long long'");
3952                         }
3953                         break;
3954
3955                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3956                         atomic_type = unsigned_int8_type_kind;
3957                         break;
3958
3959                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3960                         atomic_type = unsigned_int16_type_kind;
3961                         break;
3962
3963                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3964                         atomic_type = unsigned_int32_type_kind;
3965                         break;
3966
3967                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3968                         atomic_type = unsigned_int64_type_kind;
3969                         break;
3970
3971                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3972                         atomic_type = unsigned_int128_type_kind;
3973                         break;
3974
3975                 case SPECIFIER_INT8:
3976                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3977                         atomic_type = int8_type_kind;
3978                         break;
3979
3980                 case SPECIFIER_INT16:
3981                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3982                         atomic_type = int16_type_kind;
3983                         break;
3984
3985                 case SPECIFIER_INT32:
3986                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3987                         atomic_type = int32_type_kind;
3988                         break;
3989
3990                 case SPECIFIER_INT64:
3991                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3992                         atomic_type = int64_type_kind;
3993                         break;
3994
3995                 case SPECIFIER_INT128:
3996                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3997                         atomic_type = int128_type_kind;
3998                         break;
3999
4000                 case SPECIFIER_FLOAT:
4001                         atomic_type = ATOMIC_TYPE_FLOAT;
4002                         break;
4003                 case SPECIFIER_DOUBLE:
4004                         atomic_type = ATOMIC_TYPE_DOUBLE;
4005                         break;
4006                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4007                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4008                         break;
4009                 case SPECIFIER_BOOL:
4010                         atomic_type = ATOMIC_TYPE_BOOL;
4011                         break;
4012                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4013                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4014                         atomic_type = ATOMIC_TYPE_FLOAT;
4015                         break;
4016                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4017                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4018                         atomic_type = ATOMIC_TYPE_DOUBLE;
4019                         break;
4020                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4021                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4022                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4023                         break;
4024                 default:
4025                         /* invalid specifier combination, give an error message */
4026                         if (type_specifiers == 0) {
4027                                 if (saw_error)
4028                                         goto end_error;
4029
4030                                 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4031                                 if (!(c_mode & _CXX) && !strict_mode) {
4032                                         if (warning.implicit_int) {
4033                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
4034                                         }
4035                                         atomic_type = ATOMIC_TYPE_INT;
4036                                         break;
4037                                 } else {
4038                                         errorf(HERE, "no type specifiers given in declaration");
4039                                 }
4040                         } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4041                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
4042                                 errorf(HERE, "signed and unsigned specifiers given");
4043                         } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4044                                 errorf(HERE, "only integer types can be signed or unsigned");
4045                         } else {
4046                                 errorf(HERE, "multiple datatypes in declaration");
4047                         }
4048                         goto end_error;
4049                 }
4050
4051                 if (type_specifiers & SPECIFIER_COMPLEX) {
4052                         type                = allocate_type_zero(TYPE_COMPLEX);
4053                         type->complex.akind = atomic_type;
4054                 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4055                         type                  = allocate_type_zero(TYPE_IMAGINARY);
4056                         type->imaginary.akind = atomic_type;
4057                 } else {
4058                         type                 = allocate_type_zero(TYPE_ATOMIC);
4059                         type->atomic.akind   = atomic_type;
4060                 }
4061                 type->base.alignment = get_atomic_type_alignment(atomic_type);
4062                 unsigned const size  = get_atomic_type_size(atomic_type);
4063                 type->base.size      =
4064                         type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4065                 newtype = true;
4066         } else if (type_specifiers != 0) {
4067                 errorf(HERE, "multiple datatypes in declaration");
4068         }
4069
4070         /* FIXME: check type qualifiers here */
4071
4072         if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4073                 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4074         type->base.qualifiers = qualifiers;
4075         type->base.modifiers  = modifiers;
4076
4077         if (newtype) {
4078                 type = identify_new_type(type);
4079         } else {
4080                 type = typehash_insert(type);
4081         }
4082
4083         type = handle_type_attributes(specifiers->gnu_attributes, type);
4084         specifiers->type = type;
4085         return;
4086
4087 end_error:
4088         specifiers->type = type_error_type;
4089         return;
4090 }
4091
4092 static type_qualifiers_t parse_type_qualifiers(void)
4093 {
4094         type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4095
4096         while (true) {
4097                 switch (token.type) {
4098                 /* type qualifiers */
4099                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
4100                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4101                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4102                 /* microsoft extended type modifiers */
4103                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
4104                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
4105                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
4106                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
4107                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
4108
4109                 default:
4110                         return qualifiers;
4111                 }
4112         }
4113 }
4114
4115 /**
4116  * Parses an K&R identifier list
4117  */
4118 static void parse_identifier_list(scope_t *scope)
4119 {
4120         do {
4121                 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4122                 entity->base.source_position = token.source_position;
4123                 entity->base.namespc         = NAMESPACE_NORMAL;
4124                 entity->base.symbol          = token.v.symbol;
4125                 /* a K&R parameter has no type, yet */
4126                 next_token();
4127
4128                 if (scope != NULL)
4129                         append_entity(scope, entity);
4130
4131                 if (token.type != ',') {
4132                         break;
4133                 }
4134                 next_token();
4135         } while (token.type == T_IDENTIFIER);
4136 }
4137
4138 static entity_t *parse_parameter(void)
4139 {
4140         declaration_specifiers_t specifiers;
4141         memset(&specifiers, 0, sizeof(specifiers));
4142
4143         parse_declaration_specifiers(&specifiers);
4144
4145         entity_t *entity = parse_declarator(&specifiers,
4146                         DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4147         anonymous_entity = NULL;
4148         return entity;
4149 }
4150
4151 static void semantic_parameter_incomplete(const entity_t *entity)
4152 {
4153         assert(entity->kind == ENTITY_PARAMETER);
4154
4155         /* §6.7.5.3:4  After adjustment, the parameters in a parameter type
4156          *             list in a function declarator that is part of a
4157          *             definition of that function shall not have
4158          *             incomplete type. */
4159         type_t *type = skip_typeref(entity->declaration.type);
4160         if (is_type_incomplete(type)) {
4161                 errorf(&entity->base.source_position,
4162                        "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4163                        entity->declaration.type);
4164         }
4165 }
4166
4167 static bool has_parameters(void)
4168 {
4169         /* func(void) is not a parameter */
4170         if (token.type == T_IDENTIFIER) {
4171                 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
4172                 if (entity->kind != ENTITY_TYPEDEF)
4173                         return true;
4174                 if (skip_typeref(entity->typedefe.type) != type_void)
4175                         return true;
4176         } else if (token.type != T_void) {
4177                 return true;
4178         }
4179         if (look_ahead(1)->type != ')')
4180                 return true;
4181         next_token();
4182         return false;
4183 }
4184
4185 /**
4186  * Parses function type parameters (and optionally creates variable_t entities
4187  * for them in a scope)
4188  */
4189 static void parse_parameters(function_type_t *type, scope_t *scope)
4190 {
4191         eat('(');
4192         add_anchor_token(')');
4193         int saved_comma_state = save_and_reset_anchor_state(',');
4194
4195         if (token.type == T_IDENTIFIER &&
4196             !is_typedef_symbol(token.v.symbol)) {
4197                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4198                 if (la1_type == ',' || la1_type == ')') {
4199                         type->kr_style_parameters    = true;
4200                         type->unspecified_parameters = true;
4201                         parse_identifier_list(scope);
4202                         goto parameters_finished;
4203                 }
4204         }
4205
4206         if (token.type == ')') {
4207                 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4208                 if (!(c_mode & _CXX))
4209                         type->unspecified_parameters = true;
4210                 goto parameters_finished;
4211         }
4212
4213         if (has_parameters()) {
4214                 function_parameter_t **anchor = &type->parameters;
4215                 for (;;) {
4216                         switch (token.type) {
4217                         case T_DOTDOTDOT:
4218                                 next_token();
4219                                 type->variadic = true;
4220                                 goto parameters_finished;
4221
4222                         case T_IDENTIFIER:
4223                         case T___extension__:
4224                         DECLARATION_START
4225                         {
4226                                 entity_t *entity = parse_parameter();
4227                                 if (entity->kind == ENTITY_TYPEDEF) {
4228                                         errorf(&entity->base.source_position,
4229                                                         "typedef not allowed as function parameter");
4230                                         break;
4231                                 }
4232                                 assert(is_declaration(entity));
4233
4234                                 semantic_parameter_incomplete(entity);
4235
4236                                 function_parameter_t *const parameter =
4237                                         allocate_parameter(entity->declaration.type);
4238
4239                                 if (scope != NULL) {
4240                                         append_entity(scope, entity);
4241                                 }
4242
4243                                 *anchor = parameter;
4244                                 anchor  = &parameter->next;
4245                                 break;
4246                         }
4247
4248                         default:
4249                                 goto parameters_finished;
4250                         }
4251                         if (token.type != ',') {
4252                                 goto parameters_finished;
4253                         }
4254                         next_token();
4255                 }
4256         }
4257
4258
4259 parameters_finished:
4260         rem_anchor_token(')');
4261         expect(')', end_error);
4262
4263 end_error:
4264         restore_anchor_state(',', saved_comma_state);
4265 }
4266
4267 typedef enum construct_type_kind_t {
4268         CONSTRUCT_INVALID,
4269         CONSTRUCT_POINTER,
4270         CONSTRUCT_REFERENCE,
4271         CONSTRUCT_FUNCTION,
4272         CONSTRUCT_ARRAY
4273 } construct_type_kind_t;
4274
4275 typedef union construct_type_t construct_type_t;
4276
4277 typedef struct construct_type_base_t {
4278         construct_type_kind_t  kind;
4279         construct_type_t      *next;
4280 } construct_type_base_t;
4281
4282 typedef struct parsed_pointer_t {
4283         construct_type_base_t  base;
4284         type_qualifiers_t      type_qualifiers;
4285         variable_t             *base_variable;  /**< MS __based extension. */
4286 } parsed_pointer_t;
4287
4288 typedef struct parsed_reference_t {
4289         construct_type_base_t base;
4290 } parsed_reference_t;
4291
4292 typedef struct construct_function_type_t {
4293         construct_type_base_t  base;
4294         type_t                *function_type;
4295 } construct_function_type_t;
4296
4297 typedef struct parsed_array_t {
4298         construct_type_base_t  base;
4299         type_qualifiers_t      type_qualifiers;
4300         bool                   is_static;
4301         bool                   is_variable;
4302         expression_t          *size;
4303 } parsed_array_t;
4304
4305 union construct_type_t {
4306         construct_type_kind_t     kind;
4307         construct_type_base_t     base;
4308         parsed_pointer_t          pointer;
4309         parsed_reference_t        reference;
4310         construct_function_type_t function;
4311         parsed_array_t            array;
4312 };
4313
4314 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4315 {
4316         eat('*');
4317
4318         construct_type_t *cons    = obstack_alloc(&temp_obst, sizeof(cons->pointer));
4319         parsed_pointer_t *pointer = &cons->pointer;
4320         memset(pointer, 0, sizeof(*pointer));
4321         cons->kind               = CONSTRUCT_POINTER;
4322         pointer->type_qualifiers = parse_type_qualifiers();
4323         pointer->base_variable   = base_variable;
4324
4325         return cons;
4326 }
4327
4328 static construct_type_t *parse_reference_declarator(void)
4329 {
4330         eat('&');
4331
4332         construct_type_t   *cons      = obstack_alloc(&temp_obst, sizeof(cons->reference));
4333         parsed_reference_t *reference = &cons->reference;
4334         memset(reference, 0, sizeof(*reference));
4335         cons->kind = CONSTRUCT_REFERENCE;
4336
4337         return cons;
4338 }
4339
4340 static construct_type_t *parse_array_declarator(void)
4341 {
4342         eat('[');
4343         add_anchor_token(']');
4344
4345         construct_type_t *cons  = obstack_alloc(&temp_obst, sizeof(cons->array));
4346         parsed_array_t   *array = &cons->array;
4347         memset(array, 0, sizeof(*array));
4348         cons->kind = CONSTRUCT_ARRAY;
4349
4350         if (token.type == T_static) {
4351                 array->is_static = true;
4352                 next_token();
4353         }
4354
4355         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4356         if (type_qualifiers != 0) {
4357                 if (token.type == T_static) {
4358                         array->is_static = true;
4359                         next_token();
4360                 }
4361         }
4362         array->type_qualifiers = type_qualifiers;
4363
4364         if (token.type == '*' && look_ahead(1)->type == ']') {
4365                 array->is_variable = true;
4366                 next_token();
4367         } else if (token.type != ']') {
4368                 expression_t *const size = parse_assignment_expression();
4369                 array->size = size;
4370                 mark_vars_read(size, NULL);
4371         }
4372
4373         rem_anchor_token(']');
4374         expect(']', end_error);
4375
4376 end_error:
4377         return cons;
4378 }
4379
4380 static construct_type_t *parse_function_declarator(scope_t *scope,
4381                                                    decl_modifiers_t modifiers)
4382 {
4383         type_t          *type  = allocate_type_zero(TYPE_FUNCTION);
4384         function_type_t *ftype = &type->function;
4385
4386         ftype->linkage = current_linkage;
4387
4388         switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4389                 case DM_NONE:     break;
4390                 case DM_CDECL:    ftype->calling_convention = CC_CDECL;    break;
4391                 case DM_STDCALL:  ftype->calling_convention = CC_STDCALL;  break;
4392                 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4393                 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4394
4395                 default:
4396                         errorf(HERE, "multiple calling conventions in declaration");
4397                         break;
4398         }
4399
4400         parse_parameters(ftype, scope);
4401
4402         construct_type_t          *cons     = obstack_alloc(&temp_obst, sizeof(cons->function));
4403         construct_function_type_t *function = &cons->function;
4404         memset(function, 0, sizeof(*function));
4405         cons->kind              = CONSTRUCT_FUNCTION;
4406         function->function_type = type;
4407
4408         return cons;
4409 }
4410
4411 typedef struct parse_declarator_env_t {
4412         decl_modifiers_t   modifiers;
4413         symbol_t          *symbol;
4414         source_position_t  source_position;
4415         scope_t            parameters;
4416 } parse_declarator_env_t;
4417
4418 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4419                 bool may_be_abstract)
4420 {
4421         /* construct a single linked list of construct_type_t's which describe
4422          * how to construct the final declarator type */
4423         construct_type_t  *first      = NULL;
4424         construct_type_t **anchor     = &first;
4425         gnu_attribute_t   *attributes = NULL;
4426
4427         decl_modifiers_t modifiers = parse_attributes(&attributes);
4428
4429         for (;;) {
4430                 construct_type_t *type;
4431                 variable_t       *based = NULL; /* MS __based extension */
4432                 switch (token.type) {
4433                         case '&':
4434                                 if (!(c_mode & _CXX))
4435                                         errorf(HERE, "references are only available for C++");
4436                                 type = parse_reference_declarator();
4437                                 break;
4438
4439                         case T__based: {
4440                                 source_position_t const pos = *HERE;
4441                                 next_token();
4442                                 expect('(', end_error);
4443                                 add_anchor_token(')');
4444                                 based = parse_microsoft_based();
4445                                 rem_anchor_token(')');
4446                                 expect(')', end_error);
4447                                 if (token.type != '*') {
4448                                         if (token.type == T__based) {
4449                                                 errorf(&pos, "__based type modifier specified more than once");
4450                                         } else if (warning.other) {
4451                                                 warningf(&pos,
4452                                                                 "__based does not precede a pointer declarator, ignored");
4453                                         }
4454                                         continue;
4455                                 }
4456                                 /* FALLTHROUGH */
4457                         }
4458
4459                         case '*':
4460                                 type = parse_pointer_declarator(based);
4461                                 break;
4462
4463                         default:
4464                                 goto ptr_operator_end;
4465                 }
4466
4467                 *anchor = type;
4468                 anchor  = &type->base.next;
4469
4470                 /* TODO: find out if this is correct */
4471                 modifiers |= parse_attributes(&attributes);
4472         }
4473 ptr_operator_end:
4474
4475         if (env != NULL) {
4476                 modifiers      |= env->modifiers;
4477                 env->modifiers  = modifiers;
4478         }
4479
4480         construct_type_t *inner_types = NULL;
4481
4482         switch (token.type) {
4483         case T_IDENTIFIER:
4484                 if (env == NULL) {
4485                         errorf(HERE, "no identifier expected in typename");
4486                 } else {
4487                         env->symbol          = token.v.symbol;
4488                         env->source_position = token.source_position;
4489                 }
4490                 next_token();
4491                 break;
4492         case '(':
4493                 /* §6.7.6:2 footnote 126:  Empty parentheses in a type name are
4494                  * interpreted as ``function with no parameter specification'', rather
4495                  * than redundant parentheses around the omitted identifier. */
4496                 if (look_ahead(1)->type != ')') {
4497                         next_token();
4498                         add_anchor_token(')');
4499                         inner_types = parse_inner_declarator(env, may_be_abstract);
4500                         if (inner_types != NULL) {
4501                                 /* All later declarators only modify the return type */
4502                                 env = NULL;
4503                         }
4504                         rem_anchor_token(')');
4505                         expect(')', end_error);
4506                 }
4507                 break;
4508         default:
4509                 if (may_be_abstract)
4510                         break;
4511                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4512                 eat_until_anchor();
4513                 return NULL;
4514         }
4515
4516         construct_type_t **const p = anchor;
4517
4518         for (;;) {
4519                 construct_type_t *type;
4520                 switch (token.type) {
4521                 case '(': {
4522                         scope_t *scope = NULL;
4523                         if (env != NULL)
4524                                 scope = &env->parameters;
4525
4526                         type = parse_function_declarator(scope, modifiers);
4527                         break;
4528                 }
4529                 case '[':
4530                         type = parse_array_declarator();
4531                         break;
4532                 default:
4533                         goto declarator_finished;
4534                 }
4535
4536                 /* insert in the middle of the list (at p) */
4537                 type->base.next = *p;
4538                 *p              = type;
4539                 if (anchor == p)
4540                         anchor = &type->base.next;
4541         }
4542
4543 declarator_finished:
4544         /* append inner_types at the end of the list, we don't to set anchor anymore
4545          * as it's not needed anymore */
4546         *anchor = inner_types;
4547
4548         return first;
4549 end_error:
4550         return NULL;
4551 }
4552
4553 static void parse_declaration_attributes(entity_t *entity)
4554 {
4555         gnu_attribute_t  *attributes = NULL;
4556         decl_modifiers_t  modifiers  = parse_attributes(&attributes);
4557
4558         if (entity == NULL)
4559                 return;
4560
4561         type_t *type;
4562         if (entity->kind == ENTITY_TYPEDEF) {
4563                 modifiers |= entity->typedefe.modifiers;
4564                 type       = entity->typedefe.type;
4565         } else {
4566                 assert(is_declaration(entity));
4567                 modifiers |= entity->declaration.modifiers;
4568                 type       = entity->declaration.type;
4569         }
4570         if (type == NULL)
4571                 return;
4572
4573         gnu_attribute_t *attribute = attributes;
4574         for ( ; attribute != NULL; attribute = attribute->next) {
4575                 if (attribute->invalid)
4576                         continue;
4577
4578                 if (attribute->kind == GNU_AK_MODE) {
4579                         type = handle_attribute_mode(attribute, type);
4580                 } else if (attribute->kind == GNU_AK_ALIGNED) {
4581                         int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4582                         if (attribute->has_arguments)
4583                                 alignment = attribute->u.argument;
4584
4585                         if (entity->kind == ENTITY_TYPEDEF) {
4586                                 type_t *copy         = duplicate_type(type);
4587                                 copy->base.alignment = attribute->u.argument;
4588                                 type                 = identify_new_type(copy);
4589                         } else if(entity->kind == ENTITY_VARIABLE) {
4590                                 entity->variable.alignment = alignment;
4591                         } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4592                                 entity->compound_member.alignment = alignment;
4593                         }
4594                 }
4595         }
4596
4597         type_modifiers_t type_modifiers = type->base.modifiers;
4598         if (modifiers & DM_TRANSPARENT_UNION)
4599                 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4600
4601         if (type->base.modifiers != type_modifiers) {
4602                 type_t *copy         = duplicate_type(type);
4603                 copy->base.modifiers = type_modifiers;
4604                 type                 = identify_new_type(copy);
4605         }
4606
4607         if (entity->kind == ENTITY_TYPEDEF) {
4608                 entity->typedefe.type      = type;
4609                 entity->typedefe.modifiers = modifiers;
4610         } else {
4611                 entity->declaration.type      = type;
4612                 entity->declaration.modifiers = modifiers;
4613         }
4614 }
4615
4616 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4617 {
4618         construct_type_t *iter = construct_list;
4619         for (; iter != NULL; iter = iter->base.next) {
4620                 switch (iter->kind) {
4621                 case CONSTRUCT_INVALID:
4622                         break;
4623                 case CONSTRUCT_FUNCTION: {
4624                         construct_function_type_t *function      = &iter->function;
4625                         type_t                    *function_type = function->function_type;
4626
4627                         function_type->function.return_type = type;
4628
4629                         type_t *skipped_return_type = skip_typeref(type);
4630                         /* §6.7.5.3:1 */
4631                         if (is_type_function(skipped_return_type)) {
4632                                 errorf(HERE, "function returning function is not allowed");
4633                         } else if (is_type_array(skipped_return_type)) {
4634                                 errorf(HERE, "function returning array is not allowed");
4635                         } else {
4636                                 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4637                                         warningf(HERE,
4638                                                 "type qualifiers in return type of function type are meaningless");
4639                                 }
4640                         }
4641
4642                         /* The function type was constructed earlier.  Freeing it here will
4643                          * destroy other types. */
4644                         type = typehash_insert(function_type);
4645                         continue;
4646                 }
4647
4648                 case CONSTRUCT_POINTER: {
4649                         if (is_type_reference(skip_typeref(type)))
4650                                 errorf(HERE, "cannot declare a pointer to reference");
4651
4652                         parsed_pointer_t *pointer = &iter->pointer;
4653                         type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
4654                         continue;
4655                 }
4656
4657                 case CONSTRUCT_REFERENCE:
4658                         if (is_type_reference(skip_typeref(type)))
4659                                 errorf(HERE, "cannot declare a reference to reference");
4660
4661                         type = make_reference_type(type);
4662                         continue;
4663
4664                 case CONSTRUCT_ARRAY: {
4665                         if (is_type_reference(skip_typeref(type)))
4666                                 errorf(HERE, "cannot declare an array of references");
4667
4668                         parsed_array_t *array      = &iter->array;
4669                         type_t         *array_type = allocate_type_zero(TYPE_ARRAY);
4670
4671                         expression_t *size_expression = array->size;
4672                         if (size_expression != NULL) {
4673                                 size_expression
4674                                         = create_implicit_cast(size_expression, type_size_t);
4675                         }
4676
4677                         array_type->base.qualifiers       = array->type_qualifiers;
4678                         array_type->array.element_type    = type;
4679                         array_type->array.is_static       = array->is_static;
4680                         array_type->array.is_variable     = array->is_variable;
4681                         array_type->array.size_expression = size_expression;
4682
4683                         if (size_expression != NULL) {
4684                                 if (is_constant_expression(size_expression)) {
4685                                         array_type->array.size_constant = true;
4686                                         array_type->array.size
4687                                                 = fold_constant(size_expression);
4688                                 } else {
4689                                         array_type->array.is_vla = true;
4690                                 }
4691                         }
4692
4693                         type_t *skipped_type = skip_typeref(type);
4694                         /* §6.7.5.2:1 */
4695                         if (is_type_incomplete(skipped_type)) {
4696                                 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4697                         } else if (is_type_function(skipped_type)) {
4698                                 errorf(HERE, "array of functions is not allowed");
4699                         }
4700                         type = identify_new_type(array_type);
4701                         continue;
4702                 }
4703                 }
4704                 internal_errorf(HERE, "invalid type construction found");
4705         }
4706
4707         return type;
4708 }
4709
4710 static type_t *automatic_type_conversion(type_t *orig_type);
4711
4712 static type_t *semantic_parameter(const source_position_t *pos,
4713                                   type_t *type,
4714                                   const declaration_specifiers_t *specifiers,
4715                                   symbol_t *symbol)
4716 {
4717         /* §6.7.5.3:7  A declaration of a parameter as ``array of type''
4718          *             shall be adjusted to ``qualified pointer to type'',
4719          *             [...]
4720          * §6.7.5.3:8  A declaration of a parameter as ``function returning
4721          *             type'' shall be adjusted to ``pointer to function
4722          *             returning type'', as in 6.3.2.1. */
4723         type = automatic_type_conversion(type);
4724
4725         if (specifiers->is_inline && is_type_valid(type)) {
4726                 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4727         }
4728
4729         /* §6.9.1:6  The declarations in the declaration list shall contain
4730          *           no storage-class specifier other than register and no
4731          *           initializations. */
4732         if (specifiers->thread_local || (
4733                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
4734                         specifiers->storage_class != STORAGE_CLASS_REGISTER)
4735            ) {
4736                 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4737         }
4738
4739         /* delay test for incomplete type, because we might have (void)
4740          * which is legal but incomplete... */
4741
4742         return type;
4743 }
4744
4745 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4746                                   declarator_flags_t flags)
4747 {
4748         parse_declarator_env_t env;
4749         memset(&env, 0, sizeof(env));
4750         env.modifiers = specifiers->modifiers;
4751
4752         construct_type_t *construct_type =
4753                 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4754         type_t           *orig_type      =
4755                 construct_declarator_type(construct_type, specifiers->type);
4756         type_t           *type           = skip_typeref(orig_type);
4757
4758         if (construct_type != NULL) {
4759                 obstack_free(&temp_obst, construct_type);
4760         }
4761
4762         entity_t *entity;
4763         if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4764                 entity                       = allocate_entity_zero(ENTITY_TYPEDEF);
4765                 entity->base.symbol          = env.symbol;
4766                 entity->base.source_position = env.source_position;
4767                 entity->typedefe.type        = orig_type;
4768
4769                 if (anonymous_entity != NULL) {
4770                         if (is_type_compound(type)) {
4771                                 assert(anonymous_entity->compound.alias == NULL);
4772                                 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4773                                        anonymous_entity->kind == ENTITY_UNION);
4774                                 anonymous_entity->compound.alias = entity;
4775                                 anonymous_entity = NULL;
4776                         } else if (is_type_enum(type)) {
4777                                 assert(anonymous_entity->enume.alias == NULL);
4778                                 assert(anonymous_entity->kind == ENTITY_ENUM);
4779                                 anonymous_entity->enume.alias = entity;
4780                                 anonymous_entity = NULL;
4781                         }
4782                 }
4783         } else {
4784                 /* create a declaration type entity */
4785                 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4786                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4787
4788                         if (env.symbol != NULL) {
4789                                 if (specifiers->is_inline && is_type_valid(type)) {
4790                                         errorf(&env.source_position,
4791                                                         "compound member '%Y' declared 'inline'", env.symbol);
4792                                 }
4793
4794                                 if (specifiers->thread_local ||
4795                                                 specifiers->storage_class != STORAGE_CLASS_NONE) {
4796                                         errorf(&env.source_position,
4797                                                         "compound member '%Y' must have no storage class",
4798                                                         env.symbol);
4799                                 }
4800                         }
4801                 } else if (flags & DECL_IS_PARAMETER) {
4802                         orig_type = semantic_parameter(&env.source_position, orig_type,
4803                                                        specifiers, env.symbol);
4804
4805                         entity = allocate_entity_zero(ENTITY_PARAMETER);
4806                 } else if (is_type_function(type)) {
4807                         entity = allocate_entity_zero(ENTITY_FUNCTION);
4808
4809                         entity->function.is_inline  = specifiers->is_inline;
4810                         entity->function.parameters = env.parameters;
4811
4812                         if (env.symbol != NULL) {
4813                                 if (specifiers->thread_local || (
4814                                                         specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4815                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
4816                                                         specifiers->storage_class != STORAGE_CLASS_STATIC
4817                                                 )) {
4818                                         errorf(&env.source_position,
4819                                                         "invalid storage class for function '%Y'", env.symbol);
4820                                 }
4821                         }
4822                 } else {
4823                         entity = allocate_entity_zero(ENTITY_VARIABLE);
4824
4825                         entity->variable.get_property_sym = specifiers->get_property_sym;
4826                         entity->variable.put_property_sym = specifiers->put_property_sym;
4827
4828                         entity->variable.thread_local = specifiers->thread_local;
4829
4830                         if (env.symbol != NULL) {
4831                                 if (specifiers->is_inline && is_type_valid(type)) {
4832                                         errorf(&env.source_position,
4833                                                         "variable '%Y' declared 'inline'", env.symbol);
4834                                 }
4835
4836                                 bool invalid_storage_class = false;
4837                                 if (current_scope == file_scope) {
4838                                         if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4839                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
4840                                                         specifiers->storage_class != STORAGE_CLASS_STATIC) {
4841                                                 invalid_storage_class = true;
4842                                         }
4843                                 } else {
4844                                         if (specifiers->thread_local &&
4845                                                         specifiers->storage_class == STORAGE_CLASS_NONE) {
4846                                                 invalid_storage_class = true;
4847                                         }
4848                                 }
4849                                 if (invalid_storage_class) {
4850                                         errorf(&env.source_position,
4851                                                         "invalid storage class for variable '%Y'", env.symbol);
4852                                 }
4853                         }
4854                 }
4855
4856                 if (env.symbol != NULL) {
4857                         entity->base.symbol          = env.symbol;
4858                         entity->base.source_position = env.source_position;
4859                 } else {
4860                         entity->base.source_position = specifiers->source_position;
4861                 }
4862                 entity->base.namespc                  = NAMESPACE_NORMAL;
4863                 entity->declaration.type              = orig_type;
4864                 entity->declaration.modifiers         = env.modifiers;
4865                 entity->declaration.deprecated_string = specifiers->deprecated_string;
4866
4867                 storage_class_t storage_class = specifiers->storage_class;
4868                 entity->declaration.declared_storage_class = storage_class;
4869
4870                 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4871                         storage_class = STORAGE_CLASS_AUTO;
4872                 entity->declaration.storage_class = storage_class;
4873         }
4874
4875         parse_declaration_attributes(entity);
4876
4877         return entity;
4878 }
4879
4880 static type_t *parse_abstract_declarator(type_t *base_type)
4881 {
4882         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4883
4884         type_t *result = construct_declarator_type(construct_type, base_type);
4885         if (construct_type != NULL) {
4886                 obstack_free(&temp_obst, construct_type);
4887         }
4888
4889         return result;
4890 }
4891
4892 /**
4893  * Check if the declaration of main is suspicious.  main should be a
4894  * function with external linkage, returning int, taking either zero
4895  * arguments, two, or three arguments of appropriate types, ie.
4896  *
4897  * int main([ int argc, char **argv [, char **env ] ]).
4898  *
4899  * @param decl    the declaration to check
4900  * @param type    the function type of the declaration
4901  */
4902 static void check_type_of_main(const entity_t *entity)
4903 {
4904         const source_position_t *pos = &entity->base.source_position;
4905         if (entity->kind != ENTITY_FUNCTION) {
4906                 warningf(pos, "'main' is not a function");
4907                 return;
4908         }
4909
4910         if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4911                 warningf(pos, "'main' is normally a non-static function");
4912         }
4913
4914         type_t *type = skip_typeref(entity->declaration.type);
4915         assert(is_type_function(type));
4916
4917         function_type_t *func_type = &type->function;
4918         if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4919                 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4920                          func_type->return_type);
4921         }
4922         const function_parameter_t *parm = func_type->parameters;
4923         if (parm != NULL) {
4924                 type_t *const first_type = parm->type;
4925                 if (!types_compatible(skip_typeref(first_type), type_int)) {
4926                         warningf(pos,
4927                                  "first argument of 'main' should be 'int', but is '%T'",
4928                                  first_type);
4929                 }
4930                 parm = parm->next;
4931                 if (parm != NULL) {
4932                         type_t *const second_type = parm->type;
4933                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4934                                 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4935                         }
4936                         parm = parm->next;
4937                         if (parm != NULL) {
4938                                 type_t *const third_type = parm->type;
4939                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4940                                         warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4941                                 }
4942                                 parm = parm->next;
4943                                 if (parm != NULL)
4944                                         goto warn_arg_count;
4945                         }
4946                 } else {
4947 warn_arg_count:
4948                         warningf(pos, "'main' takes only zero, two or three arguments");
4949                 }
4950         }
4951 }
4952
4953 /**
4954  * Check if a symbol is the equal to "main".
4955  */
4956 static bool is_sym_main(const symbol_t *const sym)
4957 {
4958         return strcmp(sym->string, "main") == 0;
4959 }
4960
4961 static void error_redefined_as_different_kind(const source_position_t *pos,
4962                 const entity_t *old, entity_kind_t new_kind)
4963 {
4964         errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4965                get_entity_kind_name(old->kind), old->base.symbol,
4966                get_entity_kind_name(new_kind), &old->base.source_position);
4967 }
4968
4969 static bool is_error_entity(entity_t *const ent)
4970 {
4971         if (is_declaration(ent)) {
4972                 return is_type_valid(skip_typeref(ent->declaration.type));
4973         } else if (ent->kind == ENTITY_TYPEDEF) {
4974                 return is_type_valid(skip_typeref(ent->typedefe.type));
4975         }
4976         return false;
4977 }
4978
4979 /**
4980  * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4981  * for various problems that occur for multiple definitions
4982  */
4983 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4984 {
4985         const symbol_t *const    symbol  = entity->base.symbol;
4986         const namespace_tag_t    namespc = (namespace_tag_t)entity->base.namespc;
4987         const source_position_t *pos     = &entity->base.source_position;
4988
4989         /* can happen in error cases */
4990         if (symbol == NULL)
4991                 return entity;
4992
4993         entity_t *const previous_entity = get_entity(symbol, namespc);
4994         /* pushing the same entity twice will break the stack structure */
4995         assert(previous_entity != entity);
4996
4997         if (entity->kind == ENTITY_FUNCTION) {
4998                 type_t *const orig_type = entity->declaration.type;
4999                 type_t *const type      = skip_typeref(orig_type);
5000
5001                 assert(is_type_function(type));
5002                 if (type->function.unspecified_parameters &&
5003                                 warning.strict_prototypes &&
5004                                 previous_entity == NULL) {
5005                         warningf(pos, "function declaration '%#T' is not a prototype",
5006                                          orig_type, symbol);
5007                 }
5008
5009                 if (warning.main && current_scope == file_scope
5010                                 && is_sym_main(symbol)) {
5011                         check_type_of_main(entity);
5012                 }
5013         }
5014
5015         if (is_declaration(entity) &&
5016                         warning.nested_externs &&
5017                         entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5018                         current_scope != file_scope) {
5019                 warningf(pos, "nested extern declaration of '%#T'",
5020                          entity->declaration.type, symbol);
5021         }
5022
5023         if (previous_entity != NULL) {
5024                 if (previous_entity->base.parent_scope == &current_function->parameters &&
5025                                 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5026                         assert(previous_entity->kind == ENTITY_PARAMETER);
5027                         errorf(pos,
5028                                         "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5029                                         entity->declaration.type, symbol,
5030                                         previous_entity->declaration.type, symbol,
5031                                         &previous_entity->base.source_position);
5032                         goto finish;
5033                 }
5034
5035                 if (previous_entity->base.parent_scope == current_scope) {
5036                         if (previous_entity->kind != entity->kind) {
5037                                 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
5038                                         error_redefined_as_different_kind(pos, previous_entity,
5039                                                         entity->kind);
5040                                 }
5041                                 goto finish;
5042                         }
5043                         if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5044                                 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5045                                                 symbol, &previous_entity->base.source_position);
5046                                 goto finish;
5047                         }
5048                         if (previous_entity->kind == ENTITY_TYPEDEF) {
5049                                 /* TODO: C++ allows this for exactly the same type */
5050                                 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5051                                                 symbol, &previous_entity->base.source_position);
5052                                 goto finish;
5053                         }
5054
5055                         /* at this point we should have only VARIABLES or FUNCTIONS */
5056                         assert(is_declaration(previous_entity) && is_declaration(entity));
5057
5058                         declaration_t *const prev_decl = &previous_entity->declaration;
5059                         declaration_t *const decl      = &entity->declaration;
5060
5061                         /* can happen for K&R style declarations */
5062                         if (prev_decl->type       == NULL             &&
5063                                         previous_entity->kind == ENTITY_PARAMETER &&
5064                                         entity->kind          == ENTITY_PARAMETER) {
5065                                 prev_decl->type                   = decl->type;
5066                                 prev_decl->storage_class          = decl->storage_class;
5067                                 prev_decl->declared_storage_class = decl->declared_storage_class;
5068                                 prev_decl->modifiers              = decl->modifiers;
5069                                 prev_decl->deprecated_string      = decl->deprecated_string;
5070                                 return previous_entity;
5071                         }
5072
5073                         type_t *const orig_type = decl->type;
5074                         assert(orig_type != NULL);
5075                         type_t *const type      = skip_typeref(orig_type);
5076                         type_t *const prev_type = skip_typeref(prev_decl->type);
5077
5078                         if (!types_compatible(type, prev_type)) {
5079                                 errorf(pos,
5080                                                 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5081                                                 orig_type, symbol, prev_decl->type, symbol,
5082                                                 &previous_entity->base.source_position);
5083                         } else {
5084                                 unsigned old_storage_class = prev_decl->storage_class;
5085                                 if (warning.redundant_decls               &&
5086                                                 is_definition                     &&
5087                                                 !prev_decl->used                  &&
5088                                                 !(prev_decl->modifiers & DM_USED) &&
5089                                                 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5090                                         warningf(&previous_entity->base.source_position,
5091                                                         "unnecessary static forward declaration for '%#T'",
5092                                                         prev_decl->type, symbol);
5093                                 }
5094
5095                                 storage_class_t new_storage_class = decl->storage_class;
5096
5097                                 /* pretend no storage class means extern for function
5098                                  * declarations (except if the previous declaration is neither
5099                                  * none nor extern) */
5100                                 if (entity->kind == ENTITY_FUNCTION) {
5101                                         /* the previous declaration could have unspecified parameters or
5102                                          * be a typedef, so use the new type */
5103                                         if (prev_type->function.unspecified_parameters || is_definition)
5104                                                 prev_decl->type = type;
5105
5106                                         switch (old_storage_class) {
5107                                                 case STORAGE_CLASS_NONE:
5108                                                         old_storage_class = STORAGE_CLASS_EXTERN;
5109                                                         /* FALLTHROUGH */
5110
5111                                                 case STORAGE_CLASS_EXTERN:
5112                                                         if (is_definition) {
5113                                                                 if (warning.missing_prototypes &&
5114                                                                                 prev_type->function.unspecified_parameters &&
5115                                                                                 !is_sym_main(symbol)) {
5116                                                                         warningf(pos, "no previous prototype for '%#T'",
5117                                                                                         orig_type, symbol);
5118                                                                 }
5119                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
5120                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
5121                                                         }
5122                                                         break;
5123
5124                                                 default:
5125                                                         break;
5126                                         }
5127                                 } else if (is_type_incomplete(prev_type)) {
5128                                         prev_decl->type = type;
5129                                 }
5130
5131                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5132                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
5133 warn_redundant_declaration:
5134                                         if (!is_definition           &&
5135                                                         warning.redundant_decls  &&
5136                                                         is_type_valid(prev_type) &&
5137                                                         strcmp(previous_entity->base.source_position.input_name,
5138                                                                 "<builtin>") != 0) {
5139                                                 warningf(pos,
5140                                                                 "redundant declaration for '%Y' (declared %P)",
5141                                                                 symbol, &previous_entity->base.source_position);
5142                                         }
5143                                 } else if (current_function == NULL) {
5144                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
5145                                                         new_storage_class == STORAGE_CLASS_STATIC) {
5146                                                 errorf(pos,
5147                                                                 "static declaration of '%Y' follows non-static declaration (declared %P)",
5148                                                                 symbol, &previous_entity->base.source_position);
5149                                         } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5150                                                 prev_decl->storage_class          = STORAGE_CLASS_NONE;
5151                                                 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5152                                         } else {
5153                                                 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5154                                                 if (c_mode & _CXX)
5155                                                         goto error_redeclaration;
5156                                                 goto warn_redundant_declaration;
5157                                         }
5158                                 } else if (is_type_valid(prev_type)) {
5159                                         if (old_storage_class == new_storage_class) {
5160 error_redeclaration:
5161                                                 errorf(pos, "redeclaration of '%Y' (declared %P)",
5162                                                                 symbol, &previous_entity->base.source_position);
5163                                         } else {
5164                                                 errorf(pos,
5165                                                                 "redeclaration of '%Y' with different linkage (declared %P)",
5166                                                                 symbol, &previous_entity->base.source_position);
5167                                         }
5168                                 }
5169                         }
5170
5171                         prev_decl->modifiers |= decl->modifiers;
5172                         if (entity->kind == ENTITY_FUNCTION) {
5173                                 previous_entity->function.is_inline |= entity->function.is_inline;
5174                         }
5175                         return previous_entity;
5176                 }
5177
5178                 if (warning.shadow) {
5179                         warningf(pos, "%s '%Y' shadows %s (declared %P)",
5180                                         get_entity_kind_name(entity->kind), symbol,
5181                                         get_entity_kind_name(previous_entity->kind),
5182                                         &previous_entity->base.source_position);
5183                 }
5184         }
5185
5186         if (entity->kind == ENTITY_FUNCTION) {
5187                 if (is_definition &&
5188                                 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5189                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
5190                                 warningf(pos, "no previous prototype for '%#T'",
5191                                          entity->declaration.type, symbol);
5192                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5193                                 warningf(pos, "no previous declaration for '%#T'",
5194                                          entity->declaration.type, symbol);
5195                         }
5196                 }
5197         } else if (warning.missing_declarations &&
5198                         entity->kind == ENTITY_VARIABLE &&
5199                         current_scope == file_scope) {
5200                 declaration_t *declaration = &entity->declaration;
5201                 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5202                         warningf(pos, "no previous declaration for '%#T'",
5203                                  declaration->type, symbol);
5204                 }
5205         }
5206
5207 finish:
5208         assert(entity->base.parent_scope == NULL);
5209         assert(current_scope != NULL);
5210
5211         entity->base.parent_scope = current_scope;
5212         entity->base.namespc      = NAMESPACE_NORMAL;
5213         environment_push(entity);
5214         append_entity(current_scope, entity);
5215
5216         return entity;
5217 }
5218
5219 static void parser_error_multiple_definition(entity_t *entity,
5220                 const source_position_t *source_position)
5221 {
5222         errorf(source_position, "multiple definition of '%Y' (declared %P)",
5223                entity->base.symbol, &entity->base.source_position);
5224 }
5225
5226 static bool is_declaration_specifier(const token_t *token,
5227                                      bool only_specifiers_qualifiers)
5228 {
5229         switch (token->type) {
5230                 TYPE_SPECIFIERS
5231                 TYPE_QUALIFIERS
5232                         return true;
5233                 case T_IDENTIFIER:
5234                         return is_typedef_symbol(token->v.symbol);
5235
5236                 case T___extension__:
5237                 STORAGE_CLASSES
5238                         return !only_specifiers_qualifiers;
5239
5240                 default:
5241                         return false;
5242         }
5243 }
5244
5245 static void parse_init_declarator_rest(entity_t *entity)
5246 {
5247         assert(is_declaration(entity));
5248         declaration_t *const declaration = &entity->declaration;
5249
5250         eat('=');
5251
5252         type_t *orig_type = declaration->type;
5253         type_t *type      = skip_typeref(orig_type);
5254
5255         if (entity->kind == ENTITY_VARIABLE
5256                         && entity->variable.initializer != NULL) {
5257                 parser_error_multiple_definition(entity, HERE);
5258         }
5259
5260         bool must_be_constant = false;
5261         if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5262             entity->base.parent_scope  == file_scope) {
5263                 must_be_constant = true;
5264         }
5265
5266         if (is_type_function(type)) {
5267                 errorf(&entity->base.source_position,
5268                        "function '%#T' is initialized like a variable",
5269                        orig_type, entity->base.symbol);
5270                 orig_type = type_error_type;
5271         }
5272
5273         parse_initializer_env_t env;
5274         env.type             = orig_type;
5275         env.must_be_constant = must_be_constant;
5276         env.entity           = entity;
5277         current_init_decl    = entity;
5278
5279         initializer_t *initializer = parse_initializer(&env);
5280         current_init_decl = NULL;
5281
5282         if (entity->kind == ENTITY_VARIABLE) {
5283                 /* §6.7.5:22  array initializers for arrays with unknown size
5284                  * determine the array type size */
5285                 declaration->type            = env.type;
5286                 entity->variable.initializer = initializer;
5287         }
5288 }
5289
5290 /* parse rest of a declaration without any declarator */
5291 static void parse_anonymous_declaration_rest(
5292                 const declaration_specifiers_t *specifiers)
5293 {
5294         eat(';');
5295         anonymous_entity = NULL;
5296
5297         if (warning.other) {
5298                 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5299                                 specifiers->thread_local) {
5300                         warningf(&specifiers->source_position,
5301                                  "useless storage class in empty declaration");
5302                 }
5303
5304                 type_t *type = specifiers->type;
5305                 switch (type->kind) {
5306                         case TYPE_COMPOUND_STRUCT:
5307                         case TYPE_COMPOUND_UNION: {
5308                                 if (type->compound.compound->base.symbol == NULL) {
5309                                         warningf(&specifiers->source_position,
5310                                                  "unnamed struct/union that defines no instances");
5311                                 }
5312                                 break;
5313                         }
5314
5315                         case TYPE_ENUM:
5316                                 break;
5317
5318                         default:
5319                                 warningf(&specifiers->source_position, "empty declaration");
5320                                 break;
5321                 }
5322         }
5323 }
5324
5325 static void check_variable_type_complete(entity_t *ent)
5326 {
5327         if (ent->kind != ENTITY_VARIABLE)
5328                 return;
5329
5330         /* §6.7:7  If an identifier for an object is declared with no linkage, the
5331          *         type for the object shall be complete [...] */
5332         declaration_t *decl = &ent->declaration;
5333         if (decl->storage_class == STORAGE_CLASS_EXTERN ||
5334                         decl->storage_class == STORAGE_CLASS_STATIC)
5335                 return;
5336
5337         type_t *const orig_type = decl->type;
5338         type_t *const type      = skip_typeref(orig_type);
5339         if (!is_type_incomplete(type))
5340                 return;
5341
5342         /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
5343          * are given length one. */
5344         if (is_type_array(type) && ent->base.parent_scope == file_scope) {
5345                 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5346                 return;
5347         }
5348
5349         errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5350                         orig_type, ent->base.symbol);
5351 }
5352
5353
5354 static void parse_declaration_rest(entity_t *ndeclaration,
5355                 const declaration_specifiers_t *specifiers,
5356                 parsed_declaration_func         finished_declaration,
5357                 declarator_flags_t              flags)
5358 {
5359         add_anchor_token(';');
5360         add_anchor_token(',');
5361         while (true) {
5362                 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5363
5364                 if (token.type == '=') {
5365                         parse_init_declarator_rest(entity);
5366                 } else if (entity->kind == ENTITY_VARIABLE) {
5367                         /* ISO/IEC 14882:1998(E) §8.5.3:3  The initializer can be omitted
5368                          * [...] where the extern specifier is explicitly used. */
5369                         declaration_t *decl = &entity->declaration;
5370                         if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5371                                 type_t *type = decl->type;
5372                                 if (is_type_reference(skip_typeref(type))) {
5373                                         errorf(&entity->base.source_position,
5374                                                         "reference '%#T' must be initialized",
5375                                                         type, entity->base.symbol);
5376                                 }
5377                         }
5378                 }
5379
5380                 check_variable_type_complete(entity);
5381
5382                 if (token.type != ',')
5383                         break;
5384                 eat(',');
5385
5386                 add_anchor_token('=');
5387                 ndeclaration = parse_declarator(specifiers, flags);
5388                 rem_anchor_token('=');
5389         }
5390         expect(';', end_error);
5391
5392 end_error:
5393         anonymous_entity = NULL;
5394         rem_anchor_token(';');
5395         rem_anchor_token(',');
5396 }
5397
5398 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5399 {
5400         symbol_t *symbol = entity->base.symbol;
5401         if (symbol == NULL) {
5402                 errorf(HERE, "anonymous declaration not valid as function parameter");
5403                 return entity;
5404         }
5405
5406         assert(entity->base.namespc == NAMESPACE_NORMAL);
5407         entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5408         if (previous_entity == NULL
5409                         || previous_entity->base.parent_scope != current_scope) {
5410                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5411                        symbol);
5412                 return entity;
5413         }
5414
5415         if (is_definition) {
5416                 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5417         }
5418
5419         return record_entity(entity, false);
5420 }
5421
5422 static void parse_declaration(parsed_declaration_func finished_declaration,
5423                               declarator_flags_t      flags)
5424 {
5425         declaration_specifiers_t specifiers;
5426         memset(&specifiers, 0, sizeof(specifiers));
5427
5428         add_anchor_token(';');
5429         parse_declaration_specifiers(&specifiers);
5430         rem_anchor_token(';');
5431
5432         if (token.type == ';') {
5433                 parse_anonymous_declaration_rest(&specifiers);
5434         } else {
5435                 entity_t *entity = parse_declarator(&specifiers, flags);
5436                 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5437         }
5438 }
5439
5440 static type_t *get_default_promoted_type(type_t *orig_type)
5441 {
5442         type_t *result = orig_type;
5443
5444         type_t *type = skip_typeref(orig_type);
5445         if (is_type_integer(type)) {
5446                 result = promote_integer(type);
5447         } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
5448                 result = type_double;
5449         }
5450
5451         return result;
5452 }
5453
5454 static void parse_kr_declaration_list(entity_t *entity)
5455 {
5456         if (entity->kind != ENTITY_FUNCTION)
5457                 return;
5458
5459         type_t *type = skip_typeref(entity->declaration.type);
5460         assert(is_type_function(type));
5461         if (!type->function.kr_style_parameters)
5462                 return;
5463
5464
5465         add_anchor_token('{');
5466
5467         /* push function parameters */
5468         size_t const  top       = environment_top();
5469         scope_t      *old_scope = scope_push(&entity->function.parameters);
5470
5471         entity_t *parameter = entity->function.parameters.entities;
5472         for ( ; parameter != NULL; parameter = parameter->base.next) {
5473                 assert(parameter->base.parent_scope == NULL);
5474                 parameter->base.parent_scope = current_scope;
5475                 environment_push(parameter);
5476         }
5477
5478         /* parse declaration list */
5479         for (;;) {
5480                 switch (token.type) {
5481                         DECLARATION_START
5482                         case T___extension__:
5483                         /* This covers symbols, which are no type, too, and results in
5484                          * better error messages.  The typical cases are misspelled type
5485                          * names and missing includes. */
5486                         case T_IDENTIFIER:
5487                                 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5488                                 break;
5489                         default:
5490                                 goto decl_list_end;
5491                 }
5492         }
5493 decl_list_end:
5494
5495         /* pop function parameters */
5496         assert(current_scope == &entity->function.parameters);
5497         scope_pop(old_scope);
5498         environment_pop_to(top);
5499
5500         /* update function type */
5501         type_t *new_type = duplicate_type(type);
5502
5503         function_parameter_t  *parameters = NULL;
5504         function_parameter_t **anchor     = &parameters;
5505
5506         parameter = entity->function.parameters.entities;
5507         for (; parameter != NULL; parameter = parameter->base.next) {
5508                 if (parameter->kind != ENTITY_PARAMETER)
5509                         continue;
5510
5511                 type_t *parameter_type = parameter->declaration.type;
5512                 if (parameter_type == NULL) {
5513                         if (strict_mode) {
5514                                 errorf(HERE, "no type specified for function parameter '%Y'",
5515                                        parameter->base.symbol);
5516                         } else {
5517                                 if (warning.implicit_int) {
5518                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5519                                                  parameter->base.symbol);
5520                                 }
5521                                 parameter_type              = type_int;
5522                                 parameter->declaration.type = parameter_type;
5523                         }
5524                 }
5525
5526                 semantic_parameter_incomplete(parameter);
5527                 parameter_type = parameter->declaration.type;
5528
5529                 /*
5530                  * we need the default promoted types for the function type
5531                  */
5532                 parameter_type = get_default_promoted_type(parameter_type);
5533
5534                 function_parameter_t *const parameter =
5535                         allocate_parameter(parameter_type);
5536
5537                 *anchor = parameter;
5538                 anchor  = &parameter->next;
5539         }
5540
5541         /* §6.9.1.7: A K&R style parameter list does NOT act as a function
5542          * prototype */
5543         new_type->function.parameters             = parameters;
5544         new_type->function.unspecified_parameters = true;
5545
5546         new_type = identify_new_type(new_type);
5547
5548         entity->declaration.type = new_type;
5549
5550         rem_anchor_token('{');
5551 }
5552
5553 static bool first_err = true;
5554
5555 /**
5556  * When called with first_err set, prints the name of the current function,
5557  * else does noting.
5558  */
5559 static void print_in_function(void)
5560 {
5561         if (first_err) {
5562                 first_err = false;
5563                 diagnosticf("%s: In function '%Y':\n",
5564                             current_function->base.base.source_position.input_name,
5565                             current_function->base.base.symbol);
5566         }
5567 }
5568
5569 /**
5570  * Check if all labels are defined in the current function.
5571  * Check if all labels are used in the current function.
5572  */
5573 static void check_labels(void)
5574 {
5575         for (const goto_statement_t *goto_statement = goto_first;
5576             goto_statement != NULL;
5577             goto_statement = goto_statement->next) {
5578                 /* skip computed gotos */
5579                 if (goto_statement->expression != NULL)
5580                         continue;
5581
5582                 label_t *label = goto_statement->label;
5583
5584                 label->used = true;
5585                 if (label->base.source_position.input_name == NULL) {
5586                         print_in_function();
5587                         errorf(&goto_statement->base.source_position,
5588                                "label '%Y' used but not defined", label->base.symbol);
5589                  }
5590         }
5591
5592         if (warning.unused_label) {
5593                 for (const label_statement_t *label_statement = label_first;
5594                          label_statement != NULL;
5595                          label_statement = label_statement->next) {
5596                         label_t *label = label_statement->label;
5597
5598                         if (! label->used) {
5599                                 print_in_function();
5600                                 warningf(&label_statement->base.source_position,
5601                                          "label '%Y' defined but not used", label->base.symbol);
5602                         }
5603                 }
5604         }
5605 }
5606
5607 static void warn_unused_entity(entity_t *entity, entity_t *last)
5608 {
5609         entity_t const *const end = last != NULL ? last->base.next : NULL;
5610         for (; entity != end; entity = entity->base.next) {
5611                 if (!is_declaration(entity))
5612                         continue;
5613
5614                 declaration_t *declaration = &entity->declaration;
5615                 if (declaration->implicit)
5616                         continue;
5617
5618                 if (!declaration->used) {
5619                         print_in_function();
5620                         const char *what = get_entity_kind_name(entity->kind);
5621                         warningf(&entity->base.source_position, "%s '%Y' is unused",
5622                                  what, entity->base.symbol);
5623                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5624                         print_in_function();
5625                         const char *what = get_entity_kind_name(entity->kind);
5626                         warningf(&entity->base.source_position, "%s '%Y' is never read",
5627                                  what, entity->base.symbol);
5628                 }
5629         }
5630 }
5631
5632 static void check_unused_variables(statement_t *const stmt, void *const env)
5633 {
5634         (void)env;
5635
5636         switch (stmt->kind) {
5637                 case STATEMENT_DECLARATION: {
5638                         declaration_statement_t const *const decls = &stmt->declaration;
5639                         warn_unused_entity(decls->declarations_begin,
5640                                            decls->declarations_end);
5641                         return;
5642                 }
5643
5644                 case STATEMENT_FOR:
5645                         warn_unused_entity(stmt->fors.scope.entities, NULL);
5646                         return;
5647
5648                 default:
5649                         return;
5650         }
5651 }
5652
5653 /**
5654  * Check declarations of current_function for unused entities.
5655  */
5656 static void check_declarations(void)
5657 {
5658         if (warning.unused_parameter) {
5659                 const scope_t *scope = &current_function->parameters;
5660
5661                 /* do not issue unused warnings for main */
5662                 if (!is_sym_main(current_function->base.base.symbol)) {
5663                         warn_unused_entity(scope->entities, NULL);
5664                 }
5665         }
5666         if (warning.unused_variable) {
5667                 walk_statements(current_function->statement, check_unused_variables,
5668                                 NULL);
5669         }
5670 }
5671
5672 static int determine_truth(expression_t const* const cond)
5673 {
5674         return
5675                 !is_constant_expression(cond) ? 0 :
5676                 fold_constant(cond) != 0      ? 1 :
5677                 -1;
5678 }
5679
5680 static void check_reachable(statement_t *);
5681 static bool reaches_end;
5682
5683 static bool expression_returns(expression_t const *const expr)
5684 {
5685         switch (expr->kind) {
5686                 case EXPR_CALL: {
5687                         expression_t const *const func = expr->call.function;
5688                         if (func->kind == EXPR_REFERENCE) {
5689                                 entity_t *entity = func->reference.entity;
5690                                 if (entity->kind == ENTITY_FUNCTION
5691                                                 && entity->declaration.modifiers & DM_NORETURN)
5692                                         return false;
5693                         }
5694
5695                         if (!expression_returns(func))
5696                                 return false;
5697
5698                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5699                                 if (!expression_returns(arg->expression))
5700                                         return false;
5701                         }
5702
5703                         return true;
5704                 }
5705
5706                 case EXPR_REFERENCE:
5707                 case EXPR_REFERENCE_ENUM_VALUE:
5708                 case EXPR_CONST:
5709                 case EXPR_CHARACTER_CONSTANT:
5710                 case EXPR_WIDE_CHARACTER_CONSTANT:
5711                 case EXPR_STRING_LITERAL:
5712                 case EXPR_WIDE_STRING_LITERAL:
5713                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5714                 case EXPR_LABEL_ADDRESS:
5715                 case EXPR_CLASSIFY_TYPE:
5716                 case EXPR_SIZEOF: // TODO handle obscure VLA case
5717                 case EXPR_ALIGNOF:
5718                 case EXPR_FUNCNAME:
5719                 case EXPR_BUILTIN_CONSTANT_P:
5720                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5721                 case EXPR_OFFSETOF:
5722                 case EXPR_INVALID:
5723                         return true;
5724
5725                 case EXPR_STATEMENT: {
5726                         bool old_reaches_end = reaches_end;
5727                         reaches_end = false;
5728                         check_reachable(expr->statement.statement);
5729                         bool returns = reaches_end;
5730                         reaches_end = old_reaches_end;
5731                         return returns;
5732                 }
5733
5734                 case EXPR_CONDITIONAL:
5735                         // TODO handle constant expression
5736
5737                         if (!expression_returns(expr->conditional.condition))
5738                                 return false;
5739
5740                         if (expr->conditional.true_expression != NULL
5741                                         && expression_returns(expr->conditional.true_expression))
5742                                 return true;
5743
5744                         return expression_returns(expr->conditional.false_expression);
5745
5746                 case EXPR_SELECT:
5747                         return expression_returns(expr->select.compound);
5748
5749                 case EXPR_ARRAY_ACCESS:
5750                         return
5751                                 expression_returns(expr->array_access.array_ref) &&
5752                                 expression_returns(expr->array_access.index);
5753
5754                 case EXPR_VA_START:
5755                         return expression_returns(expr->va_starte.ap);
5756
5757                 case EXPR_VA_ARG:
5758                         return expression_returns(expr->va_arge.ap);
5759
5760                 EXPR_UNARY_CASES_MANDATORY
5761                         return expression_returns(expr->unary.value);
5762
5763                 case EXPR_UNARY_THROW:
5764                         return false;
5765
5766                 EXPR_BINARY_CASES
5767                         // TODO handle constant lhs of && and ||
5768                         return
5769                                 expression_returns(expr->binary.left) &&
5770                                 expression_returns(expr->binary.right);
5771
5772                 case EXPR_UNKNOWN:
5773                         break;
5774         }
5775
5776         panic("unhandled expression");
5777 }
5778
5779 static bool initializer_returns(initializer_t const *const init)
5780 {
5781         switch (init->kind) {
5782                 case INITIALIZER_VALUE:
5783                         return expression_returns(init->value.value);
5784
5785                 case INITIALIZER_LIST: {
5786                         initializer_t * const*       i       = init->list.initializers;
5787                         initializer_t * const* const end     = i + init->list.len;
5788                         bool                         returns = true;
5789                         for (; i != end; ++i) {
5790                                 if (!initializer_returns(*i))
5791                                         returns = false;
5792                         }
5793                         return returns;
5794                 }
5795
5796                 case INITIALIZER_STRING:
5797                 case INITIALIZER_WIDE_STRING:
5798                 case INITIALIZER_DESIGNATOR: // designators have no payload
5799                         return true;
5800         }
5801         panic("unhandled initializer");
5802 }
5803
5804 static bool noreturn_candidate;
5805
5806 static void check_reachable(statement_t *const stmt)
5807 {
5808         if (stmt->base.reachable)
5809                 return;
5810         if (stmt->kind != STATEMENT_DO_WHILE)
5811                 stmt->base.reachable = true;
5812
5813         statement_t *last = stmt;
5814         statement_t *next;
5815         switch (stmt->kind) {
5816                 case STATEMENT_INVALID:
5817                 case STATEMENT_EMPTY:
5818                 case STATEMENT_ASM:
5819                         next = stmt->base.next;
5820                         break;
5821
5822                 case STATEMENT_DECLARATION: {
5823                         declaration_statement_t const *const decl = &stmt->declaration;
5824                         entity_t                const *      ent  = decl->declarations_begin;
5825                         entity_t                const *const last = decl->declarations_end;
5826                         if (ent != NULL) {
5827                                 for (;; ent = ent->base.next) {
5828                                         if (ent->kind                 == ENTITY_VARIABLE &&
5829                                                         ent->variable.initializer != NULL            &&
5830                                                         !initializer_returns(ent->variable.initializer)) {
5831                                                 return;
5832                                         }
5833                                         if (ent == last)
5834                                                 break;
5835                                 }
5836                         }
5837                         next = stmt->base.next;
5838                         break;
5839                 }
5840
5841                 case STATEMENT_COMPOUND:
5842                         next = stmt->compound.statements;
5843                         if (next == NULL)
5844                                 next = stmt->base.next;
5845                         break;
5846
5847                 case STATEMENT_RETURN: {
5848                         expression_t const *const val = stmt->returns.value;
5849                         if (val == NULL || expression_returns(val))
5850                                 noreturn_candidate = false;
5851                         return;
5852                 }
5853
5854                 case STATEMENT_IF: {
5855                         if_statement_t const *const ifs  = &stmt->ifs;
5856                         expression_t   const *const cond = ifs->condition;
5857
5858                         if (!expression_returns(cond))
5859                                 return;
5860
5861                         int const val = determine_truth(cond);
5862
5863                         if (val >= 0)
5864                                 check_reachable(ifs->true_statement);
5865
5866                         if (val > 0)
5867                                 return;
5868
5869                         if (ifs->false_statement != NULL) {
5870                                 check_reachable(ifs->false_statement);
5871                                 return;
5872                         }
5873
5874                         next = stmt->base.next;
5875                         break;
5876                 }
5877
5878                 case STATEMENT_SWITCH: {
5879                         switch_statement_t const *const switchs = &stmt->switchs;
5880                         expression_t       const *const expr    = switchs->expression;
5881
5882                         if (!expression_returns(expr))
5883                                 return;
5884
5885                         if (is_constant_expression(expr)) {
5886                                 long                    const val      = fold_constant(expr);
5887                                 case_label_statement_t *      defaults = NULL;
5888                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5889                                         if (i->expression == NULL) {
5890                                                 defaults = i;
5891                                                 continue;
5892                                         }
5893
5894                                         if (i->first_case <= val && val <= i->last_case) {
5895                                                 check_reachable((statement_t*)i);
5896                                                 return;
5897                                         }
5898                                 }
5899
5900                                 if (defaults != NULL) {
5901                                         check_reachable((statement_t*)defaults);
5902                                         return;
5903                                 }
5904                         } else {
5905                                 bool has_default = false;
5906                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5907                                         if (i->expression == NULL)
5908                                                 has_default = true;
5909
5910                                         check_reachable((statement_t*)i);
5911                                 }
5912
5913                                 if (has_default)
5914                                         return;
5915                         }
5916
5917                         next = stmt->base.next;
5918                         break;
5919                 }
5920
5921                 case STATEMENT_EXPRESSION: {
5922                         /* Check for noreturn function call */
5923                         expression_t const *const expr = stmt->expression.expression;
5924                         if (!expression_returns(expr))
5925                                 return;
5926
5927                         next = stmt->base.next;
5928                         break;
5929                 }
5930
5931                 case STATEMENT_CONTINUE: {
5932                         statement_t *parent = stmt;
5933                         for (;;) {
5934                                 parent = parent->base.parent;
5935                                 if (parent == NULL) /* continue not within loop */
5936                                         return;
5937
5938                                 next = parent;
5939                                 switch (parent->kind) {
5940                                         case STATEMENT_WHILE:    goto continue_while;
5941                                         case STATEMENT_DO_WHILE: goto continue_do_while;
5942                                         case STATEMENT_FOR:      goto continue_for;
5943
5944                                         default: break;
5945                                 }
5946                         }
5947                 }
5948
5949                 case STATEMENT_BREAK: {
5950                         statement_t *parent = stmt;
5951                         for (;;) {
5952                                 parent = parent->base.parent;
5953                                 if (parent == NULL) /* break not within loop/switch */
5954                                         return;
5955
5956                                 switch (parent->kind) {
5957                                         case STATEMENT_SWITCH:
5958                                         case STATEMENT_WHILE:
5959                                         case STATEMENT_DO_WHILE:
5960                                         case STATEMENT_FOR:
5961                                                 last = parent;
5962                                                 next = parent->base.next;
5963                                                 goto found_break_parent;
5964
5965                                         default: break;
5966                                 }
5967                         }
5968 found_break_parent:
5969                         break;
5970                 }
5971
5972                 case STATEMENT_GOTO:
5973                         if (stmt->gotos.expression) {
5974                                 if (!expression_returns(stmt->gotos.expression))
5975                                         return;
5976
5977                                 statement_t *parent = stmt->base.parent;
5978                                 if (parent == NULL) /* top level goto */
5979                                         return;
5980                                 next = parent;
5981                         } else {
5982                                 next = stmt->gotos.label->statement;
5983                                 if (next == NULL) /* missing label */
5984                                         return;
5985                         }
5986                         break;
5987
5988                 case STATEMENT_LABEL:
5989                         next = stmt->label.statement;
5990                         break;
5991
5992                 case STATEMENT_CASE_LABEL:
5993                         next = stmt->case_label.statement;
5994                         break;
5995
5996                 case STATEMENT_WHILE: {
5997                         while_statement_t const *const whiles = &stmt->whiles;
5998                         expression_t      const *const cond   = whiles->condition;
5999
6000                         if (!expression_returns(cond))
6001                                 return;
6002
6003                         int const val = determine_truth(cond);
6004
6005                         if (val >= 0)
6006                                 check_reachable(whiles->body);
6007
6008                         if (val > 0)
6009                                 return;
6010
6011                         next = stmt->base.next;
6012                         break;
6013                 }
6014
6015                 case STATEMENT_DO_WHILE:
6016                         next = stmt->do_while.body;
6017                         break;
6018
6019                 case STATEMENT_FOR: {
6020                         for_statement_t *const fors = &stmt->fors;
6021
6022                         if (fors->condition_reachable)
6023                                 return;
6024                         fors->condition_reachable = true;
6025
6026                         expression_t const *const cond = fors->condition;
6027
6028                         int val;
6029                         if (cond == NULL) {
6030                                 val = 1;
6031                         } else if (expression_returns(cond)) {
6032                                 val = determine_truth(cond);
6033                         } else {
6034                                 return;
6035                         }
6036
6037                         if (val >= 0)
6038                                 check_reachable(fors->body);
6039
6040                         if (val > 0)
6041                                 return;
6042
6043                         next = stmt->base.next;
6044                         break;
6045                 }
6046
6047                 case STATEMENT_MS_TRY: {
6048                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
6049                         check_reachable(ms_try->try_statement);
6050                         next = ms_try->final_statement;
6051                         break;
6052                 }
6053
6054                 case STATEMENT_LEAVE: {
6055                         statement_t *parent = stmt;
6056                         for (;;) {
6057                                 parent = parent->base.parent;
6058                                 if (parent == NULL) /* __leave not within __try */
6059                                         return;
6060
6061                                 if (parent->kind == STATEMENT_MS_TRY) {
6062                                         last = parent;
6063                                         next = parent->ms_try.final_statement;
6064                                         break;
6065                                 }
6066                         }
6067                         break;
6068                 }
6069
6070                 default:
6071                         panic("invalid statement kind");
6072         }
6073
6074         while (next == NULL) {
6075                 next = last->base.parent;
6076                 if (next == NULL) {
6077                         noreturn_candidate = false;
6078
6079                         type_t *const type = skip_typeref(current_function->base.type);
6080                         assert(is_type_function(type));
6081                         type_t *const ret  = skip_typeref(type->function.return_type);
6082                         if (warning.return_type                    &&
6083                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6084                             is_type_valid(ret)                     &&
6085                             !is_sym_main(current_function->base.base.symbol)) {
6086                                 warningf(&stmt->base.source_position,
6087                                          "control reaches end of non-void function");
6088                         }
6089                         return;
6090                 }
6091
6092                 switch (next->kind) {
6093                         case STATEMENT_INVALID:
6094                         case STATEMENT_EMPTY:
6095                         case STATEMENT_DECLARATION:
6096                         case STATEMENT_EXPRESSION:
6097                         case STATEMENT_ASM:
6098                         case STATEMENT_RETURN:
6099                         case STATEMENT_CONTINUE:
6100                         case STATEMENT_BREAK:
6101                         case STATEMENT_GOTO:
6102                         case STATEMENT_LEAVE:
6103                                 panic("invalid control flow in function");
6104
6105                         case STATEMENT_COMPOUND:
6106                                 if (next->compound.stmt_expr) {
6107                                         reaches_end = true;
6108                                         return;
6109                                 }
6110                                 /* FALLTHROUGH */
6111                         case STATEMENT_IF:
6112                         case STATEMENT_SWITCH:
6113                         case STATEMENT_LABEL:
6114                         case STATEMENT_CASE_LABEL:
6115                                 last = next;
6116                                 next = next->base.next;
6117                                 break;
6118
6119                         case STATEMENT_WHILE: {
6120 continue_while:
6121                                 if (next->base.reachable)
6122                                         return;
6123                                 next->base.reachable = true;
6124
6125                                 while_statement_t const *const whiles = &next->whiles;
6126                                 expression_t      const *const cond   = whiles->condition;
6127
6128                                 if (!expression_returns(cond))
6129                                         return;
6130
6131                                 int const val = determine_truth(cond);
6132
6133                                 if (val >= 0)
6134                                         check_reachable(whiles->body);
6135
6136                                 if (val > 0)
6137                                         return;
6138
6139                                 last = next;
6140                                 next = next->base.next;
6141                                 break;
6142                         }
6143
6144                         case STATEMENT_DO_WHILE: {
6145 continue_do_while:
6146                                 if (next->base.reachable)
6147                                         return;
6148                                 next->base.reachable = true;
6149
6150                                 do_while_statement_t const *const dw   = &next->do_while;
6151                                 expression_t         const *const cond = dw->condition;
6152
6153                                 if (!expression_returns(cond))
6154                                         return;
6155
6156                                 int const val = determine_truth(cond);
6157
6158                                 if (val >= 0)
6159                                         check_reachable(dw->body);
6160
6161                                 if (val > 0)
6162                                         return;
6163
6164                                 last = next;
6165                                 next = next->base.next;
6166                                 break;
6167                         }
6168
6169                         case STATEMENT_FOR: {
6170 continue_for:;
6171                                 for_statement_t *const fors = &next->fors;
6172
6173                                 fors->step_reachable = true;
6174
6175                                 if (fors->condition_reachable)
6176                                         return;
6177                                 fors->condition_reachable = true;
6178
6179                                 expression_t const *const cond = fors->condition;
6180
6181                                 int val;
6182                                 if (cond == NULL) {
6183                                         val = 1;
6184                                 } else if (expression_returns(cond)) {
6185                                         val = determine_truth(cond);
6186                                 } else {
6187                                         return;
6188                                 }
6189
6190                                 if (val >= 0)
6191                                         check_reachable(fors->body);
6192
6193                                 if (val > 0)
6194                                         return;
6195
6196                                 last = next;
6197                                 next = next->base.next;
6198                                 break;
6199                         }
6200
6201                         case STATEMENT_MS_TRY:
6202                                 last = next;
6203                                 next = next->ms_try.final_statement;
6204                                 break;
6205                 }
6206         }
6207
6208         check_reachable(next);
6209 }
6210
6211 static void check_unreachable(statement_t* const stmt, void *const env)
6212 {
6213         (void)env;
6214
6215         switch (stmt->kind) {
6216                 case STATEMENT_DO_WHILE:
6217                         if (!stmt->base.reachable) {
6218                                 expression_t const *const cond = stmt->do_while.condition;
6219                                 if (determine_truth(cond) >= 0) {
6220                                         warningf(&cond->base.source_position,
6221                                                  "condition of do-while-loop is unreachable");
6222                                 }
6223                         }
6224                         return;
6225
6226                 case STATEMENT_FOR: {
6227                         for_statement_t const* const fors = &stmt->fors;
6228
6229                         // if init and step are unreachable, cond is unreachable, too
6230                         if (!stmt->base.reachable && !fors->step_reachable) {
6231                                 warningf(&stmt->base.source_position, "statement is unreachable");
6232                         } else {
6233                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
6234                                         warningf(&fors->initialisation->base.source_position,
6235                                                  "initialisation of for-statement is unreachable");
6236                                 }
6237
6238                                 if (!fors->condition_reachable && fors->condition != NULL) {
6239                                         warningf(&fors->condition->base.source_position,
6240                                                  "condition of for-statement is unreachable");
6241                                 }
6242
6243                                 if (!fors->step_reachable && fors->step != NULL) {
6244                                         warningf(&fors->step->base.source_position,
6245                                                  "step of for-statement is unreachable");
6246                                 }
6247                         }
6248                         return;
6249                 }
6250
6251                 case STATEMENT_COMPOUND:
6252                         if (stmt->compound.statements != NULL)
6253                                 return;
6254                         goto warn_unreachable;
6255
6256                 case STATEMENT_DECLARATION: {
6257                         /* Only warn if there is at least one declarator with an initializer.
6258                          * This typically occurs in switch statements. */
6259                         declaration_statement_t const *const decl = &stmt->declaration;
6260                         entity_t                const *      ent  = decl->declarations_begin;
6261                         entity_t                const *const last = decl->declarations_end;
6262                         if (ent != NULL) {
6263                                 for (;; ent = ent->base.next) {
6264                                         if (ent->kind                 == ENTITY_VARIABLE &&
6265                                                         ent->variable.initializer != NULL) {
6266                                                 goto warn_unreachable;
6267                                         }
6268                                         if (ent == last)
6269                                                 return;
6270                                 }
6271                         }
6272                 }
6273
6274                 default:
6275 warn_unreachable:
6276                         if (!stmt->base.reachable)
6277                                 warningf(&stmt->base.source_position, "statement is unreachable");
6278                         return;
6279         }
6280 }
6281
6282 static void parse_external_declaration(void)
6283 {
6284         /* function-definitions and declarations both start with declaration
6285          * specifiers */
6286         declaration_specifiers_t specifiers;
6287         memset(&specifiers, 0, sizeof(specifiers));
6288
6289         add_anchor_token(';');
6290         parse_declaration_specifiers(&specifiers);
6291         rem_anchor_token(';');
6292
6293         /* must be a declaration */
6294         if (token.type == ';') {
6295                 parse_anonymous_declaration_rest(&specifiers);
6296                 return;
6297         }
6298
6299         add_anchor_token(',');
6300         add_anchor_token('=');
6301         add_anchor_token(';');
6302         add_anchor_token('{');
6303
6304         /* declarator is common to both function-definitions and declarations */
6305         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6306
6307         rem_anchor_token('{');
6308         rem_anchor_token(';');
6309         rem_anchor_token('=');
6310         rem_anchor_token(',');
6311
6312         /* must be a declaration */
6313         switch (token.type) {
6314                 case ',':
6315                 case ';':
6316                 case '=':
6317                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6318                                         DECL_FLAGS_NONE);
6319                         return;
6320         }
6321
6322         /* must be a function definition */
6323         parse_kr_declaration_list(ndeclaration);
6324
6325         if (token.type != '{') {
6326                 parse_error_expected("while parsing function definition", '{', NULL);
6327                 eat_until_matching_token(';');
6328                 return;
6329         }
6330
6331         assert(is_declaration(ndeclaration));
6332         type_t *const orig_type = ndeclaration->declaration.type;
6333         type_t *      type      = skip_typeref(orig_type);
6334
6335         if (!is_type_function(type)) {
6336                 if (is_type_valid(type)) {
6337                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
6338                                type, ndeclaration->base.symbol);
6339                 }
6340                 eat_block();
6341                 return;
6342         } else if (is_typeref(orig_type)) {
6343                 /* §6.9.1:2 */
6344                 errorf(&ndeclaration->base.source_position,
6345                                 "type of function definition '%#T' is a typedef",
6346                                 orig_type, ndeclaration->base.symbol);
6347         }
6348
6349         if (warning.aggregate_return &&
6350             is_type_compound(skip_typeref(type->function.return_type))) {
6351                 warningf(HERE, "function '%Y' returns an aggregate",
6352                          ndeclaration->base.symbol);
6353         }
6354         if (warning.traditional && !type->function.unspecified_parameters) {
6355                 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6356                         ndeclaration->base.symbol);
6357         }
6358         if (warning.old_style_definition && type->function.unspecified_parameters) {
6359                 warningf(HERE, "old-style function definition '%Y'",
6360                         ndeclaration->base.symbol);
6361         }
6362
6363         /* §6.7.5.3:14 a function definition with () means no
6364          * parameters (and not unspecified parameters) */
6365         if (type->function.unspecified_parameters &&
6366                         type->function.parameters == NULL     &&
6367                         !type->function.kr_style_parameters) {
6368                 type_t *copy                          = duplicate_type(type);
6369                 copy->function.unspecified_parameters = false;
6370                 type                                  = identify_new_type(copy);
6371
6372                 ndeclaration->declaration.type = type;
6373         }
6374
6375         entity_t *const entity = record_entity(ndeclaration, true);
6376         assert(entity->kind == ENTITY_FUNCTION);
6377         assert(ndeclaration->kind == ENTITY_FUNCTION);
6378
6379         function_t *function = &entity->function;
6380         if (ndeclaration != entity) {
6381                 function->parameters = ndeclaration->function.parameters;
6382         }
6383         assert(is_declaration(entity));
6384         type = skip_typeref(entity->declaration.type);
6385
6386         /* push function parameters and switch scope */
6387         size_t const  top       = environment_top();
6388         scope_t      *old_scope = scope_push(&function->parameters);
6389
6390         entity_t *parameter = function->parameters.entities;
6391         for (; parameter != NULL; parameter = parameter->base.next) {
6392                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6393                         parameter->base.parent_scope = current_scope;
6394                 }
6395                 assert(parameter->base.parent_scope == NULL
6396                                 || parameter->base.parent_scope == current_scope);
6397                 parameter->base.parent_scope = current_scope;
6398                 if (parameter->base.symbol == NULL) {
6399                         errorf(&parameter->base.source_position, "parameter name omitted");
6400                         continue;
6401                 }
6402                 environment_push(parameter);
6403         }
6404
6405         if (function->statement != NULL) {
6406                 parser_error_multiple_definition(entity, HERE);
6407                 eat_block();
6408         } else {
6409                 /* parse function body */
6410                 int         label_stack_top      = label_top();
6411                 function_t *old_current_function = current_function;
6412                 current_function                 = function;
6413                 current_parent                   = NULL;
6414
6415                 goto_first   = NULL;
6416                 goto_anchor  = &goto_first;
6417                 label_first  = NULL;
6418                 label_anchor = &label_first;
6419
6420                 statement_t *const body = parse_compound_statement(false);
6421                 function->statement = body;
6422                 first_err = true;
6423                 check_labels();
6424                 check_declarations();
6425                 if (warning.return_type      ||
6426                     warning.unreachable_code ||
6427                     (warning.missing_noreturn
6428                      && !(function->base.modifiers & DM_NORETURN))) {
6429                         noreturn_candidate = true;
6430                         check_reachable(body);
6431                         if (warning.unreachable_code)
6432                                 walk_statements(body, check_unreachable, NULL);
6433                         if (warning.missing_noreturn &&
6434                             noreturn_candidate       &&
6435                             !(function->base.modifiers & DM_NORETURN)) {
6436                                 warningf(&body->base.source_position,
6437                                          "function '%#T' is candidate for attribute 'noreturn'",
6438                                          type, entity->base.symbol);
6439                         }
6440                 }
6441
6442                 assert(current_parent   == NULL);
6443                 assert(current_function == function);
6444                 current_function = old_current_function;
6445                 label_pop_to(label_stack_top);
6446         }
6447
6448         assert(current_scope == &function->parameters);
6449         scope_pop(old_scope);
6450         environment_pop_to(top);
6451 }
6452
6453 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6454                                   source_position_t *source_position,
6455                                   const symbol_t *symbol)
6456 {
6457         type_t *type = allocate_type_zero(TYPE_BITFIELD);
6458
6459         type->bitfield.base_type       = base_type;
6460         type->bitfield.size_expression = size;
6461
6462         il_size_t bit_size;
6463         type_t *skipped_type = skip_typeref(base_type);
6464         if (!is_type_integer(skipped_type)) {
6465                 errorf(HERE, "bitfield base type '%T' is not an integer type",
6466                         base_type);
6467                 bit_size = 0;
6468         } else {
6469                 bit_size = skipped_type->base.size * 8;
6470         }
6471
6472         if (is_constant_expression(size)) {
6473                 long v = fold_constant(size);
6474
6475                 if (v < 0) {
6476                         errorf(source_position, "negative width in bit-field '%Y'", symbol);
6477                 } else if (v == 0) {
6478                         errorf(source_position, "zero width for bit-field '%Y'", symbol);
6479                 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6480                         errorf(source_position, "width of '%Y' exceeds its type", symbol);
6481                 } else {
6482                         type->bitfield.bit_size = v;
6483                 }
6484         }
6485
6486         return type;
6487 }
6488
6489 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6490 {
6491         entity_t *iter = compound->members.entities;
6492         for (; iter != NULL; iter = iter->base.next) {
6493                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6494                         continue;
6495
6496                 if (iter->base.symbol == symbol) {
6497                         return iter;
6498                 } else if (iter->base.symbol == NULL) {
6499                         type_t *type = skip_typeref(iter->declaration.type);
6500                         if (is_type_compound(type)) {
6501                                 entity_t *result
6502                                         = find_compound_entry(type->compound.compound, symbol);
6503                                 if (result != NULL)
6504                                         return result;
6505                         }
6506                         continue;
6507                 }
6508         }
6509
6510         return NULL;
6511 }
6512
6513 static void parse_compound_declarators(compound_t *compound,
6514                 const declaration_specifiers_t *specifiers)
6515 {
6516         while (true) {
6517                 entity_t *entity;
6518
6519                 if (token.type == ':') {
6520                         source_position_t source_position = *HERE;
6521                         next_token();
6522
6523                         type_t *base_type = specifiers->type;
6524                         expression_t *size = parse_constant_expression();
6525
6526                         type_t *type = make_bitfield_type(base_type, size,
6527                                         &source_position, sym_anonymous);
6528
6529                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6530                         entity->base.namespc                       = NAMESPACE_NORMAL;
6531                         entity->base.source_position               = source_position;
6532                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6533                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
6534                         entity->declaration.modifiers              = specifiers->modifiers;
6535                         entity->declaration.type                   = type;
6536                         append_entity(&compound->members, entity);
6537                 } else {
6538                         entity = parse_declarator(specifiers,
6539                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6540                         if (entity->kind == ENTITY_TYPEDEF) {
6541                                 errorf(&entity->base.source_position,
6542                                                 "typedef not allowed as compound member");
6543                         } else {
6544                                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6545
6546                                 /* make sure we don't define a symbol multiple times */
6547                                 symbol_t *symbol = entity->base.symbol;
6548                                 if (symbol != NULL) {
6549                                         entity_t *prev = find_compound_entry(compound, symbol);
6550                                         if (prev != NULL) {
6551                                                 errorf(&entity->base.source_position,
6552                                                                 "multiple declarations of symbol '%Y' (declared %P)",
6553                                                                 symbol, &prev->base.source_position);
6554                                         }
6555                                 }
6556
6557                                 if (token.type == ':') {
6558                                         source_position_t source_position = *HERE;
6559                                         next_token();
6560                                         expression_t *size = parse_constant_expression();
6561
6562                                         type_t *type          = entity->declaration.type;
6563                                         type_t *bitfield_type = make_bitfield_type(type, size,
6564                                                         &source_position, entity->base.symbol);
6565                                         entity->declaration.type = bitfield_type;
6566                                 } else {
6567                                         type_t *orig_type = entity->declaration.type;
6568                                         type_t *type      = skip_typeref(orig_type);
6569                                         if (is_type_function(type)) {
6570                                                 errorf(&entity->base.source_position,
6571                                                                 "compound member '%Y' must not have function type '%T'",
6572                                                                 entity->base.symbol, orig_type);
6573                                         } else if (is_type_incomplete(type)) {
6574                                                 /* §6.7.2.1:16 flexible array member */
6575                                                 if (!is_type_array(type)       ||
6576                                                                 token.type          != ';' ||
6577                                                                 look_ahead(1)->type != '}') {
6578                                                         errorf(&entity->base.source_position,
6579                                                                         "compound member '%Y' has incomplete type '%T'",
6580                                                                         entity->base.symbol, orig_type);
6581                                                 }
6582                                         }
6583                                 }
6584
6585                                 append_entity(&compound->members, entity);
6586                         }
6587                 }
6588
6589                 if (token.type != ',')
6590                         break;
6591                 next_token();
6592         }
6593         expect(';', end_error);
6594
6595 end_error:
6596         anonymous_entity = NULL;
6597 }
6598
6599 static void parse_compound_type_entries(compound_t *compound)
6600 {
6601         eat('{');
6602         add_anchor_token('}');
6603
6604         while (token.type != '}') {
6605                 if (token.type == T_EOF) {
6606                         errorf(HERE, "EOF while parsing struct");
6607                         break;
6608                 }
6609                 declaration_specifiers_t specifiers;
6610                 memset(&specifiers, 0, sizeof(specifiers));
6611                 parse_declaration_specifiers(&specifiers);
6612
6613                 parse_compound_declarators(compound, &specifiers);
6614         }
6615         rem_anchor_token('}');
6616         next_token();
6617
6618         /* §6.7.2.1:7 */
6619         compound->complete = true;
6620 }
6621
6622 static type_t *parse_typename(void)
6623 {
6624         declaration_specifiers_t specifiers;
6625         memset(&specifiers, 0, sizeof(specifiers));
6626         parse_declaration_specifiers(&specifiers);
6627         if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6628                         specifiers.thread_local) {
6629                 /* TODO: improve error message, user does probably not know what a
6630                  * storage class is...
6631                  */
6632                 errorf(HERE, "typename may not have a storage class");
6633         }
6634
6635         type_t *result = parse_abstract_declarator(specifiers.type);
6636
6637         return result;
6638 }
6639
6640
6641
6642
6643 typedef expression_t* (*parse_expression_function)(void);
6644 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6645
6646 typedef struct expression_parser_function_t expression_parser_function_t;
6647 struct expression_parser_function_t {
6648         parse_expression_function        parser;
6649         precedence_t                     infix_precedence;
6650         parse_expression_infix_function  infix_parser;
6651 };
6652
6653 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6654
6655 /**
6656  * Prints an error message if an expression was expected but not read
6657  */
6658 static expression_t *expected_expression_error(void)
6659 {
6660         /* skip the error message if the error token was read */
6661         if (token.type != T_ERROR) {
6662                 errorf(HERE, "expected expression, got token %K", &token);
6663         }
6664         next_token();
6665
6666         return create_invalid_expression();
6667 }
6668
6669 /**
6670  * Parse a string constant.
6671  */
6672 static expression_t *parse_string_const(void)
6673 {
6674         wide_string_t wres;
6675         if (token.type == T_STRING_LITERAL) {
6676                 string_t res = token.v.string;
6677                 next_token();
6678                 while (token.type == T_STRING_LITERAL) {
6679                         res = concat_strings(&res, &token.v.string);
6680                         next_token();
6681                 }
6682                 if (token.type != T_WIDE_STRING_LITERAL) {
6683                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6684                         /* note: that we use type_char_ptr here, which is already the
6685                          * automatic converted type. revert_automatic_type_conversion
6686                          * will construct the array type */
6687                         cnst->base.type    = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6688                         cnst->string.value = res;
6689                         return cnst;
6690                 }
6691
6692                 wres = concat_string_wide_string(&res, &token.v.wide_string);
6693         } else {
6694                 wres = token.v.wide_string;
6695         }
6696         next_token();
6697
6698         for (;;) {
6699                 switch (token.type) {
6700                         case T_WIDE_STRING_LITERAL:
6701                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
6702                                 break;
6703
6704                         case T_STRING_LITERAL:
6705                                 wres = concat_wide_string_string(&wres, &token.v.string);
6706                                 break;
6707
6708                         default: {
6709                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6710                                 cnst->base.type         = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6711                                 cnst->wide_string.value = wres;
6712                                 return cnst;
6713                         }
6714                 }
6715                 next_token();
6716         }
6717 }
6718
6719 /**
6720  * Parse a boolean constant.
6721  */
6722 static expression_t *parse_bool_const(bool value)
6723 {
6724         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6725         cnst->base.type          = type_bool;
6726         cnst->conste.v.int_value = value;
6727
6728         next_token();
6729
6730         return cnst;
6731 }
6732
6733 /**
6734  * Parse an integer constant.
6735  */
6736 static expression_t *parse_int_const(void)
6737 {
6738         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6739         cnst->base.type          = token.datatype;
6740         cnst->conste.v.int_value = token.v.intvalue;
6741
6742         next_token();
6743
6744         return cnst;
6745 }
6746
6747 /**
6748  * Parse a character constant.
6749  */
6750 static expression_t *parse_character_constant(void)
6751 {
6752         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6753         cnst->base.type          = token.datatype;
6754         cnst->conste.v.character = token.v.string;
6755
6756         if (cnst->conste.v.character.size != 1) {
6757                 if (!GNU_MODE) {
6758                         errorf(HERE, "more than 1 character in character constant");
6759                 } else if (warning.multichar) {
6760                         warningf(HERE, "multi-character character constant");
6761                 }
6762         }
6763         next_token();
6764
6765         return cnst;
6766 }
6767
6768 /**
6769  * Parse a wide character constant.
6770  */
6771 static expression_t *parse_wide_character_constant(void)
6772 {
6773         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6774         cnst->base.type               = token.datatype;
6775         cnst->conste.v.wide_character = token.v.wide_string;
6776
6777         if (cnst->conste.v.wide_character.size != 1) {
6778                 if (!GNU_MODE) {
6779                         errorf(HERE, "more than 1 character in character constant");
6780                 } else if (warning.multichar) {
6781                         warningf(HERE, "multi-character character constant");
6782                 }
6783         }
6784         next_token();
6785
6786         return cnst;
6787 }
6788
6789 /**
6790  * Parse a float constant.
6791  */
6792 static expression_t *parse_float_const(void)
6793 {
6794         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
6795         cnst->base.type            = token.datatype;
6796         cnst->conste.v.float_value = token.v.floatvalue;
6797
6798         next_token();
6799
6800         return cnst;
6801 }
6802
6803 static entity_t *create_implicit_function(symbol_t *symbol,
6804                 const source_position_t *source_position)
6805 {
6806         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
6807         ntype->function.return_type            = type_int;
6808         ntype->function.unspecified_parameters = true;
6809         ntype->function.linkage                = LINKAGE_C;
6810         type_t *type                           = identify_new_type(ntype);
6811
6812         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6813         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
6814         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6815         entity->declaration.type                   = type;
6816         entity->declaration.implicit               = true;
6817         entity->base.symbol                        = symbol;
6818         entity->base.source_position               = *source_position;
6819
6820         bool strict_prototypes_old = warning.strict_prototypes;
6821         warning.strict_prototypes  = false;
6822         record_entity(entity, false);
6823         warning.strict_prototypes = strict_prototypes_old;
6824
6825         return entity;
6826 }
6827
6828 /**
6829  * Creates a return_type (func)(argument_type) function type if not
6830  * already exists.
6831  */
6832 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6833                                     type_t *argument_type2)
6834 {
6835         function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6836         function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6837         parameter1->next = parameter2;
6838
6839         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6840         type->function.return_type = return_type;
6841         type->function.parameters  = parameter1;
6842
6843         return identify_new_type(type);
6844 }
6845
6846 /**
6847  * Creates a return_type (func)(argument_type) function type if not
6848  * already exists.
6849  *
6850  * @param return_type    the return type
6851  * @param argument_type  the argument type
6852  */
6853 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6854 {
6855         function_parameter_t *const parameter = allocate_parameter(argument_type);
6856
6857         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6858         type->function.return_type = return_type;
6859         type->function.parameters  = parameter;
6860
6861         return identify_new_type(type);
6862 }
6863
6864 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6865 {
6866         type_t *res = make_function_1_type(return_type, argument_type);
6867         res->function.variadic = 1;
6868         return res;
6869 }
6870
6871 /**
6872  * Creates a return_type (func)(void) function type if not
6873  * already exists.
6874  *
6875  * @param return_type    the return type
6876  */
6877 static type_t *make_function_0_type(type_t *return_type)
6878 {
6879         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6880         type->function.return_type = return_type;
6881         type->function.parameters  = NULL;
6882
6883         return identify_new_type(type);
6884 }
6885
6886 /**
6887  * Creates a NO_RETURN return_type (func)(void) function type if not
6888  * already exists.
6889  *
6890  * @param return_type    the return type
6891  */
6892 static type_t *make_function_0_type_noreturn(type_t *return_type)
6893 {
6894         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6895         type->function.return_type = return_type;
6896         type->function.parameters  = NULL;
6897         type->function.base.modifiers |= DM_NORETURN;
6898         return type;
6899
6900         return identify_new_type(type);
6901 }
6902
6903 /**
6904  * Performs automatic type cast as described in §6.3.2.1.
6905  *
6906  * @param orig_type  the original type
6907  */
6908 static type_t *automatic_type_conversion(type_t *orig_type)
6909 {
6910         type_t *type = skip_typeref(orig_type);
6911         if (is_type_array(type)) {
6912                 array_type_t *array_type   = &type->array;
6913                 type_t       *element_type = array_type->element_type;
6914                 unsigned      qualifiers   = array_type->base.qualifiers;
6915
6916                 return make_pointer_type(element_type, qualifiers);
6917         }
6918
6919         if (is_type_function(type)) {
6920                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6921         }
6922
6923         return orig_type;
6924 }
6925
6926 /**
6927  * reverts the automatic casts of array to pointer types and function
6928  * to function-pointer types as defined §6.3.2.1
6929  */
6930 type_t *revert_automatic_type_conversion(const expression_t *expression)
6931 {
6932         switch (expression->kind) {
6933                 case EXPR_REFERENCE: {
6934                         entity_t *entity = expression->reference.entity;
6935                         if (is_declaration(entity)) {
6936                                 return entity->declaration.type;
6937                         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6938                                 return entity->enum_value.enum_type;
6939                         } else {
6940                                 panic("no declaration or enum in reference");
6941                         }
6942                 }
6943
6944                 case EXPR_SELECT: {
6945                         entity_t *entity = expression->select.compound_entry;
6946                         assert(is_declaration(entity));
6947                         type_t   *type   = entity->declaration.type;
6948                         return get_qualified_type(type,
6949                                         expression->base.type->base.qualifiers);
6950                 }
6951
6952                 case EXPR_UNARY_DEREFERENCE: {
6953                         const expression_t *const value = expression->unary.value;
6954                         type_t             *const type  = skip_typeref(value->base.type);
6955                         if (!is_type_pointer(type))
6956                                 return type_error_type;
6957                         return type->pointer.points_to;
6958                 }
6959
6960                 case EXPR_ARRAY_ACCESS: {
6961                         const expression_t *array_ref = expression->array_access.array_ref;
6962                         type_t             *type_left = skip_typeref(array_ref->base.type);
6963                         if (!is_type_pointer(type_left))
6964                                 return type_error_type;
6965                         return type_left->pointer.points_to;
6966                 }
6967
6968                 case EXPR_STRING_LITERAL: {
6969                         size_t size = expression->string.value.size;
6970                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6971                 }
6972
6973                 case EXPR_WIDE_STRING_LITERAL: {
6974                         size_t size = expression->wide_string.value.size;
6975                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6976                 }
6977
6978                 case EXPR_COMPOUND_LITERAL:
6979                         return expression->compound_literal.type;
6980
6981                 default:
6982                         return expression->base.type;
6983         }
6984 }
6985
6986 static expression_t *parse_reference(void)
6987 {
6988         symbol_t *const symbol = token.v.symbol;
6989
6990         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6991
6992         if (entity == NULL) {
6993                 if (!strict_mode && look_ahead(1)->type == '(') {
6994                         /* an implicitly declared function */
6995                         if (warning.error_implicit_function_declaration) {
6996                                 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6997                         } else if (warning.implicit_function_declaration) {
6998                                 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6999                         }
7000
7001                         entity = create_implicit_function(symbol, HERE);
7002                 } else {
7003                         errorf(HERE, "unknown identifier '%Y' found.", symbol);
7004                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
7005                 }
7006         }
7007
7008         type_t *orig_type;
7009
7010         if (is_declaration(entity)) {
7011                 orig_type = entity->declaration.type;
7012         } else if (entity->kind == ENTITY_ENUM_VALUE) {
7013                 orig_type = entity->enum_value.enum_type;
7014         } else if (entity->kind == ENTITY_TYPEDEF) {
7015                 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7016                         symbol);
7017                 next_token();
7018                 return create_invalid_expression();
7019         } else {
7020                 panic("expected declaration or enum value in reference");
7021         }
7022
7023         /* we always do the auto-type conversions; the & and sizeof parser contains
7024          * code to revert this! */
7025         type_t *type = automatic_type_conversion(orig_type);
7026
7027         expression_kind_t kind = EXPR_REFERENCE;
7028         if (entity->kind == ENTITY_ENUM_VALUE)
7029                 kind = EXPR_REFERENCE_ENUM_VALUE;
7030
7031         expression_t *expression     = allocate_expression_zero(kind);
7032         expression->reference.entity = entity;
7033         expression->base.type        = type;
7034
7035         /* this declaration is used */
7036         if (is_declaration(entity)) {
7037                 entity->declaration.used = true;
7038         }
7039
7040         if (entity->base.parent_scope != file_scope
7041                 && entity->base.parent_scope->depth < current_function->parameters.depth
7042                 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7043                 if (entity->kind == ENTITY_VARIABLE) {
7044                         /* access of a variable from an outer function */
7045                         entity->variable.address_taken = true;
7046                 } else if (entity->kind == ENTITY_PARAMETER) {
7047                         entity->parameter.address_taken = true;
7048                 }
7049                 current_function->need_closure = true;
7050         }
7051
7052         /* check for deprecated functions */
7053         if (warning.deprecated_declarations
7054                 && is_declaration(entity)
7055                 && entity->declaration.modifiers & DM_DEPRECATED) {
7056                 declaration_t *declaration = &entity->declaration;
7057
7058                 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7059                         "function" : "variable";
7060
7061                 if (declaration->deprecated_string != NULL) {
7062                         warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7063                                  prefix, entity->base.symbol, &entity->base.source_position,
7064                                  declaration->deprecated_string);
7065                 } else {
7066                         warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7067                                  entity->base.symbol, &entity->base.source_position);
7068                 }
7069         }
7070
7071         if (warning.init_self && entity == current_init_decl && !in_type_prop
7072             && entity->kind == ENTITY_VARIABLE) {
7073                 current_init_decl = NULL;
7074                 warningf(HERE, "variable '%#T' is initialized by itself",
7075                          entity->declaration.type, entity->base.symbol);
7076         }
7077
7078         next_token();
7079         return expression;
7080 }
7081
7082 static bool semantic_cast(expression_t *cast)
7083 {
7084         expression_t            *expression      = cast->unary.value;
7085         type_t                  *orig_dest_type  = cast->base.type;
7086         type_t                  *orig_type_right = expression->base.type;
7087         type_t            const *dst_type        = skip_typeref(orig_dest_type);
7088         type_t            const *src_type        = skip_typeref(orig_type_right);
7089         source_position_t const *pos             = &cast->base.source_position;
7090
7091         /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7092         if (dst_type == type_void)
7093                 return true;
7094
7095         /* only integer and pointer can be casted to pointer */
7096         if (is_type_pointer(dst_type)  &&
7097             !is_type_pointer(src_type) &&
7098             !is_type_integer(src_type) &&
7099             is_type_valid(src_type)) {
7100                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7101                 return false;
7102         }
7103
7104         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7105                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7106                 return false;
7107         }
7108
7109         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7110                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7111                 return false;
7112         }
7113
7114         if (warning.cast_qual &&
7115             is_type_pointer(src_type) &&
7116             is_type_pointer(dst_type)) {
7117                 type_t *src = skip_typeref(src_type->pointer.points_to);
7118                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7119                 unsigned missing_qualifiers =
7120                         src->base.qualifiers & ~dst->base.qualifiers;
7121                 if (missing_qualifiers != 0) {
7122                         warningf(pos,
7123                                  "cast discards qualifiers '%Q' in pointer target type of '%T'",
7124                                  missing_qualifiers, orig_type_right);
7125                 }
7126         }
7127         return true;
7128 }
7129
7130 static expression_t *parse_compound_literal(type_t *type)
7131 {
7132         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7133
7134         parse_initializer_env_t env;
7135         env.type             = type;
7136         env.entity           = NULL;
7137         env.must_be_constant = false;
7138         initializer_t *initializer = parse_initializer(&env);
7139         type = env.type;
7140
7141         expression->compound_literal.initializer = initializer;
7142         expression->compound_literal.type        = type;
7143         expression->base.type                    = automatic_type_conversion(type);
7144
7145         return expression;
7146 }
7147
7148 /**
7149  * Parse a cast expression.
7150  */
7151 static expression_t *parse_cast(void)
7152 {
7153         add_anchor_token(')');
7154
7155         source_position_t source_position = token.source_position;
7156
7157         type_t *type = parse_typename();
7158
7159         rem_anchor_token(')');
7160         expect(')', end_error);
7161
7162         if (token.type == '{') {
7163                 return parse_compound_literal(type);
7164         }
7165
7166         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7167         cast->base.source_position = source_position;
7168
7169         expression_t *value = parse_sub_expression(PREC_CAST);
7170         cast->base.type   = type;
7171         cast->unary.value = value;
7172
7173         if (! semantic_cast(cast)) {
7174                 /* TODO: record the error in the AST. else it is impossible to detect it */
7175         }
7176
7177         return cast;
7178 end_error:
7179         return create_invalid_expression();
7180 }
7181
7182 /**
7183  * Parse a statement expression.
7184  */
7185 static expression_t *parse_statement_expression(void)
7186 {
7187         add_anchor_token(')');
7188
7189         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7190
7191         statement_t *statement          = parse_compound_statement(true);
7192         statement->compound.stmt_expr   = true;
7193         expression->statement.statement = statement;
7194
7195         /* find last statement and use its type */
7196         type_t *type = type_void;
7197         const statement_t *stmt = statement->compound.statements;
7198         if (stmt != NULL) {
7199                 while (stmt->base.next != NULL)
7200                         stmt = stmt->base.next;
7201
7202                 if (stmt->kind == STATEMENT_EXPRESSION) {
7203                         type = stmt->expression.expression->base.type;
7204                 }
7205         } else if (warning.other) {
7206                 warningf(&expression->base.source_position, "empty statement expression ({})");
7207         }
7208         expression->base.type = type;
7209
7210         rem_anchor_token(')');
7211         expect(')', end_error);
7212
7213 end_error:
7214         return expression;
7215 }
7216
7217 /**
7218  * Parse a parenthesized expression.
7219  */
7220 static expression_t *parse_parenthesized_expression(void)
7221 {
7222         eat('(');
7223
7224         switch (token.type) {
7225         case '{':
7226                 /* gcc extension: a statement expression */
7227                 return parse_statement_expression();
7228
7229         TYPE_QUALIFIERS
7230         TYPE_SPECIFIERS
7231                 return parse_cast();
7232         case T_IDENTIFIER:
7233                 if (is_typedef_symbol(token.v.symbol)) {
7234                         return parse_cast();
7235                 }
7236         }
7237
7238         add_anchor_token(')');
7239         expression_t *result = parse_expression();
7240         result->base.parenthesized = true;
7241         rem_anchor_token(')');
7242         expect(')', end_error);
7243
7244 end_error:
7245         return result;
7246 }
7247
7248 static expression_t *parse_function_keyword(void)
7249 {
7250         /* TODO */
7251
7252         if (current_function == NULL) {
7253                 errorf(HERE, "'__func__' used outside of a function");
7254         }
7255
7256         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7257         expression->base.type     = type_char_ptr;
7258         expression->funcname.kind = FUNCNAME_FUNCTION;
7259
7260         next_token();
7261
7262         return expression;
7263 }
7264
7265 static expression_t *parse_pretty_function_keyword(void)
7266 {
7267         if (current_function == NULL) {
7268                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7269         }
7270
7271         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7272         expression->base.type     = type_char_ptr;
7273         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7274
7275         eat(T___PRETTY_FUNCTION__);
7276
7277         return expression;
7278 }
7279
7280 static expression_t *parse_funcsig_keyword(void)
7281 {
7282         if (current_function == NULL) {
7283                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7284         }
7285
7286         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7287         expression->base.type     = type_char_ptr;
7288         expression->funcname.kind = FUNCNAME_FUNCSIG;
7289
7290         eat(T___FUNCSIG__);
7291
7292         return expression;
7293 }
7294
7295 static expression_t *parse_funcdname_keyword(void)
7296 {
7297         if (current_function == NULL) {
7298                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7299         }
7300
7301         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7302         expression->base.type     = type_char_ptr;
7303         expression->funcname.kind = FUNCNAME_FUNCDNAME;
7304
7305         eat(T___FUNCDNAME__);
7306
7307         return expression;
7308 }
7309
7310 static designator_t *parse_designator(void)
7311 {
7312         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
7313         result->source_position = *HERE;
7314
7315         if (token.type != T_IDENTIFIER) {
7316                 parse_error_expected("while parsing member designator",
7317                                      T_IDENTIFIER, NULL);
7318                 return NULL;
7319         }
7320         result->symbol = token.v.symbol;
7321         next_token();
7322
7323         designator_t *last_designator = result;
7324         while (true) {
7325                 if (token.type == '.') {
7326                         next_token();
7327                         if (token.type != T_IDENTIFIER) {
7328                                 parse_error_expected("while parsing member designator",
7329                                                      T_IDENTIFIER, NULL);
7330                                 return NULL;
7331                         }
7332                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7333                         designator->source_position = *HERE;
7334                         designator->symbol          = token.v.symbol;
7335                         next_token();
7336
7337                         last_designator->next = designator;
7338                         last_designator       = designator;
7339                         continue;
7340                 }
7341                 if (token.type == '[') {
7342                         next_token();
7343                         add_anchor_token(']');
7344                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7345                         designator->source_position = *HERE;
7346                         designator->array_index     = parse_expression();
7347                         rem_anchor_token(']');
7348                         expect(']', end_error);
7349                         if (designator->array_index == NULL) {
7350                                 return NULL;
7351                         }
7352
7353                         last_designator->next = designator;
7354                         last_designator       = designator;
7355                         continue;
7356                 }
7357                 break;
7358         }
7359
7360         return result;
7361 end_error:
7362         return NULL;
7363 }
7364
7365 /**
7366  * Parse the __builtin_offsetof() expression.
7367  */
7368 static expression_t *parse_offsetof(void)
7369 {
7370         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7371         expression->base.type    = type_size_t;
7372
7373         eat(T___builtin_offsetof);
7374
7375         expect('(', end_error);
7376         add_anchor_token(',');
7377         type_t *type = parse_typename();
7378         rem_anchor_token(',');
7379         expect(',', end_error);
7380         add_anchor_token(')');
7381         designator_t *designator = parse_designator();
7382         rem_anchor_token(')');
7383         expect(')', end_error);
7384
7385         expression->offsetofe.type       = type;
7386         expression->offsetofe.designator = designator;
7387
7388         type_path_t path;
7389         memset(&path, 0, sizeof(path));
7390         path.top_type = type;
7391         path.path     = NEW_ARR_F(type_path_entry_t, 0);
7392
7393         descend_into_subtype(&path);
7394
7395         if (!walk_designator(&path, designator, true)) {
7396                 return create_invalid_expression();
7397         }
7398
7399         DEL_ARR_F(path.path);
7400
7401         return expression;
7402 end_error:
7403         return create_invalid_expression();
7404 }
7405
7406 /**
7407  * Parses a _builtin_va_start() expression.
7408  */
7409 static expression_t *parse_va_start(void)
7410 {
7411         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7412
7413         eat(T___builtin_va_start);
7414
7415         expect('(', end_error);
7416         add_anchor_token(',');
7417         expression->va_starte.ap = parse_assignment_expression();
7418         rem_anchor_token(',');
7419         expect(',', end_error);
7420         expression_t *const expr = parse_assignment_expression();
7421         if (expr->kind == EXPR_REFERENCE) {
7422                 entity_t *const entity = expr->reference.entity;
7423                 if (entity->base.parent_scope != &current_function->parameters
7424                                 || entity->base.next != NULL
7425                                 || entity->kind != ENTITY_PARAMETER) {
7426                         errorf(&expr->base.source_position,
7427                                "second argument of 'va_start' must be last parameter of the current function");
7428                 } else {
7429                         expression->va_starte.parameter = &entity->variable;
7430                 }
7431                 expect(')', end_error);
7432                 return expression;
7433         }
7434         expect(')', end_error);
7435 end_error:
7436         return create_invalid_expression();
7437 }
7438
7439 /**
7440  * Parses a _builtin_va_arg() expression.
7441  */
7442 static expression_t *parse_va_arg(void)
7443 {
7444         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7445
7446         eat(T___builtin_va_arg);
7447
7448         expect('(', end_error);
7449         expression->va_arge.ap = parse_assignment_expression();
7450         expect(',', end_error);
7451         expression->base.type = parse_typename();
7452         expect(')', end_error);
7453
7454         return expression;
7455 end_error:
7456         return create_invalid_expression();
7457 }
7458
7459 /**
7460  * Parses a __builtin_constant_p() expression.
7461  */
7462 static expression_t *parse_builtin_constant(void)
7463 {
7464         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7465
7466         eat(T___builtin_constant_p);
7467
7468         expect('(', end_error);
7469         add_anchor_token(')');
7470         expression->builtin_constant.value = parse_assignment_expression();
7471         rem_anchor_token(')');
7472         expect(')', end_error);
7473         expression->base.type = type_int;
7474
7475         return expression;
7476 end_error:
7477         return create_invalid_expression();
7478 }
7479
7480 /**
7481  * Parses a __builtin_types_compatible_p() expression.
7482  */
7483 static expression_t *parse_builtin_types_compatible(void)
7484 {
7485         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7486
7487         eat(T___builtin_types_compatible_p);
7488
7489         expect('(', end_error);
7490         add_anchor_token(')');
7491         add_anchor_token(',');
7492         expression->builtin_types_compatible.left = parse_typename();
7493         rem_anchor_token(',');
7494         expect(',', end_error);
7495         expression->builtin_types_compatible.right = parse_typename();
7496         rem_anchor_token(')');
7497         expect(')', end_error);
7498         expression->base.type = type_int;
7499
7500         return expression;
7501 end_error:
7502         return create_invalid_expression();
7503 }
7504
7505 /**
7506  * Parses a __builtin_is_*() compare expression.
7507  */
7508 static expression_t *parse_compare_builtin(void)
7509 {
7510         expression_t *expression;
7511
7512         switch (token.type) {
7513         case T___builtin_isgreater:
7514                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7515                 break;
7516         case T___builtin_isgreaterequal:
7517                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7518                 break;
7519         case T___builtin_isless:
7520                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7521                 break;
7522         case T___builtin_islessequal:
7523                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7524                 break;
7525         case T___builtin_islessgreater:
7526                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7527                 break;
7528         case T___builtin_isunordered:
7529                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7530                 break;
7531         default:
7532                 internal_errorf(HERE, "invalid compare builtin found");
7533         }
7534         expression->base.source_position = *HERE;
7535         next_token();
7536
7537         expect('(', end_error);
7538         expression->binary.left = parse_assignment_expression();
7539         expect(',', end_error);
7540         expression->binary.right = parse_assignment_expression();
7541         expect(')', end_error);
7542
7543         type_t *const orig_type_left  = expression->binary.left->base.type;
7544         type_t *const orig_type_right = expression->binary.right->base.type;
7545
7546         type_t *const type_left  = skip_typeref(orig_type_left);
7547         type_t *const type_right = skip_typeref(orig_type_right);
7548         if (!is_type_float(type_left) && !is_type_float(type_right)) {
7549                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7550                         type_error_incompatible("invalid operands in comparison",
7551                                 &expression->base.source_position, orig_type_left, orig_type_right);
7552                 }
7553         } else {
7554                 semantic_comparison(&expression->binary);
7555         }
7556
7557         return expression;
7558 end_error:
7559         return create_invalid_expression();
7560 }
7561
7562 #if 0
7563 /**
7564  * Parses a __builtin_expect(, end_error) expression.
7565  */
7566 static expression_t *parse_builtin_expect(void, end_error)
7567 {
7568         expression_t *expression
7569                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7570
7571         eat(T___builtin_expect);
7572
7573         expect('(', end_error);
7574         expression->binary.left = parse_assignment_expression();
7575         expect(',', end_error);
7576         expression->binary.right = parse_constant_expression();
7577         expect(')', end_error);
7578
7579         expression->base.type = expression->binary.left->base.type;
7580
7581         return expression;
7582 end_error:
7583         return create_invalid_expression();
7584 }
7585 #endif
7586
7587 /**
7588  * Parses a MS assume() expression.
7589  */
7590 static expression_t *parse_assume(void)
7591 {
7592         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7593
7594         eat(T__assume);
7595
7596         expect('(', end_error);
7597         add_anchor_token(')');
7598         expression->unary.value = parse_assignment_expression();
7599         rem_anchor_token(')');
7600         expect(')', end_error);
7601
7602         expression->base.type = type_void;
7603         return expression;
7604 end_error:
7605         return create_invalid_expression();
7606 }
7607
7608 /**
7609  * Return the declaration for a given label symbol or create a new one.
7610  *
7611  * @param symbol  the symbol of the label
7612  */
7613 static label_t *get_label(symbol_t *symbol)
7614 {
7615         entity_t *label;
7616         assert(current_function != NULL);
7617
7618         label = get_entity(symbol, NAMESPACE_LABEL);
7619         /* if we found a local label, we already created the declaration */
7620         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7621                 if (label->base.parent_scope != current_scope) {
7622                         assert(label->base.parent_scope->depth < current_scope->depth);
7623                         current_function->goto_to_outer = true;
7624                 }
7625                 return &label->label;
7626         }
7627
7628         label = get_entity(symbol, NAMESPACE_LABEL);
7629         /* if we found a label in the same function, then we already created the
7630          * declaration */
7631         if (label != NULL
7632                         && label->base.parent_scope == &current_function->parameters) {
7633                 return &label->label;
7634         }
7635
7636         /* otherwise we need to create a new one */
7637         label               = allocate_entity_zero(ENTITY_LABEL);
7638         label->base.namespc = NAMESPACE_LABEL;
7639         label->base.symbol  = symbol;
7640
7641         label_push(label);
7642
7643         return &label->label;
7644 }
7645
7646 /**
7647  * Parses a GNU && label address expression.
7648  */
7649 static expression_t *parse_label_address(void)
7650 {
7651         source_position_t source_position = token.source_position;
7652         eat(T_ANDAND);
7653         if (token.type != T_IDENTIFIER) {
7654                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7655                 goto end_error;
7656         }
7657         symbol_t *symbol = token.v.symbol;
7658         next_token();
7659
7660         label_t *label       = get_label(symbol);
7661         label->used          = true;
7662         label->address_taken = true;
7663
7664         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7665         expression->base.source_position = source_position;
7666
7667         /* label address is threaten as a void pointer */
7668         expression->base.type           = type_void_ptr;
7669         expression->label_address.label = label;
7670         return expression;
7671 end_error:
7672         return create_invalid_expression();
7673 }
7674
7675 /**
7676  * Parse a microsoft __noop expression.
7677  */
7678 static expression_t *parse_noop_expression(void)
7679 {
7680         /* the result is a (int)0 */
7681         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
7682         cnst->base.type            = type_int;
7683         cnst->conste.v.int_value   = 0;
7684         cnst->conste.is_ms_noop    = true;
7685
7686         eat(T___noop);
7687
7688         if (token.type == '(') {
7689                 /* parse arguments */
7690                 eat('(');
7691                 add_anchor_token(')');
7692                 add_anchor_token(',');
7693
7694                 if (token.type != ')') {
7695                         while (true) {
7696                                 (void)parse_assignment_expression();
7697                                 if (token.type != ',')
7698                                         break;
7699                                 next_token();
7700                         }
7701                 }
7702         }
7703         rem_anchor_token(',');
7704         rem_anchor_token(')');
7705         expect(')', end_error);
7706
7707 end_error:
7708         return cnst;
7709 }
7710
7711 /**
7712  * Parses a primary expression.
7713  */
7714 static expression_t *parse_primary_expression(void)
7715 {
7716         switch (token.type) {
7717                 case T_false:                        return parse_bool_const(false);
7718                 case T_true:                         return parse_bool_const(true);
7719                 case T_INTEGER:                      return parse_int_const();
7720                 case T_CHARACTER_CONSTANT:           return parse_character_constant();
7721                 case T_WIDE_CHARACTER_CONSTANT:      return parse_wide_character_constant();
7722                 case T_FLOATINGPOINT:                return parse_float_const();
7723                 case T_STRING_LITERAL:
7724                 case T_WIDE_STRING_LITERAL:          return parse_string_const();
7725                 case T_IDENTIFIER:                   return parse_reference();
7726                 case T___FUNCTION__:
7727                 case T___func__:                     return parse_function_keyword();
7728                 case T___PRETTY_FUNCTION__:          return parse_pretty_function_keyword();
7729                 case T___FUNCSIG__:                  return parse_funcsig_keyword();
7730                 case T___FUNCDNAME__:                return parse_funcdname_keyword();
7731                 case T___builtin_offsetof:           return parse_offsetof();
7732                 case T___builtin_va_start:           return parse_va_start();
7733                 case T___builtin_va_arg:             return parse_va_arg();
7734                 case T___builtin_isgreater:
7735                 case T___builtin_isgreaterequal:
7736                 case T___builtin_isless:
7737                 case T___builtin_islessequal:
7738                 case T___builtin_islessgreater:
7739                 case T___builtin_isunordered:        return parse_compare_builtin();
7740                 case T___builtin_constant_p:         return parse_builtin_constant();
7741                 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7742                 case T__assume:                      return parse_assume();
7743                 case T_ANDAND:
7744                         if (GNU_MODE)
7745                                 return parse_label_address();
7746                         break;
7747
7748                 case '(':                            return parse_parenthesized_expression();
7749                 case T___noop:                       return parse_noop_expression();
7750         }
7751
7752         errorf(HERE, "unexpected token %K, expected an expression", &token);
7753         return create_invalid_expression();
7754 }
7755
7756 /**
7757  * Check if the expression has the character type and issue a warning then.
7758  */
7759 static void check_for_char_index_type(const expression_t *expression)
7760 {
7761         type_t       *const type      = expression->base.type;
7762         const type_t *const base_type = skip_typeref(type);
7763
7764         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7765                         warning.char_subscripts) {
7766                 warningf(&expression->base.source_position,
7767                          "array subscript has type '%T'", type);
7768         }
7769 }
7770
7771 static expression_t *parse_array_expression(expression_t *left)
7772 {
7773         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7774
7775         eat('[');
7776         add_anchor_token(']');
7777
7778         expression_t *inside = parse_expression();
7779
7780         type_t *const orig_type_left   = left->base.type;
7781         type_t *const orig_type_inside = inside->base.type;
7782
7783         type_t *const type_left   = skip_typeref(orig_type_left);
7784         type_t *const type_inside = skip_typeref(orig_type_inside);
7785
7786         type_t                    *return_type;
7787         array_access_expression_t *array_access = &expression->array_access;
7788         if (is_type_pointer(type_left)) {
7789                 return_type             = type_left->pointer.points_to;
7790                 array_access->array_ref = left;
7791                 array_access->index     = inside;
7792                 check_for_char_index_type(inside);
7793         } else if (is_type_pointer(type_inside)) {
7794                 return_type             = type_inside->pointer.points_to;
7795                 array_access->array_ref = inside;
7796                 array_access->index     = left;
7797                 array_access->flipped   = true;
7798                 check_for_char_index_type(left);
7799         } else {
7800                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7801                         errorf(HERE,
7802                                 "array access on object with non-pointer types '%T', '%T'",
7803                                 orig_type_left, orig_type_inside);
7804                 }
7805                 return_type             = type_error_type;
7806                 array_access->array_ref = left;
7807                 array_access->index     = inside;
7808         }
7809
7810         expression->base.type = automatic_type_conversion(return_type);
7811
7812         rem_anchor_token(']');
7813         expect(']', end_error);
7814 end_error:
7815         return expression;
7816 }
7817
7818 static expression_t *parse_typeprop(expression_kind_t const kind)
7819 {
7820         expression_t  *tp_expression = allocate_expression_zero(kind);
7821         tp_expression->base.type     = type_size_t;
7822
7823         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7824
7825         /* we only refer to a type property, mark this case */
7826         bool old     = in_type_prop;
7827         in_type_prop = true;
7828
7829         type_t       *orig_type;
7830         expression_t *expression;
7831         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7832                 next_token();
7833                 add_anchor_token(')');
7834                 orig_type = parse_typename();
7835                 rem_anchor_token(')');
7836                 expect(')', end_error);
7837
7838                 if (token.type == '{') {
7839                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7840                          * starting with a compound literal */
7841                         expression = parse_compound_literal(orig_type);
7842                         goto typeprop_expression;
7843                 }
7844         } else {
7845                 expression = parse_sub_expression(PREC_UNARY);
7846
7847 typeprop_expression:
7848                 tp_expression->typeprop.tp_expression = expression;
7849
7850                 orig_type = revert_automatic_type_conversion(expression);
7851                 expression->base.type = orig_type;
7852         }
7853
7854         tp_expression->typeprop.type   = orig_type;
7855         type_t const* const type       = skip_typeref(orig_type);
7856         char   const* const wrong_type =
7857                 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL                  :
7858                 is_type_incomplete(type)                           ? "incomplete"          :
7859                 type->kind == TYPE_FUNCTION                        ? "function designator" :
7860                 type->kind == TYPE_BITFIELD                        ? "bitfield"            :
7861                 NULL;
7862         if (wrong_type != NULL) {
7863                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7864                 errorf(&tp_expression->base.source_position,
7865                                 "operand of %s expression must not be of %s type '%T'",
7866                                 what, wrong_type, orig_type);
7867         }
7868
7869 end_error:
7870         in_type_prop = old;
7871         return tp_expression;
7872 }
7873
7874 static expression_t *parse_sizeof(void)
7875 {
7876         return parse_typeprop(EXPR_SIZEOF);
7877 }
7878
7879 static expression_t *parse_alignof(void)
7880 {
7881         return parse_typeprop(EXPR_ALIGNOF);
7882 }
7883
7884 static expression_t *parse_select_expression(expression_t *compound)
7885 {
7886         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
7887         select->select.compound = compound;
7888
7889         assert(token.type == '.' || token.type == T_MINUSGREATER);
7890         bool is_pointer = (token.type == T_MINUSGREATER);
7891         next_token();
7892
7893         if (token.type != T_IDENTIFIER) {
7894                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7895                 return select;
7896         }
7897         symbol_t *symbol = token.v.symbol;
7898         next_token();
7899
7900         type_t *const orig_type = compound->base.type;
7901         type_t *const type      = skip_typeref(orig_type);
7902
7903         type_t *type_left;
7904         bool    saw_error = false;
7905         if (is_type_pointer(type)) {
7906                 if (!is_pointer) {
7907                         errorf(HERE,
7908                                "request for member '%Y' in something not a struct or union, but '%T'",
7909                                symbol, orig_type);
7910                         saw_error = true;
7911                 }
7912                 type_left = skip_typeref(type->pointer.points_to);
7913         } else {
7914                 if (is_pointer && is_type_valid(type)) {
7915                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7916                         saw_error = true;
7917                 }
7918                 type_left = type;
7919         }
7920
7921         entity_t *entry;
7922         if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7923             type_left->kind == TYPE_COMPOUND_UNION) {
7924                 compound_t *compound = type_left->compound.compound;
7925
7926                 if (!compound->complete) {
7927                         errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7928                                symbol, type_left);
7929                         goto create_error_entry;
7930                 }
7931
7932                 entry = find_compound_entry(compound, symbol);
7933                 if (entry == NULL) {
7934                         errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7935                         goto create_error_entry;
7936                 }
7937         } else {
7938                 if (is_type_valid(type_left) && !saw_error) {
7939                         errorf(HERE,
7940                                "request for member '%Y' in something not a struct or union, but '%T'",
7941                                symbol, type_left);
7942                 }
7943 create_error_entry:
7944                 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7945         }
7946
7947         assert(is_declaration(entry));
7948         select->select.compound_entry = entry;
7949
7950         type_t *entry_type = entry->declaration.type;
7951         type_t *res_type
7952                 = get_qualified_type(entry_type, type_left->base.qualifiers);
7953
7954         /* we always do the auto-type conversions; the & and sizeof parser contains
7955          * code to revert this! */
7956         select->base.type = automatic_type_conversion(res_type);
7957
7958         type_t *skipped = skip_typeref(res_type);
7959         if (skipped->kind == TYPE_BITFIELD) {
7960                 select->base.type = skipped->bitfield.base_type;
7961         }
7962
7963         return select;
7964 }
7965
7966 static void check_call_argument(const function_parameter_t *parameter,
7967                                 call_argument_t *argument, unsigned pos)
7968 {
7969         type_t         *expected_type      = parameter->type;
7970         type_t         *expected_type_skip = skip_typeref(expected_type);
7971         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7972         expression_t   *arg_expr           = argument->expression;
7973         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7974
7975         /* handle transparent union gnu extension */
7976         if (is_type_union(expected_type_skip)
7977                         && (expected_type_skip->base.modifiers
7978                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7979                 compound_t *union_decl  = expected_type_skip->compound.compound;
7980                 type_t     *best_type   = NULL;
7981                 entity_t   *entry       = union_decl->members.entities;
7982                 for ( ; entry != NULL; entry = entry->base.next) {
7983                         assert(is_declaration(entry));
7984                         type_t *decl_type = entry->declaration.type;
7985                         error = semantic_assign(decl_type, arg_expr);
7986                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7987                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7988                                 continue;
7989
7990                         if (error == ASSIGN_SUCCESS) {
7991                                 best_type = decl_type;
7992                         } else if (best_type == NULL) {
7993                                 best_type = decl_type;
7994                         }
7995                 }
7996
7997                 if (best_type != NULL) {
7998                         expected_type = best_type;
7999                 }
8000         }
8001
8002         error                = semantic_assign(expected_type, arg_expr);
8003         argument->expression = create_implicit_cast(argument->expression,
8004                                                     expected_type);
8005
8006         if (error != ASSIGN_SUCCESS) {
8007                 /* report exact scope in error messages (like "in argument 3") */
8008                 char buf[64];
8009                 snprintf(buf, sizeof(buf), "call argument %u", pos);
8010                 report_assign_error(error, expected_type, arg_expr,     buf,
8011                                                         &arg_expr->base.source_position);
8012         } else if (warning.traditional || warning.conversion) {
8013                 type_t *const promoted_type = get_default_promoted_type(arg_type);
8014                 if (!types_compatible(expected_type_skip, promoted_type) &&
8015                     !types_compatible(expected_type_skip, type_void_ptr) &&
8016                     !types_compatible(type_void_ptr,      promoted_type)) {
8017                         /* Deliberately show the skipped types in this warning */
8018                         warningf(&arg_expr->base.source_position,
8019                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
8020                                 pos, expected_type_skip, promoted_type);
8021                 }
8022         }
8023 }
8024
8025 /**
8026  * Handle the semantic restrictions of builtin calls
8027  */
8028 static void handle_builtin_argument_restrictions(call_expression_t *call) {
8029         switch (call->function->reference.entity->function.btk) {
8030                 case bk_gnu_builtin_return_address:
8031                 case bk_gnu_builtin_frame_address: {
8032                         /* argument must be constant */
8033                         call_argument_t *argument = call->arguments;
8034
8035                         if (! is_constant_expression(argument->expression)) {
8036                                 errorf(&call->base.source_position,
8037                                        "argument of '%Y' must be a constant expression",
8038                                        call->function->reference.entity->base.symbol);
8039                         }
8040                         break;
8041                 }
8042                 case bk_gnu_builtin_prefetch: {
8043                         /* second and third argument must be constant if existent */
8044                         call_argument_t *rw = call->arguments->next;
8045                         call_argument_t *locality = NULL;
8046
8047                         if (rw != NULL) {
8048                                 if (! is_constant_expression(rw->expression)) {
8049                                         errorf(&call->base.source_position,
8050                                                "second argument of '%Y' must be a constant expression",
8051                                                call->function->reference.entity->base.symbol);
8052                                 }
8053                                 locality = rw->next;
8054                         }
8055                         if (locality != NULL) {
8056                                 if (! is_constant_expression(locality->expression)) {
8057                                         errorf(&call->base.source_position,
8058                                                "third argument of '%Y' must be a constant expression",
8059                                                call->function->reference.entity->base.symbol);
8060                                 }
8061                                 locality = rw->next;
8062                         }
8063                         break;
8064                 }
8065                 default:
8066                         break;
8067         }
8068 }
8069
8070 /**
8071  * Parse a call expression, ie. expression '( ... )'.
8072  *
8073  * @param expression  the function address
8074  */
8075 static expression_t *parse_call_expression(expression_t *expression)
8076 {
8077         expression_t      *result = allocate_expression_zero(EXPR_CALL);
8078         call_expression_t *call   = &result->call;
8079         call->function            = expression;
8080
8081         type_t *const orig_type = expression->base.type;
8082         type_t *const type      = skip_typeref(orig_type);
8083
8084         function_type_t *function_type = NULL;
8085         if (is_type_pointer(type)) {
8086                 type_t *const to_type = skip_typeref(type->pointer.points_to);
8087
8088                 if (is_type_function(to_type)) {
8089                         function_type   = &to_type->function;
8090                         call->base.type = function_type->return_type;
8091                 }
8092         }
8093
8094         if (function_type == NULL && is_type_valid(type)) {
8095                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8096         }
8097
8098         /* parse arguments */
8099         eat('(');
8100         add_anchor_token(')');
8101         add_anchor_token(',');
8102
8103         if (token.type != ')') {
8104                 call_argument_t **anchor = &call->arguments;
8105                 for (;;) {
8106                         call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
8107                         argument->expression = parse_assignment_expression();
8108
8109                         *anchor = argument;
8110                         anchor  = &argument->next;
8111
8112                         if (token.type != ',')
8113                                 break;
8114                         next_token();
8115                 }
8116         }
8117         rem_anchor_token(',');
8118         rem_anchor_token(')');
8119         expect(')', end_error);
8120
8121         if (function_type == NULL)
8122                 return result;
8123
8124         function_parameter_t *parameter = function_type->parameters;
8125         call_argument_t      *argument  = call->arguments;
8126         if (!function_type->unspecified_parameters) {
8127                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8128                                 parameter = parameter->next, argument = argument->next) {
8129                         check_call_argument(parameter, argument, ++pos);
8130                 }
8131
8132                 if (parameter != NULL) {
8133                         errorf(HERE, "too few arguments to function '%E'", expression);
8134                 } else if (argument != NULL && !function_type->variadic) {
8135                         errorf(HERE, "too many arguments to function '%E'", expression);
8136                 }
8137         }
8138
8139         /* do default promotion */
8140         for (; argument != NULL; argument = argument->next) {
8141                 type_t *type = argument->expression->base.type;
8142
8143                 type = get_default_promoted_type(type);
8144
8145                 argument->expression
8146                         = create_implicit_cast(argument->expression, type);
8147         }
8148
8149         check_format(&result->call);
8150
8151         if (warning.aggregate_return &&
8152             is_type_compound(skip_typeref(function_type->return_type))) {
8153                 warningf(&result->base.source_position,
8154                          "function call has aggregate value");
8155         }
8156
8157         if (call->function->kind == EXPR_REFERENCE) {
8158                 reference_expression_t *reference = &call->function->reference;
8159                 if (reference->entity->kind == ENTITY_FUNCTION &&
8160                     reference->entity->function.btk != bk_none)
8161                         handle_builtin_argument_restrictions(call);
8162         }
8163
8164 end_error:
8165         return result;
8166 }
8167
8168 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8169
8170 static bool same_compound_type(const type_t *type1, const type_t *type2)
8171 {
8172         return
8173                 is_type_compound(type1) &&
8174                 type1->kind == type2->kind &&
8175                 type1->compound.compound == type2->compound.compound;
8176 }
8177
8178 static expression_t const *get_reference_address(expression_t const *expr)
8179 {
8180         bool regular_take_address = true;
8181         for (;;) {
8182                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8183                         expr = expr->unary.value;
8184                 } else {
8185                         regular_take_address = false;
8186                 }
8187
8188                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8189                         break;
8190
8191                 expr = expr->unary.value;
8192         }
8193
8194         if (expr->kind != EXPR_REFERENCE)
8195                 return NULL;
8196
8197         /* special case for functions which are automatically converted to a
8198          * pointer to function without an extra TAKE_ADDRESS operation */
8199         if (!regular_take_address &&
8200                         expr->reference.entity->kind != ENTITY_FUNCTION) {
8201                 return NULL;
8202         }
8203
8204         return expr;
8205 }
8206
8207 static void warn_reference_address_as_bool(expression_t const* expr)
8208 {
8209         if (!warning.address)
8210                 return;
8211
8212         expr = get_reference_address(expr);
8213         if (expr != NULL) {
8214                 warningf(&expr->base.source_position,
8215                          "the address of '%Y' will always evaluate as 'true'",
8216                          expr->reference.entity->base.symbol);
8217         }
8218 }
8219
8220 static void warn_assignment_in_condition(const expression_t *const expr)
8221 {
8222         if (!warning.parentheses)
8223                 return;
8224         if (expr->base.kind != EXPR_BINARY_ASSIGN)
8225                 return;
8226         if (expr->base.parenthesized)
8227                 return;
8228         warningf(&expr->base.source_position,
8229                         "suggest parentheses around assignment used as truth value");
8230 }
8231
8232 static void semantic_condition(expression_t const *const expr,
8233                                char const *const context)
8234 {
8235         type_t *const type = skip_typeref(expr->base.type);
8236         if (is_type_scalar(type)) {
8237                 warn_reference_address_as_bool(expr);
8238                 warn_assignment_in_condition(expr);
8239         } else if (is_type_valid(type)) {
8240                 errorf(&expr->base.source_position,
8241                                 "%s must have scalar type", context);
8242         }
8243 }
8244
8245 /**
8246  * Parse a conditional expression, ie. 'expression ? ... : ...'.
8247  *
8248  * @param expression  the conditional expression
8249  */
8250 static expression_t *parse_conditional_expression(expression_t *expression)
8251 {
8252         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8253
8254         conditional_expression_t *conditional = &result->conditional;
8255         conditional->condition                = expression;
8256
8257         eat('?');
8258         add_anchor_token(':');
8259
8260         /* §6.5.15:2  The first operand shall have scalar type. */
8261         semantic_condition(expression, "condition of conditional operator");
8262
8263         expression_t *true_expression = expression;
8264         bool          gnu_cond = false;
8265         if (GNU_MODE && token.type == ':') {
8266                 gnu_cond = true;
8267         } else {
8268                 true_expression = parse_expression();
8269         }
8270         rem_anchor_token(':');
8271         expect(':', end_error);
8272 end_error:;
8273         expression_t *false_expression =
8274                 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8275
8276         type_t *const orig_true_type  = true_expression->base.type;
8277         type_t *const orig_false_type = false_expression->base.type;
8278         type_t *const true_type       = skip_typeref(orig_true_type);
8279         type_t *const false_type      = skip_typeref(orig_false_type);
8280
8281         /* 6.5.15.3 */
8282         type_t *result_type;
8283         if (is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8284                         is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8285                 /* ISO/IEC 14882:1998(E) §5.16:2 */
8286                 if (true_expression->kind == EXPR_UNARY_THROW) {
8287                         result_type = false_type;
8288                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8289                         result_type = true_type;
8290                 } else {
8291                         if (warning.other && (
8292                                                 !is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8293                                                 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8294                                         )) {
8295                                 warningf(&conditional->base.source_position,
8296                                                 "ISO C forbids conditional expression with only one void side");
8297                         }
8298                         result_type = type_void;
8299                 }
8300         } else if (is_type_arithmetic(true_type)
8301                    && is_type_arithmetic(false_type)) {
8302                 result_type = semantic_arithmetic(true_type, false_type);
8303
8304                 true_expression  = create_implicit_cast(true_expression, result_type);
8305                 false_expression = create_implicit_cast(false_expression, result_type);
8306
8307                 conditional->true_expression  = true_expression;
8308                 conditional->false_expression = false_expression;
8309                 conditional->base.type        = result_type;
8310         } else if (same_compound_type(true_type, false_type)) {
8311                 /* just take 1 of the 2 types */
8312                 result_type = true_type;
8313         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8314                 type_t *pointer_type;
8315                 type_t *other_type;
8316                 expression_t *other_expression;
8317                 if (is_type_pointer(true_type) &&
8318                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8319                         pointer_type     = true_type;
8320                         other_type       = false_type;
8321                         other_expression = false_expression;
8322                 } else {
8323                         pointer_type     = false_type;
8324                         other_type       = true_type;
8325                         other_expression = true_expression;
8326                 }
8327
8328                 if (is_null_pointer_constant(other_expression)) {
8329                         result_type = pointer_type;
8330                 } else if (is_type_pointer(other_type)) {
8331                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8332                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
8333
8334                         type_t *to;
8335                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8336                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8337                                 to = type_void;
8338                         } else if (types_compatible(get_unqualified_type(to1),
8339                                                     get_unqualified_type(to2))) {
8340                                 to = to1;
8341                         } else {
8342                                 if (warning.other) {
8343                                         warningf(&conditional->base.source_position,
8344                                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
8345                                                         true_type, false_type);
8346                                 }
8347                                 to = type_void;
8348                         }
8349
8350                         type_t *const type =
8351                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8352                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8353                 } else if (is_type_integer(other_type)) {
8354                         if (warning.other) {
8355                                 warningf(&conditional->base.source_position,
8356                                                 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8357                         }
8358                         result_type = pointer_type;
8359                 } else {
8360                         if (is_type_valid(other_type)) {
8361                                 type_error_incompatible("while parsing conditional",
8362                                                 &expression->base.source_position, true_type, false_type);
8363                         }
8364                         result_type = type_error_type;
8365                 }
8366         } else {
8367                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8368                         type_error_incompatible("while parsing conditional",
8369                                                 &conditional->base.source_position, true_type,
8370                                                 false_type);
8371                 }
8372                 result_type = type_error_type;
8373         }
8374
8375         conditional->true_expression
8376                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8377         conditional->false_expression
8378                 = create_implicit_cast(false_expression, result_type);
8379         conditional->base.type = result_type;
8380         return result;
8381 }
8382
8383 /**
8384  * Parse an extension expression.
8385  */
8386 static expression_t *parse_extension(void)
8387 {
8388         eat(T___extension__);
8389
8390         bool old_gcc_extension   = in_gcc_extension;
8391         in_gcc_extension         = true;
8392         expression_t *expression = parse_sub_expression(PREC_UNARY);
8393         in_gcc_extension         = old_gcc_extension;
8394         return expression;
8395 }
8396
8397 /**
8398  * Parse a __builtin_classify_type() expression.
8399  */
8400 static expression_t *parse_builtin_classify_type(void)
8401 {
8402         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8403         result->base.type    = type_int;
8404
8405         eat(T___builtin_classify_type);
8406
8407         expect('(', end_error);
8408         add_anchor_token(')');
8409         expression_t *expression = parse_expression();
8410         rem_anchor_token(')');
8411         expect(')', end_error);
8412         result->classify_type.type_expression = expression;
8413
8414         return result;
8415 end_error:
8416         return create_invalid_expression();
8417 }
8418
8419 /**
8420  * Parse a delete expression
8421  * ISO/IEC 14882:1998(E) §5.3.5
8422  */
8423 static expression_t *parse_delete(void)
8424 {
8425         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8426         result->base.type          = type_void;
8427
8428         eat(T_delete);
8429
8430         if (token.type == '[') {
8431                 next_token();
8432                 result->kind = EXPR_UNARY_DELETE_ARRAY;
8433                 expect(']', end_error);
8434 end_error:;
8435         }
8436
8437         expression_t *const value = parse_sub_expression(PREC_CAST);
8438         result->unary.value = value;
8439
8440         type_t *const type = skip_typeref(value->base.type);
8441         if (!is_type_pointer(type)) {
8442                 if (is_type_valid(type)) {
8443                         errorf(&value->base.source_position,
8444                                         "operand of delete must have pointer type");
8445                 }
8446         } else if (warning.other &&
8447                         is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8448                 warningf(&value->base.source_position,
8449                                 "deleting 'void*' is undefined");
8450         }
8451
8452         return result;
8453 }
8454
8455 /**
8456  * Parse a throw expression
8457  * ISO/IEC 14882:1998(E) §15:1
8458  */
8459 static expression_t *parse_throw(void)
8460 {
8461         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8462         result->base.type          = type_void;
8463
8464         eat(T_throw);
8465
8466         expression_t *value = NULL;
8467         switch (token.type) {
8468                 EXPRESSION_START {
8469                         value = parse_assignment_expression();
8470                         /* ISO/IEC 14882:1998(E) §15.1:3 */
8471                         type_t *const orig_type = value->base.type;
8472                         type_t *const type      = skip_typeref(orig_type);
8473                         if (is_type_incomplete(type)) {
8474                                 errorf(&value->base.source_position,
8475                                                 "cannot throw object of incomplete type '%T'", orig_type);
8476                         } else if (is_type_pointer(type)) {
8477                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
8478                                 if (is_type_incomplete(points_to) &&
8479                                                 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8480                                         errorf(&value->base.source_position,
8481                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
8482                                 }
8483                         }
8484                 }
8485
8486                 default:
8487                         break;
8488         }
8489         result->unary.value = value;
8490
8491         return result;
8492 }
8493
8494 static bool check_pointer_arithmetic(const source_position_t *source_position,
8495                                      type_t *pointer_type,
8496                                      type_t *orig_pointer_type)
8497 {
8498         type_t *points_to = pointer_type->pointer.points_to;
8499         points_to = skip_typeref(points_to);
8500
8501         if (is_type_incomplete(points_to)) {
8502                 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8503                         errorf(source_position,
8504                                "arithmetic with pointer to incomplete type '%T' not allowed",
8505                                orig_pointer_type);
8506                         return false;
8507                 } else if (warning.pointer_arith) {
8508                         warningf(source_position,
8509                                  "pointer of type '%T' used in arithmetic",
8510                                  orig_pointer_type);
8511                 }
8512         } else if (is_type_function(points_to)) {
8513                 if (!GNU_MODE) {
8514                         errorf(source_position,
8515                                "arithmetic with pointer to function type '%T' not allowed",
8516                                orig_pointer_type);
8517                         return false;
8518                 } else if (warning.pointer_arith) {
8519                         warningf(source_position,
8520                                  "pointer to a function '%T' used in arithmetic",
8521                                  orig_pointer_type);
8522                 }
8523         }
8524         return true;
8525 }
8526
8527 static bool is_lvalue(const expression_t *expression)
8528 {
8529         /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8530         switch (expression->kind) {
8531         case EXPR_ARRAY_ACCESS:
8532         case EXPR_COMPOUND_LITERAL:
8533         case EXPR_REFERENCE:
8534         case EXPR_SELECT:
8535         case EXPR_UNARY_DEREFERENCE:
8536                 return true;
8537
8538         default: {
8539           type_t *type = skip_typeref(expression->base.type);
8540           return
8541                 /* ISO/IEC 14882:1998(E) §3.10:3 */
8542                 is_type_reference(type) ||
8543                 /* Claim it is an lvalue, if the type is invalid.  There was a parse
8544                  * error before, which maybe prevented properly recognizing it as
8545                  * lvalue. */
8546                 !is_type_valid(type);
8547         }
8548         }
8549 }
8550
8551 static void semantic_incdec(unary_expression_t *expression)
8552 {
8553         type_t *const orig_type = expression->value->base.type;
8554         type_t *const type      = skip_typeref(orig_type);
8555         if (is_type_pointer(type)) {
8556                 if (!check_pointer_arithmetic(&expression->base.source_position,
8557                                               type, orig_type)) {
8558                         return;
8559                 }
8560         } else if (!is_type_real(type) && is_type_valid(type)) {
8561                 /* TODO: improve error message */
8562                 errorf(&expression->base.source_position,
8563                        "operation needs an arithmetic or pointer type");
8564                 return;
8565         }
8566         if (!is_lvalue(expression->value)) {
8567                 /* TODO: improve error message */
8568                 errorf(&expression->base.source_position, "lvalue required as operand");
8569         }
8570         expression->base.type = orig_type;
8571 }
8572
8573 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8574 {
8575         type_t *const orig_type = expression->value->base.type;
8576         type_t *const type      = skip_typeref(orig_type);
8577         if (!is_type_arithmetic(type)) {
8578                 if (is_type_valid(type)) {
8579                         /* TODO: improve error message */
8580                         errorf(&expression->base.source_position,
8581                                 "operation needs an arithmetic type");
8582                 }
8583                 return;
8584         }
8585
8586         expression->base.type = orig_type;
8587 }
8588
8589 static void semantic_unexpr_plus(unary_expression_t *expression)
8590 {
8591         semantic_unexpr_arithmetic(expression);
8592         if (warning.traditional)
8593                 warningf(&expression->base.source_position,
8594                         "traditional C rejects the unary plus operator");
8595 }
8596
8597 static void semantic_not(unary_expression_t *expression)
8598 {
8599         /* §6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
8600         semantic_condition(expression->value, "operand of !");
8601         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8602 }
8603
8604 static void semantic_unexpr_integer(unary_expression_t *expression)
8605 {
8606         type_t *const orig_type = expression->value->base.type;
8607         type_t *const type      = skip_typeref(orig_type);
8608         if (!is_type_integer(type)) {
8609                 if (is_type_valid(type)) {
8610                         errorf(&expression->base.source_position,
8611                                "operand of ~ must be of integer type");
8612                 }
8613                 return;
8614         }
8615
8616         expression->base.type = orig_type;
8617 }
8618
8619 static void semantic_dereference(unary_expression_t *expression)
8620 {
8621         type_t *const orig_type = expression->value->base.type;
8622         type_t *const type      = skip_typeref(orig_type);
8623         if (!is_type_pointer(type)) {
8624                 if (is_type_valid(type)) {
8625                         errorf(&expression->base.source_position,
8626                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8627                 }
8628                 return;
8629         }
8630
8631         type_t *result_type   = type->pointer.points_to;
8632         result_type           = automatic_type_conversion(result_type);
8633         expression->base.type = result_type;
8634 }
8635
8636 /**
8637  * Record that an address is taken (expression represents an lvalue).
8638  *
8639  * @param expression       the expression
8640  * @param may_be_register  if true, the expression might be an register
8641  */
8642 static void set_address_taken(expression_t *expression, bool may_be_register)
8643 {
8644         if (expression->kind != EXPR_REFERENCE)
8645                 return;
8646
8647         entity_t *const entity = expression->reference.entity;
8648
8649         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8650                 return;
8651
8652         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8653                         && !may_be_register) {
8654                 errorf(&expression->base.source_position,
8655                                 "address of register %s '%Y' requested",
8656                                 get_entity_kind_name(entity->kind),     entity->base.symbol);
8657         }
8658
8659         if (entity->kind == ENTITY_VARIABLE) {
8660                 entity->variable.address_taken = true;
8661         } else {
8662                 assert(entity->kind == ENTITY_PARAMETER);
8663                 entity->parameter.address_taken = true;
8664         }
8665 }
8666
8667 /**
8668  * Check the semantic of the address taken expression.
8669  */
8670 static void semantic_take_addr(unary_expression_t *expression)
8671 {
8672         expression_t *value = expression->value;
8673         value->base.type    = revert_automatic_type_conversion(value);
8674
8675         type_t *orig_type = value->base.type;
8676         type_t *type      = skip_typeref(orig_type);
8677         if (!is_type_valid(type))
8678                 return;
8679
8680         /* §6.5.3.2 */
8681         if (!is_lvalue(value)) {
8682                 errorf(&expression->base.source_position, "'&' requires an lvalue");
8683         }
8684         if (type->kind == TYPE_BITFIELD) {
8685                 errorf(&expression->base.source_position,
8686                        "'&' not allowed on object with bitfield type '%T'",
8687                        type);
8688         }
8689
8690         set_address_taken(value, false);
8691
8692         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8693 }
8694
8695 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8696 static expression_t *parse_##unexpression_type(void)                         \
8697 {                                                                            \
8698         expression_t *unary_expression                                           \
8699                 = allocate_expression_zero(unexpression_type);                       \
8700         eat(token_type);                                                         \
8701         unary_expression->unary.value = parse_sub_expression(PREC_UNARY);        \
8702                                                                                  \
8703         sfunc(&unary_expression->unary);                                         \
8704                                                                                  \
8705         return unary_expression;                                                 \
8706 }
8707
8708 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8709                                semantic_unexpr_arithmetic)
8710 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8711                                semantic_unexpr_plus)
8712 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8713                                semantic_not)
8714 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8715                                semantic_dereference)
8716 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8717                                semantic_take_addr)
8718 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8719                                semantic_unexpr_integer)
8720 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
8721                                semantic_incdec)
8722 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8723                                semantic_incdec)
8724
8725 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8726                                                sfunc)                         \
8727 static expression_t *parse_##unexpression_type(expression_t *left)            \
8728 {                                                                             \
8729         expression_t *unary_expression                                            \
8730                 = allocate_expression_zero(unexpression_type);                        \
8731         eat(token_type);                                                          \
8732         unary_expression->unary.value = left;                                     \
8733                                                                                   \
8734         sfunc(&unary_expression->unary);                                          \
8735                                                                               \
8736         return unary_expression;                                                  \
8737 }
8738
8739 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8740                                        EXPR_UNARY_POSTFIX_INCREMENT,
8741                                        semantic_incdec)
8742 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8743                                        EXPR_UNARY_POSTFIX_DECREMENT,
8744                                        semantic_incdec)
8745
8746 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8747 {
8748         /* TODO: handle complex + imaginary types */
8749
8750         type_left  = get_unqualified_type(type_left);
8751         type_right = get_unqualified_type(type_right);
8752
8753         /* §6.3.1.8 Usual arithmetic conversions */
8754         if (type_left == type_long_double || type_right == type_long_double) {
8755                 return type_long_double;
8756         } else if (type_left == type_double || type_right == type_double) {
8757                 return type_double;
8758         } else if (type_left == type_float || type_right == type_float) {
8759                 return type_float;
8760         }
8761
8762         type_left  = promote_integer(type_left);
8763         type_right = promote_integer(type_right);
8764
8765         if (type_left == type_right)
8766                 return type_left;
8767
8768         bool const signed_left  = is_type_signed(type_left);
8769         bool const signed_right = is_type_signed(type_right);
8770         int const  rank_left    = get_rank(type_left);
8771         int const  rank_right   = get_rank(type_right);
8772
8773         if (signed_left == signed_right)
8774                 return rank_left >= rank_right ? type_left : type_right;
8775
8776         int     s_rank;
8777         int     u_rank;
8778         type_t *s_type;
8779         type_t *u_type;
8780         if (signed_left) {
8781                 s_rank = rank_left;
8782                 s_type = type_left;
8783                 u_rank = rank_right;
8784                 u_type = type_right;
8785         } else {
8786                 s_rank = rank_right;
8787                 s_type = type_right;
8788                 u_rank = rank_left;
8789                 u_type = type_left;
8790         }
8791
8792         if (u_rank >= s_rank)
8793                 return u_type;
8794
8795         /* casting rank to atomic_type_kind is a bit hacky, but makes things
8796          * easier here... */
8797         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8798                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
8799                 return s_type;
8800
8801         switch (s_rank) {
8802                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
8803                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
8804                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8805
8806                 default: panic("invalid atomic type");
8807         }
8808 }
8809
8810 /**
8811  * Check the semantic restrictions for a binary expression.
8812  */
8813 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8814 {
8815         expression_t *const left            = expression->left;
8816         expression_t *const right           = expression->right;
8817         type_t       *const orig_type_left  = left->base.type;
8818         type_t       *const orig_type_right = right->base.type;
8819         type_t       *const type_left       = skip_typeref(orig_type_left);
8820         type_t       *const type_right      = skip_typeref(orig_type_right);
8821
8822         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8823                 /* TODO: improve error message */
8824                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8825                         errorf(&expression->base.source_position,
8826                                "operation needs arithmetic types");
8827                 }
8828                 return;
8829         }
8830
8831         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8832         expression->left      = create_implicit_cast(left, arithmetic_type);
8833         expression->right     = create_implicit_cast(right, arithmetic_type);
8834         expression->base.type = arithmetic_type;
8835 }
8836
8837 static void warn_div_by_zero(binary_expression_t const *const expression)
8838 {
8839         if (!warning.div_by_zero ||
8840             !is_type_integer(expression->base.type))
8841                 return;
8842
8843         expression_t const *const right = expression->right;
8844         /* The type of the right operand can be different for /= */
8845         if (is_type_integer(right->base.type) &&
8846             is_constant_expression(right)     &&
8847             fold_constant(right) == 0) {
8848                 warningf(&expression->base.source_position, "division by zero");
8849         }
8850 }
8851
8852 /**
8853  * Check the semantic restrictions for a div/mod expression.
8854  */
8855 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8856 {
8857         semantic_binexpr_arithmetic(expression);
8858         warn_div_by_zero(expression);
8859 }
8860
8861 static void warn_addsub_in_shift(const expression_t *const expr)
8862 {
8863         if (expr->base.parenthesized)
8864                 return;
8865
8866         char op;
8867         switch (expr->kind) {
8868                 case EXPR_BINARY_ADD: op = '+'; break;
8869                 case EXPR_BINARY_SUB: op = '-'; break;
8870                 default:              return;
8871         }
8872
8873         warningf(&expr->base.source_position,
8874                         "suggest parentheses around '%c' inside shift", op);
8875 }
8876
8877 static void semantic_shift_op(binary_expression_t *expression)
8878 {
8879         expression_t *const left            = expression->left;
8880         expression_t *const right           = expression->right;
8881         type_t       *const orig_type_left  = left->base.type;
8882         type_t       *const orig_type_right = right->base.type;
8883         type_t       *      type_left       = skip_typeref(orig_type_left);
8884         type_t       *      type_right      = skip_typeref(orig_type_right);
8885
8886         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8887                 /* TODO: improve error message */
8888                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8889                         errorf(&expression->base.source_position,
8890                                "operands of shift operation must have integer types");
8891                 }
8892                 return;
8893         }
8894
8895         if (warning.parentheses) {
8896                 warn_addsub_in_shift(left);
8897                 warn_addsub_in_shift(right);
8898         }
8899
8900         type_left  = promote_integer(type_left);
8901         type_right = promote_integer(type_right);
8902
8903         expression->left      = create_implicit_cast(left, type_left);
8904         expression->right     = create_implicit_cast(right, type_right);
8905         expression->base.type = type_left;
8906 }
8907
8908 static void semantic_add(binary_expression_t *expression)
8909 {
8910         expression_t *const left            = expression->left;
8911         expression_t *const right           = expression->right;
8912         type_t       *const orig_type_left  = left->base.type;
8913         type_t       *const orig_type_right = right->base.type;
8914         type_t       *const type_left       = skip_typeref(orig_type_left);
8915         type_t       *const type_right      = skip_typeref(orig_type_right);
8916
8917         /* §6.5.6 */
8918         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8919                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8920                 expression->left  = create_implicit_cast(left, arithmetic_type);
8921                 expression->right = create_implicit_cast(right, arithmetic_type);
8922                 expression->base.type = arithmetic_type;
8923         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8924                 check_pointer_arithmetic(&expression->base.source_position,
8925                                          type_left, orig_type_left);
8926                 expression->base.type = type_left;
8927         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8928                 check_pointer_arithmetic(&expression->base.source_position,
8929                                          type_right, orig_type_right);
8930                 expression->base.type = type_right;
8931         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8932                 errorf(&expression->base.source_position,
8933                        "invalid operands to binary + ('%T', '%T')",
8934                        orig_type_left, orig_type_right);
8935         }
8936 }
8937
8938 static void semantic_sub(binary_expression_t *expression)
8939 {
8940         expression_t            *const left            = expression->left;
8941         expression_t            *const right           = expression->right;
8942         type_t                  *const orig_type_left  = left->base.type;
8943         type_t                  *const orig_type_right = right->base.type;
8944         type_t                  *const type_left       = skip_typeref(orig_type_left);
8945         type_t                  *const type_right      = skip_typeref(orig_type_right);
8946         source_position_t const *const pos             = &expression->base.source_position;
8947
8948         /* §5.6.5 */
8949         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8950                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8951                 expression->left        = create_implicit_cast(left, arithmetic_type);
8952                 expression->right       = create_implicit_cast(right, arithmetic_type);
8953                 expression->base.type =  arithmetic_type;
8954         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8955                 check_pointer_arithmetic(&expression->base.source_position,
8956                                          type_left, orig_type_left);
8957                 expression->base.type = type_left;
8958         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8959                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8960                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8961                 if (!types_compatible(unqual_left, unqual_right)) {
8962                         errorf(pos,
8963                                "subtracting pointers to incompatible types '%T' and '%T'",
8964                                orig_type_left, orig_type_right);
8965                 } else if (!is_type_object(unqual_left)) {
8966                         if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8967                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8968                                        orig_type_left);
8969                         } else if (warning.other) {
8970                                 warningf(pos, "subtracting pointers to void");
8971                         }
8972                 }
8973                 expression->base.type = type_ptrdiff_t;
8974         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8975                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8976                        orig_type_left, orig_type_right);
8977         }
8978 }
8979
8980 static void warn_string_literal_address(expression_t const* expr)
8981 {
8982         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8983                 expr = expr->unary.value;
8984                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8985                         return;
8986                 expr = expr->unary.value;
8987         }
8988
8989         if (expr->kind == EXPR_STRING_LITERAL ||
8990             expr->kind == EXPR_WIDE_STRING_LITERAL) {
8991                 warningf(&expr->base.source_position,
8992                         "comparison with string literal results in unspecified behaviour");
8993         }
8994 }
8995
8996 static void warn_comparison_in_comparison(const expression_t *const expr)
8997 {
8998         if (expr->base.parenthesized)
8999                 return;
9000         switch (expr->base.kind) {
9001                 case EXPR_BINARY_LESS:
9002                 case EXPR_BINARY_GREATER:
9003                 case EXPR_BINARY_LESSEQUAL:
9004                 case EXPR_BINARY_GREATEREQUAL:
9005                 case EXPR_BINARY_NOTEQUAL:
9006                 case EXPR_BINARY_EQUAL:
9007                         warningf(&expr->base.source_position,
9008                                         "comparisons like 'x <= y < z' do not have their mathematical meaning");
9009                         break;
9010                 default:
9011                         break;
9012         }
9013 }
9014
9015 static bool maybe_negative(expression_t const *const expr)
9016 {
9017         return
9018                 !is_constant_expression(expr) ||
9019                 fold_constant(expr) < 0;
9020 }
9021
9022 /**
9023  * Check the semantics of comparison expressions.
9024  *
9025  * @param expression   The expression to check.
9026  */
9027 static void semantic_comparison(binary_expression_t *expression)
9028 {
9029         expression_t *left  = expression->left;
9030         expression_t *right = expression->right;
9031
9032         if (warning.address) {
9033                 warn_string_literal_address(left);
9034                 warn_string_literal_address(right);
9035
9036                 expression_t const* const func_left = get_reference_address(left);
9037                 if (func_left != NULL && is_null_pointer_constant(right)) {
9038                         warningf(&expression->base.source_position,
9039                                  "the address of '%Y' will never be NULL",
9040                                  func_left->reference.entity->base.symbol);
9041                 }
9042
9043                 expression_t const* const func_right = get_reference_address(right);
9044                 if (func_right != NULL && is_null_pointer_constant(right)) {
9045                         warningf(&expression->base.source_position,
9046                                  "the address of '%Y' will never be NULL",
9047                                  func_right->reference.entity->base.symbol);
9048                 }
9049         }
9050
9051         if (warning.parentheses) {
9052                 warn_comparison_in_comparison(left);
9053                 warn_comparison_in_comparison(right);
9054         }
9055
9056         type_t *orig_type_left  = left->base.type;
9057         type_t *orig_type_right = right->base.type;
9058         type_t *type_left       = skip_typeref(orig_type_left);
9059         type_t *type_right      = skip_typeref(orig_type_right);
9060
9061         /* TODO non-arithmetic types */
9062         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9063                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9064
9065                 /* test for signed vs unsigned compares */
9066                 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9067                         bool const signed_left  = is_type_signed(type_left);
9068                         bool const signed_right = is_type_signed(type_right);
9069                         if (signed_left != signed_right) {
9070                                 /* FIXME long long needs better const folding magic */
9071                                 /* TODO check whether constant value can be represented by other type */
9072                                 if ((signed_left  && maybe_negative(left)) ||
9073                                                 (signed_right && maybe_negative(right))) {
9074                                         warningf(&expression->base.source_position,
9075                                                         "comparison between signed and unsigned");
9076                                 }
9077                         }
9078                 }
9079
9080                 expression->left        = create_implicit_cast(left, arithmetic_type);
9081                 expression->right       = create_implicit_cast(right, arithmetic_type);
9082                 expression->base.type   = arithmetic_type;
9083                 if (warning.float_equal &&
9084                     (expression->base.kind == EXPR_BINARY_EQUAL ||
9085                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9086                     is_type_float(arithmetic_type)) {
9087                         warningf(&expression->base.source_position,
9088                                  "comparing floating point with == or != is unsafe");
9089                 }
9090         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9091                 /* TODO check compatibility */
9092         } else if (is_type_pointer(type_left)) {
9093                 expression->right = create_implicit_cast(right, type_left);
9094         } else if (is_type_pointer(type_right)) {
9095                 expression->left = create_implicit_cast(left, type_right);
9096         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9097                 type_error_incompatible("invalid operands in comparison",
9098                                         &expression->base.source_position,
9099                                         type_left, type_right);
9100         }
9101         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9102 }
9103
9104 /**
9105  * Checks if a compound type has constant fields.
9106  */
9107 static bool has_const_fields(const compound_type_t *type)
9108 {
9109         compound_t *compound = type->compound;
9110         entity_t   *entry    = compound->members.entities;
9111
9112         for (; entry != NULL; entry = entry->base.next) {
9113                 if (!is_declaration(entry))
9114                         continue;
9115
9116                 const type_t *decl_type = skip_typeref(entry->declaration.type);
9117                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9118                         return true;
9119         }
9120
9121         return false;
9122 }
9123
9124 static bool is_valid_assignment_lhs(expression_t const* const left)
9125 {
9126         type_t *const orig_type_left = revert_automatic_type_conversion(left);
9127         type_t *const type_left      = skip_typeref(orig_type_left);
9128
9129         if (!is_lvalue(left)) {
9130                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9131                        left);
9132                 return false;
9133         }
9134
9135         if (left->kind == EXPR_REFERENCE
9136                         && left->reference.entity->kind == ENTITY_FUNCTION) {
9137                 errorf(HERE, "cannot assign to function '%E'", left);
9138                 return false;
9139         }
9140
9141         if (is_type_array(type_left)) {
9142                 errorf(HERE, "cannot assign to array '%E'", left);
9143                 return false;
9144         }
9145         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9146                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9147                        orig_type_left);
9148                 return false;
9149         }
9150         if (is_type_incomplete(type_left)) {
9151                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9152                        left, orig_type_left);
9153                 return false;
9154         }
9155         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9156                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9157                        left, orig_type_left);
9158                 return false;
9159         }
9160
9161         return true;
9162 }
9163
9164 static void semantic_arithmetic_assign(binary_expression_t *expression)
9165 {
9166         expression_t *left            = expression->left;
9167         expression_t *right           = expression->right;
9168         type_t       *orig_type_left  = left->base.type;
9169         type_t       *orig_type_right = right->base.type;
9170
9171         if (!is_valid_assignment_lhs(left))
9172                 return;
9173
9174         type_t *type_left  = skip_typeref(orig_type_left);
9175         type_t *type_right = skip_typeref(orig_type_right);
9176
9177         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9178                 /* TODO: improve error message */
9179                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9180                         errorf(&expression->base.source_position,
9181                                "operation needs arithmetic types");
9182                 }
9183                 return;
9184         }
9185
9186         /* combined instructions are tricky. We can't create an implicit cast on
9187          * the left side, because we need the uncasted form for the store.
9188          * The ast2firm pass has to know that left_type must be right_type
9189          * for the arithmetic operation and create a cast by itself */
9190         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9191         expression->right       = create_implicit_cast(right, arithmetic_type);
9192         expression->base.type   = type_left;
9193 }
9194
9195 static void semantic_divmod_assign(binary_expression_t *expression)
9196 {
9197         semantic_arithmetic_assign(expression);
9198         warn_div_by_zero(expression);
9199 }
9200
9201 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9202 {
9203         expression_t *const left            = expression->left;
9204         expression_t *const right           = expression->right;
9205         type_t       *const orig_type_left  = left->base.type;
9206         type_t       *const orig_type_right = right->base.type;
9207         type_t       *const type_left       = skip_typeref(orig_type_left);
9208         type_t       *const type_right      = skip_typeref(orig_type_right);
9209
9210         if (!is_valid_assignment_lhs(left))
9211                 return;
9212
9213         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9214                 /* combined instructions are tricky. We can't create an implicit cast on
9215                  * the left side, because we need the uncasted form for the store.
9216                  * The ast2firm pass has to know that left_type must be right_type
9217                  * for the arithmetic operation and create a cast by itself */
9218                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9219                 expression->right     = create_implicit_cast(right, arithmetic_type);
9220                 expression->base.type = type_left;
9221         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9222                 check_pointer_arithmetic(&expression->base.source_position,
9223                                          type_left, orig_type_left);
9224                 expression->base.type = type_left;
9225         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9226                 errorf(&expression->base.source_position,
9227                        "incompatible types '%T' and '%T' in assignment",
9228                        orig_type_left, orig_type_right);
9229         }
9230 }
9231
9232 static void warn_logical_and_within_or(const expression_t *const expr)
9233 {
9234         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9235                 return;
9236         if (expr->base.parenthesized)
9237                 return;
9238         warningf(&expr->base.source_position,
9239                         "suggest parentheses around && within ||");
9240 }
9241
9242 /**
9243  * Check the semantic restrictions of a logical expression.
9244  */
9245 static void semantic_logical_op(binary_expression_t *expression)
9246 {
9247         /* §6.5.13:2  Each of the operands shall have scalar type.
9248          * §6.5.14:2  Each of the operands shall have scalar type. */
9249         semantic_condition(expression->left,   "left operand of logical operator");
9250         semantic_condition(expression->right, "right operand of logical operator");
9251         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9252                         warning.parentheses) {
9253                 warn_logical_and_within_or(expression->left);
9254                 warn_logical_and_within_or(expression->right);
9255         }
9256         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9257 }
9258
9259 /**
9260  * Check the semantic restrictions of a binary assign expression.
9261  */
9262 static void semantic_binexpr_assign(binary_expression_t *expression)
9263 {
9264         expression_t *left           = expression->left;
9265         type_t       *orig_type_left = left->base.type;
9266
9267         if (!is_valid_assignment_lhs(left))
9268                 return;
9269
9270         assign_error_t error = semantic_assign(orig_type_left, expression->right);
9271         report_assign_error(error, orig_type_left, expression->right,
9272                         "assignment", &left->base.source_position);
9273         expression->right = create_implicit_cast(expression->right, orig_type_left);
9274         expression->base.type = orig_type_left;
9275 }
9276
9277 /**
9278  * Determine if the outermost operation (or parts thereof) of the given
9279  * expression has no effect in order to generate a warning about this fact.
9280  * Therefore in some cases this only examines some of the operands of the
9281  * expression (see comments in the function and examples below).
9282  * Examples:
9283  *   f() + 23;    // warning, because + has no effect
9284  *   x || f();    // no warning, because x controls execution of f()
9285  *   x ? y : f(); // warning, because y has no effect
9286  *   (void)x;     // no warning to be able to suppress the warning
9287  * This function can NOT be used for an "expression has definitely no effect"-
9288  * analysis. */
9289 static bool expression_has_effect(const expression_t *const expr)
9290 {
9291         switch (expr->kind) {
9292                 case EXPR_UNKNOWN:                    break;
9293                 case EXPR_INVALID:                    return true; /* do NOT warn */
9294                 case EXPR_REFERENCE:                  return false;
9295                 case EXPR_REFERENCE_ENUM_VALUE:       return false;
9296                 /* suppress the warning for microsoft __noop operations */
9297                 case EXPR_CONST:                      return expr->conste.is_ms_noop;
9298                 case EXPR_CHARACTER_CONSTANT:         return false;
9299                 case EXPR_WIDE_CHARACTER_CONSTANT:    return false;
9300                 case EXPR_STRING_LITERAL:             return false;
9301                 case EXPR_WIDE_STRING_LITERAL:        return false;
9302                 case EXPR_LABEL_ADDRESS:              return false;
9303
9304                 case EXPR_CALL: {
9305                         const call_expression_t *const call = &expr->call;
9306                         if (call->function->kind != EXPR_REFERENCE)
9307                                 return true;
9308
9309                         switch (call->function->reference.entity->function.btk) {
9310                                 /* FIXME: which builtins have no effect? */
9311                                 default:                      return true;
9312                         }
9313                 }
9314
9315                 /* Generate the warning if either the left or right hand side of a
9316                  * conditional expression has no effect */
9317                 case EXPR_CONDITIONAL: {
9318                         conditional_expression_t const *const cond = &expr->conditional;
9319                         expression_t             const *const t    = cond->true_expression;
9320                         return
9321                                 (t == NULL || expression_has_effect(t)) &&
9322                                 expression_has_effect(cond->false_expression);
9323                 }
9324
9325                 case EXPR_SELECT:                     return false;
9326                 case EXPR_ARRAY_ACCESS:               return false;
9327                 case EXPR_SIZEOF:                     return false;
9328                 case EXPR_CLASSIFY_TYPE:              return false;
9329                 case EXPR_ALIGNOF:                    return false;
9330
9331                 case EXPR_FUNCNAME:                   return false;
9332                 case EXPR_BUILTIN_CONSTANT_P:         return false;
9333                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
9334                 case EXPR_OFFSETOF:                   return false;
9335                 case EXPR_VA_START:                   return true;
9336                 case EXPR_VA_ARG:                     return true;
9337                 case EXPR_STATEMENT:                  return true; // TODO
9338                 case EXPR_COMPOUND_LITERAL:           return false;
9339
9340                 case EXPR_UNARY_NEGATE:               return false;
9341                 case EXPR_UNARY_PLUS:                 return false;
9342                 case EXPR_UNARY_BITWISE_NEGATE:       return false;
9343                 case EXPR_UNARY_NOT:                  return false;
9344                 case EXPR_UNARY_DEREFERENCE:          return false;
9345                 case EXPR_UNARY_TAKE_ADDRESS:         return false;
9346                 case EXPR_UNARY_POSTFIX_INCREMENT:    return true;
9347                 case EXPR_UNARY_POSTFIX_DECREMENT:    return true;
9348                 case EXPR_UNARY_PREFIX_INCREMENT:     return true;
9349                 case EXPR_UNARY_PREFIX_DECREMENT:     return true;
9350
9351                 /* Treat void casts as if they have an effect in order to being able to
9352                  * suppress the warning */
9353                 case EXPR_UNARY_CAST: {
9354                         type_t *const type = skip_typeref(expr->base.type);
9355                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
9356                 }
9357
9358                 case EXPR_UNARY_CAST_IMPLICIT:        return true;
9359                 case EXPR_UNARY_ASSUME:               return true;
9360                 case EXPR_UNARY_DELETE:               return true;
9361                 case EXPR_UNARY_DELETE_ARRAY:         return true;
9362                 case EXPR_UNARY_THROW:                return true;
9363
9364                 case EXPR_BINARY_ADD:                 return false;
9365                 case EXPR_BINARY_SUB:                 return false;
9366                 case EXPR_BINARY_MUL:                 return false;
9367                 case EXPR_BINARY_DIV:                 return false;
9368                 case EXPR_BINARY_MOD:                 return false;
9369                 case EXPR_BINARY_EQUAL:               return false;
9370                 case EXPR_BINARY_NOTEQUAL:            return false;
9371                 case EXPR_BINARY_LESS:                return false;
9372                 case EXPR_BINARY_LESSEQUAL:           return false;
9373                 case EXPR_BINARY_GREATER:             return false;
9374                 case EXPR_BINARY_GREATEREQUAL:        return false;
9375                 case EXPR_BINARY_BITWISE_AND:         return false;
9376                 case EXPR_BINARY_BITWISE_OR:          return false;
9377                 case EXPR_BINARY_BITWISE_XOR:         return false;
9378                 case EXPR_BINARY_SHIFTLEFT:           return false;
9379                 case EXPR_BINARY_SHIFTRIGHT:          return false;
9380                 case EXPR_BINARY_ASSIGN:              return true;
9381                 case EXPR_BINARY_MUL_ASSIGN:          return true;
9382                 case EXPR_BINARY_DIV_ASSIGN:          return true;
9383                 case EXPR_BINARY_MOD_ASSIGN:          return true;
9384                 case EXPR_BINARY_ADD_ASSIGN:          return true;
9385                 case EXPR_BINARY_SUB_ASSIGN:          return true;
9386                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:    return true;
9387                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:   return true;
9388                 case EXPR_BINARY_BITWISE_AND_ASSIGN:  return true;
9389                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:  return true;
9390                 case EXPR_BINARY_BITWISE_OR_ASSIGN:   return true;
9391
9392                 /* Only examine the right hand side of && and ||, because the left hand
9393                  * side already has the effect of controlling the execution of the right
9394                  * hand side */
9395                 case EXPR_BINARY_LOGICAL_AND:
9396                 case EXPR_BINARY_LOGICAL_OR:
9397                 /* Only examine the right hand side of a comma expression, because the left
9398                  * hand side has a separate warning */
9399                 case EXPR_BINARY_COMMA:
9400                         return expression_has_effect(expr->binary.right);
9401
9402                 case EXPR_BINARY_ISGREATER:           return false;
9403                 case EXPR_BINARY_ISGREATEREQUAL:      return false;
9404                 case EXPR_BINARY_ISLESS:              return false;
9405                 case EXPR_BINARY_ISLESSEQUAL:         return false;
9406                 case EXPR_BINARY_ISLESSGREATER:       return false;
9407                 case EXPR_BINARY_ISUNORDERED:         return false;
9408         }
9409
9410         internal_errorf(HERE, "unexpected expression");
9411 }
9412
9413 static void semantic_comma(binary_expression_t *expression)
9414 {
9415         if (warning.unused_value) {
9416                 const expression_t *const left = expression->left;
9417                 if (!expression_has_effect(left)) {
9418                         warningf(&left->base.source_position,
9419                                  "left-hand operand of comma expression has no effect");
9420                 }
9421         }
9422         expression->base.type = expression->right->base.type;
9423 }
9424
9425 /**
9426  * @param prec_r precedence of the right operand
9427  */
9428 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9429 static expression_t *parse_##binexpression_type(expression_t *left)          \
9430 {                                                                            \
9431         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
9432         binexpr->binary.left  = left;                                            \
9433         eat(token_type);                                                         \
9434                                                                              \
9435         expression_t *right = parse_sub_expression(prec_r);                      \
9436                                                                              \
9437         binexpr->binary.right = right;                                           \
9438         sfunc(&binexpr->binary);                                                 \
9439                                                                              \
9440         return binexpr;                                                          \
9441 }
9442
9443 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
9444 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
9445 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
9446 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
9447 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
9448 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
9449 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
9450 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
9451 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
9452 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
9453 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
9454 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
9455 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
9456 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_arithmetic)
9457 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_arithmetic)
9458 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_arithmetic)
9459 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
9460 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
9461 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
9462 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9463 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9464 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9465 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9466 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9467 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9468 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9469 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9470 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9471 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9472 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
9473
9474
9475 static expression_t *parse_sub_expression(precedence_t precedence)
9476 {
9477         if (token.type < 0) {
9478                 return expected_expression_error();
9479         }
9480
9481         expression_parser_function_t *parser
9482                 = &expression_parsers[token.type];
9483         source_position_t             source_position = token.source_position;
9484         expression_t                 *left;
9485
9486         if (parser->parser != NULL) {
9487                 left = parser->parser();
9488         } else {
9489                 left = parse_primary_expression();
9490         }
9491         assert(left != NULL);
9492         left->base.source_position = source_position;
9493
9494         while (true) {
9495                 if (token.type < 0) {
9496                         return expected_expression_error();
9497                 }
9498
9499                 parser = &expression_parsers[token.type];
9500                 if (parser->infix_parser == NULL)
9501                         break;
9502                 if (parser->infix_precedence < precedence)
9503                         break;
9504
9505                 left = parser->infix_parser(left);
9506
9507                 assert(left != NULL);
9508                 assert(left->kind != EXPR_UNKNOWN);
9509                 left->base.source_position = source_position;
9510         }
9511
9512         return left;
9513 }
9514
9515 /**
9516  * Parse an expression.
9517  */
9518 static expression_t *parse_expression(void)
9519 {
9520         return parse_sub_expression(PREC_EXPRESSION);
9521 }
9522
9523 /**
9524  * Register a parser for a prefix-like operator.
9525  *
9526  * @param parser      the parser function
9527  * @param token_type  the token type of the prefix token
9528  */
9529 static void register_expression_parser(parse_expression_function parser,
9530                                        int token_type)
9531 {
9532         expression_parser_function_t *entry = &expression_parsers[token_type];
9533
9534         if (entry->parser != NULL) {
9535                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9536                 panic("trying to register multiple expression parsers for a token");
9537         }
9538         entry->parser = parser;
9539 }
9540
9541 /**
9542  * Register a parser for an infix operator with given precedence.
9543  *
9544  * @param parser      the parser function
9545  * @param token_type  the token type of the infix operator
9546  * @param precedence  the precedence of the operator
9547  */
9548 static void register_infix_parser(parse_expression_infix_function parser,
9549                 int token_type, precedence_t precedence)
9550 {
9551         expression_parser_function_t *entry = &expression_parsers[token_type];
9552
9553         if (entry->infix_parser != NULL) {
9554                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9555                 panic("trying to register multiple infix expression parsers for a "
9556                       "token");
9557         }
9558         entry->infix_parser     = parser;
9559         entry->infix_precedence = precedence;
9560 }
9561
9562 /**
9563  * Initialize the expression parsers.
9564  */
9565 static void init_expression_parsers(void)
9566 {
9567         memset(&expression_parsers, 0, sizeof(expression_parsers));
9568
9569         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
9570         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
9571         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
9572         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
9573         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
9574         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
9575         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
9576         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
9577         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
9578         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
9579         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
9580         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
9581         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
9582         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
9583         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
9584         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
9585         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
9586         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
9587         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9588         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
9589         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
9590         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
9591         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
9592         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
9593         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
9594         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
9595         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
9596         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
9597         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
9598         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
9599         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
9600         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
9601         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
9602         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
9603         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
9604         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
9605         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
9606
9607         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
9608         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
9609         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
9610         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
9611         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
9612         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
9613         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9614         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9615         register_expression_parser(parse_sizeof,                      T_sizeof);
9616         register_expression_parser(parse_alignof,                     T___alignof__);
9617         register_expression_parser(parse_extension,                   T___extension__);
9618         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
9619         register_expression_parser(parse_delete,                      T_delete);
9620         register_expression_parser(parse_throw,                       T_throw);
9621 }
9622
9623 /**
9624  * Parse a asm statement arguments specification.
9625  */
9626 static asm_argument_t *parse_asm_arguments(bool is_out)
9627 {
9628         asm_argument_t  *result = NULL;
9629         asm_argument_t **anchor = &result;
9630
9631         while (token.type == T_STRING_LITERAL || token.type == '[') {
9632                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9633                 memset(argument, 0, sizeof(argument[0]));
9634
9635                 if (token.type == '[') {
9636                         eat('[');
9637                         if (token.type != T_IDENTIFIER) {
9638                                 parse_error_expected("while parsing asm argument",
9639                                                      T_IDENTIFIER, NULL);
9640                                 return NULL;
9641                         }
9642                         argument->symbol = token.v.symbol;
9643
9644                         expect(']', end_error);
9645                 }
9646
9647                 argument->constraints = parse_string_literals();
9648                 expect('(', end_error);
9649                 add_anchor_token(')');
9650                 expression_t *expression = parse_expression();
9651                 rem_anchor_token(')');
9652                 if (is_out) {
9653                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
9654                          * change size or type representation (e.g. int -> long is ok, but
9655                          * int -> float is not) */
9656                         if (expression->kind == EXPR_UNARY_CAST) {
9657                                 type_t      *const type = expression->base.type;
9658                                 type_kind_t  const kind = type->kind;
9659                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9660                                         unsigned flags;
9661                                         unsigned size;
9662                                         if (kind == TYPE_ATOMIC) {
9663                                                 atomic_type_kind_t const akind = type->atomic.akind;
9664                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9665                                                 size  = get_atomic_type_size(akind);
9666                                         } else {
9667                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9668                                                 size  = get_atomic_type_size(get_intptr_kind());
9669                                         }
9670
9671                                         do {
9672                                                 expression_t *const value      = expression->unary.value;
9673                                                 type_t       *const value_type = value->base.type;
9674                                                 type_kind_t   const value_kind = value_type->kind;
9675
9676                                                 unsigned value_flags;
9677                                                 unsigned value_size;
9678                                                 if (value_kind == TYPE_ATOMIC) {
9679                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
9680                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9681                                                         value_size  = get_atomic_type_size(value_akind);
9682                                                 } else if (value_kind == TYPE_POINTER) {
9683                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9684                                                         value_size  = get_atomic_type_size(get_intptr_kind());
9685                                                 } else {
9686                                                         break;
9687                                                 }
9688
9689                                                 if (value_flags != flags || value_size != size)
9690                                                         break;
9691
9692                                                 expression = value;
9693                                         } while (expression->kind == EXPR_UNARY_CAST);
9694                                 }
9695                         }
9696
9697                         if (!is_lvalue(expression)) {
9698                                 errorf(&expression->base.source_position,
9699                                        "asm output argument is not an lvalue");
9700                         }
9701
9702                         if (argument->constraints.begin[0] == '+')
9703                                 mark_vars_read(expression, NULL);
9704                 } else {
9705                         mark_vars_read(expression, NULL);
9706                 }
9707                 argument->expression = expression;
9708                 expect(')', end_error);
9709
9710                 set_address_taken(expression, true);
9711
9712                 *anchor = argument;
9713                 anchor  = &argument->next;
9714
9715                 if (token.type != ',')
9716                         break;
9717                 eat(',');
9718         }
9719
9720         return result;
9721 end_error:
9722         return NULL;
9723 }
9724
9725 /**
9726  * Parse a asm statement clobber specification.
9727  */
9728 static asm_clobber_t *parse_asm_clobbers(void)
9729 {
9730         asm_clobber_t *result = NULL;
9731         asm_clobber_t *last   = NULL;
9732
9733         while (token.type == T_STRING_LITERAL) {
9734                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9735                 clobber->clobber       = parse_string_literals();
9736
9737                 if (last != NULL) {
9738                         last->next = clobber;
9739                 } else {
9740                         result = clobber;
9741                 }
9742                 last = clobber;
9743
9744                 if (token.type != ',')
9745                         break;
9746                 eat(',');
9747         }
9748
9749         return result;
9750 }
9751
9752 /**
9753  * Parse an asm statement.
9754  */
9755 static statement_t *parse_asm_statement(void)
9756 {
9757         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
9758         asm_statement_t *asm_statement = &statement->asms;
9759
9760         eat(T_asm);
9761
9762         if (token.type == T_volatile) {
9763                 next_token();
9764                 asm_statement->is_volatile = true;
9765         }
9766
9767         expect('(', end_error);
9768         add_anchor_token(')');
9769         add_anchor_token(':');
9770         asm_statement->asm_text = parse_string_literals();
9771
9772         if (token.type != ':') {
9773                 rem_anchor_token(':');
9774                 goto end_of_asm;
9775         }
9776         eat(':');
9777
9778         asm_statement->outputs = parse_asm_arguments(true);
9779         if (token.type != ':') {
9780                 rem_anchor_token(':');
9781                 goto end_of_asm;
9782         }
9783         eat(':');
9784
9785         asm_statement->inputs = parse_asm_arguments(false);
9786         if (token.type != ':') {
9787                 rem_anchor_token(':');
9788                 goto end_of_asm;
9789         }
9790         rem_anchor_token(':');
9791         eat(':');
9792
9793         asm_statement->clobbers = parse_asm_clobbers();
9794
9795 end_of_asm:
9796         rem_anchor_token(')');
9797         expect(')', end_error);
9798         expect(';', end_error);
9799
9800         if (asm_statement->outputs == NULL) {
9801                 /* GCC: An 'asm' instruction without any output operands will be treated
9802                  * identically to a volatile 'asm' instruction. */
9803                 asm_statement->is_volatile = true;
9804         }
9805
9806         return statement;
9807 end_error:
9808         return create_invalid_statement();
9809 }
9810
9811 /**
9812  * Parse a case statement.
9813  */
9814 static statement_t *parse_case_statement(void)
9815 {
9816         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9817         source_position_t *const pos       = &statement->base.source_position;
9818
9819         eat(T_case);
9820
9821         expression_t *const expression   = parse_expression();
9822         statement->case_label.expression = expression;
9823         if (!is_constant_expression(expression)) {
9824                 /* This check does not prevent the error message in all cases of an
9825                  * prior error while parsing the expression.  At least it catches the
9826                  * common case of a mistyped enum entry. */
9827                 if (is_type_valid(skip_typeref(expression->base.type))) {
9828                         errorf(pos, "case label does not reduce to an integer constant");
9829                 }
9830                 statement->case_label.is_bad = true;
9831         } else {
9832                 long const val = fold_constant(expression);
9833                 statement->case_label.first_case = val;
9834                 statement->case_label.last_case  = val;
9835         }
9836
9837         if (GNU_MODE) {
9838                 if (token.type == T_DOTDOTDOT) {
9839                         next_token();
9840                         expression_t *const end_range   = parse_expression();
9841                         statement->case_label.end_range = end_range;
9842                         if (!is_constant_expression(end_range)) {
9843                                 /* This check does not prevent the error message in all cases of an
9844                                  * prior error while parsing the expression.  At least it catches the
9845                                  * common case of a mistyped enum entry. */
9846                                 if (is_type_valid(skip_typeref(end_range->base.type))) {
9847                                         errorf(pos, "case range does not reduce to an integer constant");
9848                                 }
9849                                 statement->case_label.is_bad = true;
9850                         } else {
9851                                 long const val = fold_constant(end_range);
9852                                 statement->case_label.last_case = val;
9853
9854                                 if (warning.other && val < statement->case_label.first_case) {
9855                                         statement->case_label.is_empty_range = true;
9856                                         warningf(pos, "empty range specified");
9857                                 }
9858                         }
9859                 }
9860         }
9861
9862         PUSH_PARENT(statement);
9863
9864         expect(':', end_error);
9865 end_error:
9866
9867         if (current_switch != NULL) {
9868                 if (! statement->case_label.is_bad) {
9869                         /* Check for duplicate case values */
9870                         case_label_statement_t *c = &statement->case_label;
9871                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9872                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9873                                         continue;
9874
9875                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9876                                         continue;
9877
9878                                 errorf(pos, "duplicate case value (previously used %P)",
9879                                        &l->base.source_position);
9880                                 break;
9881                         }
9882                 }
9883                 /* link all cases into the switch statement */
9884                 if (current_switch->last_case == NULL) {
9885                         current_switch->first_case      = &statement->case_label;
9886                 } else {
9887                         current_switch->last_case->next = &statement->case_label;
9888                 }
9889                 current_switch->last_case = &statement->case_label;
9890         } else {
9891                 errorf(pos, "case label not within a switch statement");
9892         }
9893
9894         statement_t *const inner_stmt = parse_statement();
9895         statement->case_label.statement = inner_stmt;
9896         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9897                 errorf(&inner_stmt->base.source_position, "declaration after case label");
9898         }
9899
9900         POP_PARENT;
9901         return statement;
9902 }
9903
9904 /**
9905  * Parse a default statement.
9906  */
9907 static statement_t *parse_default_statement(void)
9908 {
9909         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9910
9911         eat(T_default);
9912
9913         PUSH_PARENT(statement);
9914
9915         expect(':', end_error);
9916         if (current_switch != NULL) {
9917                 const case_label_statement_t *def_label = current_switch->default_label;
9918                 if (def_label != NULL) {
9919                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9920                                &def_label->base.source_position);
9921                 } else {
9922                         current_switch->default_label = &statement->case_label;
9923
9924                         /* link all cases into the switch statement */
9925                         if (current_switch->last_case == NULL) {
9926                                 current_switch->first_case      = &statement->case_label;
9927                         } else {
9928                                 current_switch->last_case->next = &statement->case_label;
9929                         }
9930                         current_switch->last_case = &statement->case_label;
9931                 }
9932         } else {
9933                 errorf(&statement->base.source_position,
9934                         "'default' label not within a switch statement");
9935         }
9936
9937         statement_t *const inner_stmt = parse_statement();
9938         statement->case_label.statement = inner_stmt;
9939         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9940                 errorf(&inner_stmt->base.source_position, "declaration after default label");
9941         }
9942
9943         POP_PARENT;
9944         return statement;
9945 end_error:
9946         POP_PARENT;
9947         return create_invalid_statement();
9948 }
9949
9950 /**
9951  * Parse a label statement.
9952  */
9953 static statement_t *parse_label_statement(void)
9954 {
9955         assert(token.type == T_IDENTIFIER);
9956         symbol_t *symbol = token.v.symbol;
9957         label_t  *label  = get_label(symbol);
9958
9959         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9960         statement->label.label       = label;
9961
9962         next_token();
9963
9964         PUSH_PARENT(statement);
9965
9966         /* if statement is already set then the label is defined twice,
9967          * otherwise it was just mentioned in a goto/local label declaration so far
9968          */
9969         if (label->statement != NULL) {
9970                 errorf(HERE, "duplicate label '%Y' (declared %P)",
9971                        symbol, &label->base.source_position);
9972         } else {
9973                 label->base.source_position = token.source_position;
9974                 label->statement            = statement;
9975         }
9976
9977         eat(':');
9978
9979         if (token.type == '}') {
9980                 /* TODO only warn? */
9981                 if (warning.other && false) {
9982                         warningf(HERE, "label at end of compound statement");
9983                         statement->label.statement = create_empty_statement();
9984                 } else {
9985                         errorf(HERE, "label at end of compound statement");
9986                         statement->label.statement = create_invalid_statement();
9987                 }
9988         } else if (token.type == ';') {
9989                 /* Eat an empty statement here, to avoid the warning about an empty
9990                  * statement after a label.  label:; is commonly used to have a label
9991                  * before a closing brace. */
9992                 statement->label.statement = create_empty_statement();
9993                 next_token();
9994         } else {
9995                 statement_t *const inner_stmt = parse_statement();
9996                 statement->label.statement = inner_stmt;
9997                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9998                         errorf(&inner_stmt->base.source_position, "declaration after label");
9999                 }
10000         }
10001
10002         /* remember the labels in a list for later checking */
10003         *label_anchor = &statement->label;
10004         label_anchor  = &statement->label.next;
10005
10006         POP_PARENT;
10007         return statement;
10008 }
10009
10010 /**
10011  * Parse an if statement.
10012  */
10013 static statement_t *parse_if(void)
10014 {
10015         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10016
10017         eat(T_if);
10018
10019         PUSH_PARENT(statement);
10020
10021         add_anchor_token('{');
10022
10023         expect('(', end_error);
10024         add_anchor_token(')');
10025         expression_t *const expr = parse_expression();
10026         statement->ifs.condition = expr;
10027         /* §6.8.4.1:1  The controlling expression of an if statement shall have
10028          *             scalar type. */
10029         semantic_condition(expr, "condition of 'if'-statment");
10030         mark_vars_read(expr, NULL);
10031         rem_anchor_token(')');
10032         expect(')', end_error);
10033
10034 end_error:
10035         rem_anchor_token('{');
10036
10037         add_anchor_token(T_else);
10038         statement_t *const true_stmt = parse_statement();
10039         statement->ifs.true_statement = true_stmt;
10040         rem_anchor_token(T_else);
10041
10042         if (token.type == T_else) {
10043                 next_token();
10044                 statement->ifs.false_statement = parse_statement();
10045         } else if (warning.parentheses &&
10046                         true_stmt->kind == STATEMENT_IF &&
10047                         true_stmt->ifs.false_statement != NULL) {
10048                 warningf(&true_stmt->base.source_position,
10049                                 "suggest explicit braces to avoid ambiguous 'else'");
10050         }
10051
10052         POP_PARENT;
10053         return statement;
10054 }
10055
10056 /**
10057  * Check that all enums are handled in a switch.
10058  *
10059  * @param statement  the switch statement to check
10060  */
10061 static void check_enum_cases(const switch_statement_t *statement)
10062 {
10063         const type_t *type = skip_typeref(statement->expression->base.type);
10064         if (! is_type_enum(type))
10065                 return;
10066         const enum_type_t *enumt = &type->enumt;
10067
10068         /* if we have a default, no warnings */
10069         if (statement->default_label != NULL)
10070                 return;
10071
10072         /* FIXME: calculation of value should be done while parsing */
10073         /* TODO: quadratic algorithm here. Change to an n log n one */
10074         long            last_value = -1;
10075         const entity_t *entry      = enumt->enume->base.next;
10076         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10077              entry = entry->base.next) {
10078                 const expression_t *expression = entry->enum_value.value;
10079                 long                value      = expression != NULL ? fold_constant(expression) : last_value + 1;
10080                 bool                found      = false;
10081                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10082                         if (l->expression == NULL)
10083                                 continue;
10084                         if (l->first_case <= value && value <= l->last_case) {
10085                                 found = true;
10086                                 break;
10087                         }
10088                 }
10089                 if (! found) {
10090                         warningf(&statement->base.source_position,
10091                                  "enumeration value '%Y' not handled in switch",
10092                                  entry->base.symbol);
10093                 }
10094                 last_value = value;
10095         }
10096 }
10097
10098 /**
10099  * Parse a switch statement.
10100  */
10101 static statement_t *parse_switch(void)
10102 {
10103         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10104
10105         eat(T_switch);
10106
10107         PUSH_PARENT(statement);
10108
10109         expect('(', end_error);
10110         add_anchor_token(')');
10111         expression_t *const expr = parse_expression();
10112         mark_vars_read(expr, NULL);
10113         type_t       *      type = skip_typeref(expr->base.type);
10114         if (is_type_integer(type)) {
10115                 type = promote_integer(type);
10116                 if (warning.traditional) {
10117                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10118                                 warningf(&expr->base.source_position,
10119                                         "'%T' switch expression not converted to '%T' in ISO C",
10120                                         type, type_int);
10121                         }
10122                 }
10123         } else if (is_type_valid(type)) {
10124                 errorf(&expr->base.source_position,
10125                        "switch quantity is not an integer, but '%T'", type);
10126                 type = type_error_type;
10127         }
10128         statement->switchs.expression = create_implicit_cast(expr, type);
10129         expect(')', end_error);
10130         rem_anchor_token(')');
10131
10132         switch_statement_t *rem = current_switch;
10133         current_switch          = &statement->switchs;
10134         statement->switchs.body = parse_statement();
10135         current_switch          = rem;
10136
10137         if (warning.switch_default &&
10138             statement->switchs.default_label == NULL) {
10139                 warningf(&statement->base.source_position, "switch has no default case");
10140         }
10141         if (warning.switch_enum)
10142                 check_enum_cases(&statement->switchs);
10143
10144         POP_PARENT;
10145         return statement;
10146 end_error:
10147         POP_PARENT;
10148         return create_invalid_statement();
10149 }
10150
10151 static statement_t *parse_loop_body(statement_t *const loop)
10152 {
10153         statement_t *const rem = current_loop;
10154         current_loop = loop;
10155
10156         statement_t *const body = parse_statement();
10157
10158         current_loop = rem;
10159         return body;
10160 }
10161
10162 /**
10163  * Parse a while statement.
10164  */
10165 static statement_t *parse_while(void)
10166 {
10167         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10168
10169         eat(T_while);
10170
10171         PUSH_PARENT(statement);
10172
10173         expect('(', end_error);
10174         add_anchor_token(')');
10175         expression_t *const cond = parse_expression();
10176         statement->whiles.condition = cond;
10177         /* §6.8.5:2    The controlling expression of an iteration statement shall
10178          *             have scalar type. */
10179         semantic_condition(cond, "condition of 'while'-statement");
10180         mark_vars_read(cond, NULL);
10181         rem_anchor_token(')');
10182         expect(')', end_error);
10183
10184         statement->whiles.body = parse_loop_body(statement);
10185
10186         POP_PARENT;
10187         return statement;
10188 end_error:
10189         POP_PARENT;
10190         return create_invalid_statement();
10191 }
10192
10193 /**
10194  * Parse a do statement.
10195  */
10196 static statement_t *parse_do(void)
10197 {
10198         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10199
10200         eat(T_do);
10201
10202         PUSH_PARENT(statement);
10203
10204         add_anchor_token(T_while);
10205         statement->do_while.body = parse_loop_body(statement);
10206         rem_anchor_token(T_while);
10207
10208         expect(T_while, end_error);
10209         expect('(', end_error);
10210         add_anchor_token(')');
10211         expression_t *const cond = parse_expression();
10212         statement->do_while.condition = cond;
10213         /* §6.8.5:2    The controlling expression of an iteration statement shall
10214          *             have scalar type. */
10215         semantic_condition(cond, "condition of 'do-while'-statement");
10216         mark_vars_read(cond, NULL);
10217         rem_anchor_token(')');
10218         expect(')', end_error);
10219         expect(';', end_error);
10220
10221         POP_PARENT;
10222         return statement;
10223 end_error:
10224         POP_PARENT;
10225         return create_invalid_statement();
10226 }
10227
10228 /**
10229  * Parse a for statement.
10230  */
10231 static statement_t *parse_for(void)
10232 {
10233         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10234
10235         eat(T_for);
10236
10237         expect('(', end_error1);
10238         add_anchor_token(')');
10239
10240         PUSH_PARENT(statement);
10241
10242         size_t const  top       = environment_top();
10243         scope_t      *old_scope = scope_push(&statement->fors.scope);
10244
10245         if (token.type == ';') {
10246                 next_token();
10247         } else if (is_declaration_specifier(&token, false)) {
10248                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10249         } else {
10250                 add_anchor_token(';');
10251                 expression_t *const init = parse_expression();
10252                 statement->fors.initialisation = init;
10253                 mark_vars_read(init, ENT_ANY);
10254                 if (warning.unused_value && !expression_has_effect(init)) {
10255                         warningf(&init->base.source_position,
10256                                         "initialisation of 'for'-statement has no effect");
10257                 }
10258                 rem_anchor_token(';');
10259                 expect(';', end_error2);
10260         }
10261
10262         if (token.type != ';') {
10263                 add_anchor_token(';');
10264                 expression_t *const cond = parse_expression();
10265                 statement->fors.condition = cond;
10266                 /* §6.8.5:2    The controlling expression of an iteration statement
10267                  *             shall have scalar type. */
10268                 semantic_condition(cond, "condition of 'for'-statement");
10269                 mark_vars_read(cond, NULL);
10270                 rem_anchor_token(';');
10271         }
10272         expect(';', end_error2);
10273         if (token.type != ')') {
10274                 expression_t *const step = parse_expression();
10275                 statement->fors.step = step;
10276                 mark_vars_read(step, ENT_ANY);
10277                 if (warning.unused_value && !expression_has_effect(step)) {
10278                         warningf(&step->base.source_position,
10279                                  "step of 'for'-statement has no effect");
10280                 }
10281         }
10282         expect(')', end_error2);
10283         rem_anchor_token(')');
10284         statement->fors.body = parse_loop_body(statement);
10285
10286         assert(current_scope == &statement->fors.scope);
10287         scope_pop(old_scope);
10288         environment_pop_to(top);
10289
10290         POP_PARENT;
10291         return statement;
10292
10293 end_error2:
10294         POP_PARENT;
10295         rem_anchor_token(')');
10296         assert(current_scope == &statement->fors.scope);
10297         scope_pop(old_scope);
10298         environment_pop_to(top);
10299         /* fallthrough */
10300
10301 end_error1:
10302         return create_invalid_statement();
10303 }
10304
10305 /**
10306  * Parse a goto statement.
10307  */
10308 static statement_t *parse_goto(void)
10309 {
10310         statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10311         eat(T_goto);
10312
10313         if (GNU_MODE && token.type == '*') {
10314                 next_token();
10315                 expression_t *expression = parse_expression();
10316                 mark_vars_read(expression, NULL);
10317
10318                 /* Argh: although documentation says the expression must be of type void*,
10319                  * gcc accepts anything that can be casted into void* without error */
10320                 type_t *type = expression->base.type;
10321
10322                 if (type != type_error_type) {
10323                         if (!is_type_pointer(type) && !is_type_integer(type)) {
10324                                 errorf(&expression->base.source_position,
10325                                         "cannot convert to a pointer type");
10326                         } else if (warning.other && type != type_void_ptr) {
10327                                 warningf(&expression->base.source_position,
10328                                         "type of computed goto expression should be 'void*' not '%T'", type);
10329                         }
10330                         expression = create_implicit_cast(expression, type_void_ptr);
10331                 }
10332
10333                 statement->gotos.expression = expression;
10334         } else {
10335                 if (token.type != T_IDENTIFIER) {
10336                         if (GNU_MODE)
10337                                 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10338                         else
10339                                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10340                         eat_until_anchor();
10341                         goto end_error;
10342                 }
10343                 symbol_t *symbol = token.v.symbol;
10344                 next_token();
10345
10346                 statement->gotos.label = get_label(symbol);
10347         }
10348
10349         /* remember the goto's in a list for later checking */
10350         *goto_anchor = &statement->gotos;
10351         goto_anchor  = &statement->gotos.next;
10352
10353         expect(';', end_error);
10354
10355         return statement;
10356 end_error:
10357         return create_invalid_statement();
10358 }
10359
10360 /**
10361  * Parse a continue statement.
10362  */
10363 static statement_t *parse_continue(void)
10364 {
10365         if (current_loop == NULL) {
10366                 errorf(HERE, "continue statement not within loop");
10367         }
10368
10369         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10370
10371         eat(T_continue);
10372         expect(';', end_error);
10373
10374 end_error:
10375         return statement;
10376 }
10377
10378 /**
10379  * Parse a break statement.
10380  */
10381 static statement_t *parse_break(void)
10382 {
10383         if (current_switch == NULL && current_loop == NULL) {
10384                 errorf(HERE, "break statement not within loop or switch");
10385         }
10386
10387         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10388
10389         eat(T_break);
10390         expect(';', end_error);
10391
10392 end_error:
10393         return statement;
10394 }
10395
10396 /**
10397  * Parse a __leave statement.
10398  */
10399 static statement_t *parse_leave_statement(void)
10400 {
10401         if (current_try == NULL) {
10402                 errorf(HERE, "__leave statement not within __try");
10403         }
10404
10405         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10406
10407         eat(T___leave);
10408         expect(';', end_error);
10409
10410 end_error:
10411         return statement;
10412 }
10413
10414 /**
10415  * Check if a given entity represents a local variable.
10416  */
10417 static bool is_local_variable(const entity_t *entity)
10418 {
10419         if (entity->kind != ENTITY_VARIABLE)
10420                 return false;
10421
10422         switch ((storage_class_tag_t) entity->declaration.storage_class) {
10423         case STORAGE_CLASS_AUTO:
10424         case STORAGE_CLASS_REGISTER: {
10425                 const type_t *type = skip_typeref(entity->declaration.type);
10426                 if (is_type_function(type)) {
10427                         return false;
10428                 } else {
10429                         return true;
10430                 }
10431         }
10432         default:
10433                 return false;
10434         }
10435 }
10436
10437 /**
10438  * Check if a given expression represents a local variable.
10439  */
10440 static bool expression_is_local_variable(const expression_t *expression)
10441 {
10442         if (expression->base.kind != EXPR_REFERENCE) {
10443                 return false;
10444         }
10445         const entity_t *entity = expression->reference.entity;
10446         return is_local_variable(entity);
10447 }
10448
10449 /**
10450  * Check if a given expression represents a local variable and
10451  * return its declaration then, else return NULL.
10452  */
10453 entity_t *expression_is_variable(const expression_t *expression)
10454 {
10455         if (expression->base.kind != EXPR_REFERENCE) {
10456                 return NULL;
10457         }
10458         entity_t *entity = expression->reference.entity;
10459         if (entity->kind != ENTITY_VARIABLE)
10460                 return NULL;
10461
10462         return entity;
10463 }
10464
10465 /**
10466  * Parse a return statement.
10467  */
10468 static statement_t *parse_return(void)
10469 {
10470         eat(T_return);
10471
10472         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10473
10474         expression_t *return_value = NULL;
10475         if (token.type != ';') {
10476                 return_value = parse_expression();
10477                 mark_vars_read(return_value, NULL);
10478         }
10479
10480         const type_t *const func_type = skip_typeref(current_function->base.type);
10481         assert(is_type_function(func_type));
10482         type_t *const return_type = skip_typeref(func_type->function.return_type);
10483
10484         source_position_t const *const pos = &statement->base.source_position;
10485         if (return_value != NULL) {
10486                 type_t *return_value_type = skip_typeref(return_value->base.type);
10487
10488                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10489                         if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10490                                 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10491                                 /* Only warn in C mode, because GCC does the same */
10492                                 if (c_mode & _CXX || strict_mode) {
10493                                         errorf(pos,
10494                                                         "'return' with a value, in function returning 'void'");
10495                                 } else if (warning.other) {
10496                                         warningf(pos,
10497                                                         "'return' with a value, in function returning 'void'");
10498                                 }
10499                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10500                                 /* Only warn in C mode, because GCC does the same */
10501                                 if (strict_mode) {
10502                                         errorf(pos,
10503                                                         "'return' with expression in function return 'void'");
10504                                 } else if (warning.other) {
10505                                         warningf(pos,
10506                                                         "'return' with expression in function return 'void'");
10507                                 }
10508                         }
10509                 } else {
10510                         assign_error_t error = semantic_assign(return_type, return_value);
10511                         report_assign_error(error, return_type, return_value, "'return'",
10512                                         pos);
10513                 }
10514                 return_value = create_implicit_cast(return_value, return_type);
10515                 /* check for returning address of a local var */
10516                 if (warning.other && return_value != NULL
10517                                 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10518                         const expression_t *expression = return_value->unary.value;
10519                         if (expression_is_local_variable(expression)) {
10520                                 warningf(pos, "function returns address of local variable");
10521                         }
10522                 }
10523         } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10524                 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10525                 if (c_mode & _CXX || strict_mode) {
10526                         errorf(pos,
10527                                         "'return' without value, in function returning non-void");
10528                 } else {
10529                         warningf(pos,
10530                                         "'return' without value, in function returning non-void");
10531                 }
10532         }
10533         statement->returns.value = return_value;
10534
10535         expect(';', end_error);
10536
10537 end_error:
10538         return statement;
10539 }
10540
10541 /**
10542  * Parse a declaration statement.
10543  */
10544 static statement_t *parse_declaration_statement(void)
10545 {
10546         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10547
10548         entity_t *before = current_scope->last_entity;
10549         if (GNU_MODE) {
10550                 parse_external_declaration();
10551         } else {
10552                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10553         }
10554
10555         declaration_statement_t *const decl  = &statement->declaration;
10556         entity_t                *const begin =
10557                 before != NULL ? before->base.next : current_scope->entities;
10558         decl->declarations_begin = begin;
10559         decl->declarations_end   = begin != NULL ? current_scope->last_entity : NULL;
10560
10561         return statement;
10562 }
10563
10564 /**
10565  * Parse an expression statement, ie. expr ';'.
10566  */
10567 static statement_t *parse_expression_statement(void)
10568 {
10569         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10570
10571         expression_t *const expr         = parse_expression();
10572         statement->expression.expression = expr;
10573         mark_vars_read(expr, ENT_ANY);
10574
10575         expect(';', end_error);
10576
10577 end_error:
10578         return statement;
10579 }
10580
10581 /**
10582  * Parse a microsoft __try { } __finally { } or
10583  * __try{ } __except() { }
10584  */
10585 static statement_t *parse_ms_try_statment(void)
10586 {
10587         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10588         eat(T___try);
10589
10590         PUSH_PARENT(statement);
10591
10592         ms_try_statement_t *rem = current_try;
10593         current_try = &statement->ms_try;
10594         statement->ms_try.try_statement = parse_compound_statement(false);
10595         current_try = rem;
10596
10597         POP_PARENT;
10598
10599         if (token.type == T___except) {
10600                 eat(T___except);
10601                 expect('(', end_error);
10602                 add_anchor_token(')');
10603                 expression_t *const expr = parse_expression();
10604                 mark_vars_read(expr, NULL);
10605                 type_t       *      type = skip_typeref(expr->base.type);
10606                 if (is_type_integer(type)) {
10607                         type = promote_integer(type);
10608                 } else if (is_type_valid(type)) {
10609                         errorf(&expr->base.source_position,
10610                                "__expect expression is not an integer, but '%T'", type);
10611                         type = type_error_type;
10612                 }
10613                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10614                 rem_anchor_token(')');
10615                 expect(')', end_error);
10616                 statement->ms_try.final_statement = parse_compound_statement(false);
10617         } else if (token.type == T__finally) {
10618                 eat(T___finally);
10619                 statement->ms_try.final_statement = parse_compound_statement(false);
10620         } else {
10621                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10622                 return create_invalid_statement();
10623         }
10624         return statement;
10625 end_error:
10626         return create_invalid_statement();
10627 }
10628
10629 static statement_t *parse_empty_statement(void)
10630 {
10631         if (warning.empty_statement) {
10632                 warningf(HERE, "statement is empty");
10633         }
10634         statement_t *const statement = create_empty_statement();
10635         eat(';');
10636         return statement;
10637 }
10638
10639 static statement_t *parse_local_label_declaration(void)
10640 {
10641         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10642
10643         eat(T___label__);
10644
10645         entity_t *begin = NULL, *end = NULL;
10646
10647         while (true) {
10648                 if (token.type != T_IDENTIFIER) {
10649                         parse_error_expected("while parsing local label declaration",
10650                                 T_IDENTIFIER, NULL);
10651                         goto end_error;
10652                 }
10653                 symbol_t *symbol = token.v.symbol;
10654                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10655                 if (entity != NULL && entity->base.parent_scope == current_scope) {
10656                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10657                                symbol, &entity->base.source_position);
10658                 } else {
10659                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10660
10661                         entity->base.parent_scope    = current_scope;
10662                         entity->base.namespc         = NAMESPACE_LABEL;
10663                         entity->base.source_position = token.source_position;
10664                         entity->base.symbol          = symbol;
10665
10666                         if (end != NULL)
10667                                 end->base.next = entity;
10668                         end = entity;
10669                         if (begin == NULL)
10670                                 begin = entity;
10671
10672                         environment_push(entity);
10673                 }
10674                 next_token();
10675
10676                 if (token.type != ',')
10677                         break;
10678                 next_token();
10679         }
10680         eat(';');
10681 end_error:
10682         statement->declaration.declarations_begin = begin;
10683         statement->declaration.declarations_end   = end;
10684         return statement;
10685 }
10686
10687 static void parse_namespace_definition(void)
10688 {
10689         eat(T_namespace);
10690
10691         entity_t *entity = NULL;
10692         symbol_t *symbol = NULL;
10693
10694         if (token.type == T_IDENTIFIER) {
10695                 symbol = token.v.symbol;
10696                 next_token();
10697
10698                 entity = get_entity(symbol, NAMESPACE_NORMAL);
10699                 if (entity       != NULL             &&
10700                                 entity->kind != ENTITY_NAMESPACE &&
10701                                 entity->base.parent_scope == current_scope) {
10702                         if (!is_error_entity(entity)) {
10703                                 error_redefined_as_different_kind(&token.source_position,
10704                                                 entity, ENTITY_NAMESPACE);
10705                         }
10706                         entity = NULL;
10707                 }
10708         }
10709
10710         if (entity == NULL) {
10711                 entity                       = allocate_entity_zero(ENTITY_NAMESPACE);
10712                 entity->base.symbol          = symbol;
10713                 entity->base.source_position = token.source_position;
10714                 entity->base.namespc         = NAMESPACE_NORMAL;
10715                 entity->base.parent_scope    = current_scope;
10716         }
10717
10718         if (token.type == '=') {
10719                 /* TODO: parse namespace alias */
10720                 panic("namespace alias definition not supported yet");
10721         }
10722
10723         environment_push(entity);
10724         append_entity(current_scope, entity);
10725
10726         size_t const  top       = environment_top();
10727         scope_t      *old_scope = scope_push(&entity->namespacee.members);
10728
10729         expect('{', end_error);
10730         parse_externals();
10731         expect('}', end_error);
10732
10733 end_error:
10734         assert(current_scope == &entity->namespacee.members);
10735         scope_pop(old_scope);
10736         environment_pop_to(top);
10737 }
10738
10739 /**
10740  * Parse a statement.
10741  * There's also parse_statement() which additionally checks for
10742  * "statement has no effect" warnings
10743  */
10744 static statement_t *intern_parse_statement(void)
10745 {
10746         statement_t *statement = NULL;
10747
10748         /* declaration or statement */
10749         add_anchor_token(';');
10750         switch (token.type) {
10751         case T_IDENTIFIER: {
10752                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10753                 if (la1_type == ':') {
10754                         statement = parse_label_statement();
10755                 } else if (is_typedef_symbol(token.v.symbol)) {
10756                         statement = parse_declaration_statement();
10757                 } else {
10758                         /* it's an identifier, the grammar says this must be an
10759                          * expression statement. However it is common that users mistype
10760                          * declaration types, so we guess a bit here to improve robustness
10761                          * for incorrect programs */
10762                         switch (la1_type) {
10763                         case '&':
10764                         case '*':
10765                                 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10766                                         goto expression_statment;
10767                                 /* FALLTHROUGH */
10768
10769                         DECLARATION_START
10770                         case T_IDENTIFIER:
10771                                 statement = parse_declaration_statement();
10772                                 break;
10773
10774                         default:
10775 expression_statment:
10776                                 statement = parse_expression_statement();
10777                                 break;
10778                         }
10779                 }
10780                 break;
10781         }
10782
10783         case T___extension__:
10784                 /* This can be a prefix to a declaration or an expression statement.
10785                  * We simply eat it now and parse the rest with tail recursion. */
10786                 do {
10787                         next_token();
10788                 } while (token.type == T___extension__);
10789                 bool old_gcc_extension = in_gcc_extension;
10790                 in_gcc_extension       = true;
10791                 statement = intern_parse_statement();
10792                 in_gcc_extension = old_gcc_extension;
10793                 break;
10794
10795         DECLARATION_START
10796                 statement = parse_declaration_statement();
10797                 break;
10798
10799         case T___label__:
10800                 statement = parse_local_label_declaration();
10801                 break;
10802
10803         case ';':         statement = parse_empty_statement();         break;
10804         case '{':         statement = parse_compound_statement(false); break;
10805         case T___leave:   statement = parse_leave_statement();         break;
10806         case T___try:     statement = parse_ms_try_statment();         break;
10807         case T_asm:       statement = parse_asm_statement();           break;
10808         case T_break:     statement = parse_break();                   break;
10809         case T_case:      statement = parse_case_statement();          break;
10810         case T_continue:  statement = parse_continue();                break;
10811         case T_default:   statement = parse_default_statement();       break;
10812         case T_do:        statement = parse_do();                      break;
10813         case T_for:       statement = parse_for();                     break;
10814         case T_goto:      statement = parse_goto();                    break;
10815         case T_if:        statement = parse_if();                      break;
10816         case T_return:    statement = parse_return();                  break;
10817         case T_switch:    statement = parse_switch();                  break;
10818         case T_while:     statement = parse_while();                   break;
10819
10820         EXPRESSION_START
10821                 statement = parse_expression_statement();
10822                 break;
10823
10824         default:
10825                 errorf(HERE, "unexpected token %K while parsing statement", &token);
10826                 statement = create_invalid_statement();
10827                 if (!at_anchor())
10828                         next_token();
10829                 break;
10830         }
10831         rem_anchor_token(';');
10832
10833         assert(statement != NULL
10834                         && statement->base.source_position.input_name != NULL);
10835
10836         return statement;
10837 }
10838
10839 /**
10840  * parse a statement and emits "statement has no effect" warning if needed
10841  * (This is really a wrapper around intern_parse_statement with check for 1
10842  *  single warning. It is needed, because for statement expressions we have
10843  *  to avoid the warning on the last statement)
10844  */
10845 static statement_t *parse_statement(void)
10846 {
10847         statement_t *statement = intern_parse_statement();
10848
10849         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10850                 expression_t *expression = statement->expression.expression;
10851                 if (!expression_has_effect(expression)) {
10852                         warningf(&expression->base.source_position,
10853                                         "statement has no effect");
10854                 }
10855         }
10856
10857         return statement;
10858 }
10859
10860 /**
10861  * Parse a compound statement.
10862  */
10863 static statement_t *parse_compound_statement(bool inside_expression_statement)
10864 {
10865         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10866
10867         PUSH_PARENT(statement);
10868
10869         eat('{');
10870         add_anchor_token('}');
10871         /* tokens, which can start a statement */
10872         /* TODO MS, __builtin_FOO */
10873         add_anchor_token('!');
10874         add_anchor_token('&');
10875         add_anchor_token('(');
10876         add_anchor_token('*');
10877         add_anchor_token('+');
10878         add_anchor_token('-');
10879         add_anchor_token('{');
10880         add_anchor_token('~');
10881         add_anchor_token(T_CHARACTER_CONSTANT);
10882         add_anchor_token(T_COLONCOLON);
10883         add_anchor_token(T_FLOATINGPOINT);
10884         add_anchor_token(T_IDENTIFIER);
10885         add_anchor_token(T_INTEGER);
10886         add_anchor_token(T_MINUSMINUS);
10887         add_anchor_token(T_PLUSPLUS);
10888         add_anchor_token(T_STRING_LITERAL);
10889         add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10890         add_anchor_token(T_WIDE_STRING_LITERAL);
10891         add_anchor_token(T__Bool);
10892         add_anchor_token(T__Complex);
10893         add_anchor_token(T__Imaginary);
10894         add_anchor_token(T___FUNCTION__);
10895         add_anchor_token(T___PRETTY_FUNCTION__);
10896         add_anchor_token(T___alignof__);
10897         add_anchor_token(T___attribute__);
10898         add_anchor_token(T___builtin_va_start);
10899         add_anchor_token(T___extension__);
10900         add_anchor_token(T___func__);
10901         add_anchor_token(T___imag__);
10902         add_anchor_token(T___label__);
10903         add_anchor_token(T___real__);
10904         add_anchor_token(T___thread);
10905         add_anchor_token(T_asm);
10906         add_anchor_token(T_auto);
10907         add_anchor_token(T_bool);
10908         add_anchor_token(T_break);
10909         add_anchor_token(T_case);
10910         add_anchor_token(T_char);
10911         add_anchor_token(T_class);
10912         add_anchor_token(T_const);
10913         add_anchor_token(T_const_cast);
10914         add_anchor_token(T_continue);
10915         add_anchor_token(T_default);
10916         add_anchor_token(T_delete);
10917         add_anchor_token(T_double);
10918         add_anchor_token(T_do);
10919         add_anchor_token(T_dynamic_cast);
10920         add_anchor_token(T_enum);
10921         add_anchor_token(T_extern);
10922         add_anchor_token(T_false);
10923         add_anchor_token(T_float);
10924         add_anchor_token(T_for);
10925         add_anchor_token(T_goto);
10926         add_anchor_token(T_if);
10927         add_anchor_token(T_inline);
10928         add_anchor_token(T_int);
10929         add_anchor_token(T_long);
10930         add_anchor_token(T_new);
10931         add_anchor_token(T_operator);
10932         add_anchor_token(T_register);
10933         add_anchor_token(T_reinterpret_cast);
10934         add_anchor_token(T_restrict);
10935         add_anchor_token(T_return);
10936         add_anchor_token(T_short);
10937         add_anchor_token(T_signed);
10938         add_anchor_token(T_sizeof);
10939         add_anchor_token(T_static);
10940         add_anchor_token(T_static_cast);
10941         add_anchor_token(T_struct);
10942         add_anchor_token(T_switch);
10943         add_anchor_token(T_template);
10944         add_anchor_token(T_this);
10945         add_anchor_token(T_throw);
10946         add_anchor_token(T_true);
10947         add_anchor_token(T_try);
10948         add_anchor_token(T_typedef);
10949         add_anchor_token(T_typeid);
10950         add_anchor_token(T_typename);
10951         add_anchor_token(T_typeof);
10952         add_anchor_token(T_union);
10953         add_anchor_token(T_unsigned);
10954         add_anchor_token(T_using);
10955         add_anchor_token(T_void);
10956         add_anchor_token(T_volatile);
10957         add_anchor_token(T_wchar_t);
10958         add_anchor_token(T_while);
10959
10960         size_t const  top       = environment_top();
10961         scope_t      *old_scope = scope_push(&statement->compound.scope);
10962
10963         statement_t **anchor            = &statement->compound.statements;
10964         bool          only_decls_so_far = true;
10965         while (token.type != '}') {
10966                 if (token.type == T_EOF) {
10967                         errorf(&statement->base.source_position,
10968                                "EOF while parsing compound statement");
10969                         break;
10970                 }
10971                 statement_t *sub_statement = intern_parse_statement();
10972                 if (is_invalid_statement(sub_statement)) {
10973                         /* an error occurred. if we are at an anchor, return */
10974                         if (at_anchor())
10975                                 goto end_error;
10976                         continue;
10977                 }
10978
10979                 if (warning.declaration_after_statement) {
10980                         if (sub_statement->kind != STATEMENT_DECLARATION) {
10981                                 only_decls_so_far = false;
10982                         } else if (!only_decls_so_far) {
10983                                 warningf(&sub_statement->base.source_position,
10984                                          "ISO C90 forbids mixed declarations and code");
10985                         }
10986                 }
10987
10988                 *anchor = sub_statement;
10989
10990                 while (sub_statement->base.next != NULL)
10991                         sub_statement = sub_statement->base.next;
10992
10993                 anchor = &sub_statement->base.next;
10994         }
10995         next_token();
10996
10997         /* look over all statements again to produce no effect warnings */
10998         if (warning.unused_value) {
10999                 statement_t *sub_statement = statement->compound.statements;
11000                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11001                         if (sub_statement->kind != STATEMENT_EXPRESSION)
11002                                 continue;
11003                         /* don't emit a warning for the last expression in an expression
11004                          * statement as it has always an effect */
11005                         if (inside_expression_statement && sub_statement->base.next == NULL)
11006                                 continue;
11007
11008                         expression_t *expression = sub_statement->expression.expression;
11009                         if (!expression_has_effect(expression)) {
11010                                 warningf(&expression->base.source_position,
11011                                          "statement has no effect");
11012                         }
11013                 }
11014         }
11015
11016 end_error:
11017         rem_anchor_token(T_while);
11018         rem_anchor_token(T_wchar_t);
11019         rem_anchor_token(T_volatile);
11020         rem_anchor_token(T_void);
11021         rem_anchor_token(T_using);
11022         rem_anchor_token(T_unsigned);
11023         rem_anchor_token(T_union);
11024         rem_anchor_token(T_typeof);
11025         rem_anchor_token(T_typename);
11026         rem_anchor_token(T_typeid);
11027         rem_anchor_token(T_typedef);
11028         rem_anchor_token(T_try);
11029         rem_anchor_token(T_true);
11030         rem_anchor_token(T_throw);
11031         rem_anchor_token(T_this);
11032         rem_anchor_token(T_template);
11033         rem_anchor_token(T_switch);
11034         rem_anchor_token(T_struct);
11035         rem_anchor_token(T_static_cast);
11036         rem_anchor_token(T_static);
11037         rem_anchor_token(T_sizeof);
11038         rem_anchor_token(T_signed);
11039         rem_anchor_token(T_short);
11040         rem_anchor_token(T_return);
11041         rem_anchor_token(T_restrict);
11042         rem_anchor_token(T_reinterpret_cast);
11043         rem_anchor_token(T_register);
11044         rem_anchor_token(T_operator);
11045         rem_anchor_token(T_new);
11046         rem_anchor_token(T_long);
11047         rem_anchor_token(T_int);
11048         rem_anchor_token(T_inline);
11049         rem_anchor_token(T_if);
11050         rem_anchor_token(T_goto);
11051         rem_anchor_token(T_for);
11052         rem_anchor_token(T_float);
11053         rem_anchor_token(T_false);
11054         rem_anchor_token(T_extern);
11055         rem_anchor_token(T_enum);
11056         rem_anchor_token(T_dynamic_cast);
11057         rem_anchor_token(T_do);
11058         rem_anchor_token(T_double);
11059         rem_anchor_token(T_delete);
11060         rem_anchor_token(T_default);
11061         rem_anchor_token(T_continue);
11062         rem_anchor_token(T_const_cast);
11063         rem_anchor_token(T_const);
11064         rem_anchor_token(T_class);
11065         rem_anchor_token(T_char);
11066         rem_anchor_token(T_case);
11067         rem_anchor_token(T_break);
11068         rem_anchor_token(T_bool);
11069         rem_anchor_token(T_auto);
11070         rem_anchor_token(T_asm);
11071         rem_anchor_token(T___thread);
11072         rem_anchor_token(T___real__);
11073         rem_anchor_token(T___label__);
11074         rem_anchor_token(T___imag__);
11075         rem_anchor_token(T___func__);
11076         rem_anchor_token(T___extension__);
11077         rem_anchor_token(T___builtin_va_start);
11078         rem_anchor_token(T___attribute__);
11079         rem_anchor_token(T___alignof__);
11080         rem_anchor_token(T___PRETTY_FUNCTION__);
11081         rem_anchor_token(T___FUNCTION__);
11082         rem_anchor_token(T__Imaginary);
11083         rem_anchor_token(T__Complex);
11084         rem_anchor_token(T__Bool);
11085         rem_anchor_token(T_WIDE_STRING_LITERAL);
11086         rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11087         rem_anchor_token(T_STRING_LITERAL);
11088         rem_anchor_token(T_PLUSPLUS);
11089         rem_anchor_token(T_MINUSMINUS);
11090         rem_anchor_token(T_INTEGER);
11091         rem_anchor_token(T_IDENTIFIER);
11092         rem_anchor_token(T_FLOATINGPOINT);
11093         rem_anchor_token(T_COLONCOLON);
11094         rem_anchor_token(T_CHARACTER_CONSTANT);
11095         rem_anchor_token('~');
11096         rem_anchor_token('{');
11097         rem_anchor_token('-');
11098         rem_anchor_token('+');
11099         rem_anchor_token('*');
11100         rem_anchor_token('(');
11101         rem_anchor_token('&');
11102         rem_anchor_token('!');
11103         rem_anchor_token('}');
11104         assert(current_scope == &statement->compound.scope);
11105         scope_pop(old_scope);
11106         environment_pop_to(top);
11107
11108         POP_PARENT;
11109         return statement;
11110 }
11111
11112 /**
11113  * Check for unused global static functions and variables
11114  */
11115 static void check_unused_globals(void)
11116 {
11117         if (!warning.unused_function && !warning.unused_variable)
11118                 return;
11119
11120         for (const entity_t *entity = file_scope->entities; entity != NULL;
11121              entity = entity->base.next) {
11122                 if (!is_declaration(entity))
11123                         continue;
11124
11125                 const declaration_t *declaration = &entity->declaration;
11126                 if (declaration->used                  ||
11127                     declaration->modifiers & DM_UNUSED ||
11128                     declaration->modifiers & DM_USED   ||
11129                     declaration->storage_class != STORAGE_CLASS_STATIC)
11130                         continue;
11131
11132                 type_t *const type = declaration->type;
11133                 const char *s;
11134                 if (entity->kind == ENTITY_FUNCTION) {
11135                         /* inhibit warning for static inline functions */
11136                         if (entity->function.is_inline)
11137                                 continue;
11138
11139                         s = entity->function.statement != NULL ? "defined" : "declared";
11140                 } else {
11141                         s = "defined";
11142                 }
11143
11144                 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11145                         type, declaration->base.symbol, s);
11146         }
11147 }
11148
11149 static void parse_global_asm(void)
11150 {
11151         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11152
11153         eat(T_asm);
11154         expect('(', end_error);
11155
11156         statement->asms.asm_text = parse_string_literals();
11157         statement->base.next     = unit->global_asm;
11158         unit->global_asm         = statement;
11159
11160         expect(')', end_error);
11161         expect(';', end_error);
11162
11163 end_error:;
11164 }
11165
11166 static void parse_linkage_specification(void)
11167 {
11168         eat(T_extern);
11169         assert(token.type == T_STRING_LITERAL);
11170
11171         const char *linkage = parse_string_literals().begin;
11172
11173         linkage_kind_t old_linkage = current_linkage;
11174         linkage_kind_t new_linkage;
11175         if (strcmp(linkage, "C") == 0) {
11176                 new_linkage = LINKAGE_C;
11177         } else if (strcmp(linkage, "C++") == 0) {
11178                 new_linkage = LINKAGE_CXX;
11179         } else {
11180                 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11181                 new_linkage = LINKAGE_INVALID;
11182         }
11183         current_linkage = new_linkage;
11184
11185         if (token.type == '{') {
11186                 next_token();
11187                 parse_externals();
11188                 expect('}', end_error);
11189         } else {
11190                 parse_external();
11191         }
11192
11193 end_error:
11194         assert(current_linkage == new_linkage);
11195         current_linkage = old_linkage;
11196 }
11197
11198 static void parse_external(void)
11199 {
11200         switch (token.type) {
11201                 DECLARATION_START_NO_EXTERN
11202                 case T_IDENTIFIER:
11203                 case T___extension__:
11204                 /* tokens below are for implicit int */
11205                 case '&': /* & x; -> int& x; (and error later, because C++ has no
11206                              implicit int) */
11207                 case '*': /* * x; -> int* x; */
11208                 case '(': /* (x); -> int (x); */
11209                         parse_external_declaration();
11210                         return;
11211
11212                 case T_extern:
11213                         if (look_ahead(1)->type == T_STRING_LITERAL) {
11214                                 parse_linkage_specification();
11215                         } else {
11216                                 parse_external_declaration();
11217                         }
11218                         return;
11219
11220                 case T_asm:
11221                         parse_global_asm();
11222                         return;
11223
11224                 case T_namespace:
11225                         parse_namespace_definition();
11226                         return;
11227
11228                 case ';':
11229                         if (!strict_mode) {
11230                                 if (warning.other)
11231                                         warningf(HERE, "stray ';' outside of function");
11232                                 next_token();
11233                                 return;
11234                         }
11235                         /* FALLTHROUGH */
11236
11237                 default:
11238                         errorf(HERE, "stray %K outside of function", &token);
11239                         if (token.type == '(' || token.type == '{' || token.type == '[')
11240                                 eat_until_matching_token(token.type);
11241                         next_token();
11242                         return;
11243         }
11244 }
11245
11246 static void parse_externals(void)
11247 {
11248         add_anchor_token('}');
11249         add_anchor_token(T_EOF);
11250
11251 #ifndef NDEBUG
11252         unsigned char token_anchor_copy[T_LAST_TOKEN];
11253         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11254 #endif
11255
11256         while (token.type != T_EOF && token.type != '}') {
11257 #ifndef NDEBUG
11258                 bool anchor_leak = false;
11259                 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11260                         unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11261                         if (count != 0) {
11262                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11263                                 anchor_leak = true;
11264                         }
11265                 }
11266                 if (in_gcc_extension) {
11267                         errorf(HERE, "Leaked __extension__");
11268                         anchor_leak = true;
11269                 }
11270
11271                 if (anchor_leak)
11272                         abort();
11273 #endif
11274
11275                 parse_external();
11276         }
11277
11278         rem_anchor_token(T_EOF);
11279         rem_anchor_token('}');
11280 }
11281
11282 /**
11283  * Parse a translation unit.
11284  */
11285 static void parse_translation_unit(void)
11286 {
11287         add_anchor_token(T_EOF);
11288
11289         while (true) {
11290                 parse_externals();
11291
11292                 if (token.type == T_EOF)
11293                         break;
11294
11295                 errorf(HERE, "stray %K outside of function", &token);
11296                 if (token.type == '(' || token.type == '{' || token.type == '[')
11297                         eat_until_matching_token(token.type);
11298                 next_token();
11299         }
11300 }
11301
11302 /**
11303  * Parse the input.
11304  *
11305  * @return  the translation unit or NULL if errors occurred.
11306  */
11307 void start_parsing(void)
11308 {
11309         environment_stack = NEW_ARR_F(stack_entry_t, 0);
11310         label_stack       = NEW_ARR_F(stack_entry_t, 0);
11311         diagnostic_count  = 0;
11312         error_count       = 0;
11313         warning_count     = 0;
11314
11315         type_set_output(stderr);
11316         ast_set_output(stderr);
11317
11318         assert(unit == NULL);
11319         unit = allocate_ast_zero(sizeof(unit[0]));
11320
11321         assert(file_scope == NULL);
11322         file_scope = &unit->scope;
11323
11324         assert(current_scope == NULL);
11325         scope_push(&unit->scope);
11326
11327         create_gnu_builtins();
11328         if (c_mode & _MS)
11329                 create_microsoft_intrinsics();
11330 }
11331
11332 translation_unit_t *finish_parsing(void)
11333 {
11334         assert(current_scope == &unit->scope);
11335         scope_pop(NULL);
11336
11337         assert(file_scope == &unit->scope);
11338         check_unused_globals();
11339         file_scope = NULL;
11340
11341         DEL_ARR_F(environment_stack);
11342         DEL_ARR_F(label_stack);
11343
11344         translation_unit_t *result = unit;
11345         unit = NULL;
11346         return result;
11347 }
11348
11349 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11350  * are given length one. */
11351 static void complete_incomplete_arrays(void)
11352 {
11353         size_t n = ARR_LEN(incomplete_arrays);
11354         for (size_t i = 0; i != n; ++i) {
11355                 declaration_t *const decl      = incomplete_arrays[i];
11356                 type_t        *const orig_type = decl->type;
11357                 type_t        *const type      = skip_typeref(orig_type);
11358
11359                 if (!is_type_incomplete(type))
11360                         continue;
11361
11362                 if (warning.other) {
11363                         warningf(&decl->base.source_position,
11364                                         "array '%#T' assumed to have one element",
11365                                         orig_type, decl->base.symbol);
11366                 }
11367
11368                 type_t *const new_type = duplicate_type(type);
11369                 new_type->array.size_constant     = true;
11370                 new_type->array.has_implicit_size = true;
11371                 new_type->array.size              = 1;
11372
11373                 type_t *const result = identify_new_type(new_type);
11374
11375                 decl->type = result;
11376         }
11377 }
11378
11379 void parse(void)
11380 {
11381         lookahead_bufpos = 0;
11382         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11383                 next_token();
11384         }
11385         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11386         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11387         parse_translation_unit();
11388         complete_incomplete_arrays();
11389         DEL_ARR_F(incomplete_arrays);
11390         incomplete_arrays = NULL;
11391 }
11392
11393 /**
11394  * create a builtin function.
11395  */
11396 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
11397 {
11398         symbol_t *symbol = symbol_table_insert(name);
11399         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
11400         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
11401         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
11402         entity->declaration.type                   = function_type;
11403         entity->declaration.implicit               = true;
11404         entity->base.symbol                        = symbol;
11405         entity->base.source_position               = builtin_source_position;
11406
11407         entity->function.btk                       = kind;
11408
11409         record_entity(entity, /*is_definition=*/false);
11410         return entity;
11411 }
11412
11413
11414 /**
11415  * Create predefined gnu builtins.
11416  */
11417 static void create_gnu_builtins(void)
11418 {
11419 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
11420
11421         GNU_BUILTIN(alloca,         make_function_1_type(type_void_ptr, type_size_t));
11422         GNU_BUILTIN(huge_val,       make_function_0_type(type_double));
11423         GNU_BUILTIN(inf,            make_function_0_type(type_double));
11424         GNU_BUILTIN(inff,           make_function_0_type(type_float));
11425         GNU_BUILTIN(infl,           make_function_0_type(type_long_double));
11426         GNU_BUILTIN(nan,            make_function_1_type(type_double, type_char_ptr));
11427         GNU_BUILTIN(nanf,           make_function_1_type(type_float, type_char_ptr));
11428         GNU_BUILTIN(nanl,           make_function_1_type(type_long_double, type_char_ptr));
11429         GNU_BUILTIN(va_end,         make_function_1_type(type_void, type_valist));
11430         GNU_BUILTIN(expect,         make_function_2_type(type_long, type_long, type_long));
11431         GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11432         GNU_BUILTIN(frame_address,  make_function_1_type(type_void_ptr, type_unsigned_int));
11433         GNU_BUILTIN(ffs,            make_function_1_type(type_int, type_unsigned_int));
11434         GNU_BUILTIN(clz,            make_function_1_type(type_int, type_unsigned_int));
11435         GNU_BUILTIN(ctz,            make_function_1_type(type_int, type_unsigned_int));
11436         GNU_BUILTIN(popcount,       make_function_1_type(type_int, type_unsigned_int));
11437         GNU_BUILTIN(parity,         make_function_1_type(type_int, type_unsigned_int));
11438         GNU_BUILTIN(prefetch,       make_function_1_type_variadic(type_float, type_void_ptr));
11439         GNU_BUILTIN(trap,           make_function_0_type_noreturn(type_void));
11440
11441 #undef GNU_BUILTIN
11442 }
11443
11444 /**
11445  * Create predefined MS intrinsics.
11446  */
11447 static void create_microsoft_intrinsics(void)
11448 {
11449 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11450
11451         /* intrinsics for all architectures */
11452         MS_BUILTIN(_rotl,                  make_function_2_type(type_unsigned_int,   type_unsigned_int, type_int));
11453         MS_BUILTIN(_rotr,                  make_function_2_type(type_unsigned_int,   type_unsigned_int, type_int));
11454         MS_BUILTIN(_rotl64,                make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11455         MS_BUILTIN(_rotr64,                make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11456         MS_BUILTIN(_byteswap_ushort,       make_function_1_type(type_unsigned_short, type_unsigned_short));
11457         MS_BUILTIN(_byteswap_ulong,        make_function_1_type(type_unsigned_long,  type_unsigned_long));
11458         MS_BUILTIN(_byteswap_uint64,       make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11459
11460         MS_BUILTIN(__debugbreak,    make_function_0_type(type_void));
11461         MS_BUILTIN(_ReturnAddress,  make_function_0_type(type_void_ptr));
11462         MS_BUILTIN(__popcount,      make_function_1_type(type_unsigned_int, type_unsigned_int));
11463
11464         /* x86/x64 only */
11465         MS_BUILTIN(_enable,                make_function_0_type(type_void));
11466         MS_BUILTIN(_disable,               make_function_0_type(type_void));
11467         MS_BUILTIN(__inbyte,               make_function_1_type(type_unsigned_char, type_unsigned_short));
11468         MS_BUILTIN(__inword,               make_function_1_type(type_unsigned_short, type_unsigned_short));
11469         MS_BUILTIN(__indword,              make_function_1_type(type_unsigned_long, type_unsigned_short));
11470         MS_BUILTIN(__outbyte,              make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11471         MS_BUILTIN(__outword,              make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11472         MS_BUILTIN(__outdword,             make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11473         MS_BUILTIN(__ud2,                  make_function_0_type_noreturn(type_void));
11474         MS_BUILTIN(_BitScanForward,        make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11475         MS_BUILTIN(_BitScanReverse,        make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11476         MS_BUILTIN(_InterlockedExchange,   make_function_2_type(type_long, type_long_ptr, type_long));
11477         MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11478
11479         if (machine_size <= 32) {
11480                 MS_BUILTIN(__readeflags,           make_function_0_type(type_unsigned_int));
11481                 MS_BUILTIN(__writeeflags,          make_function_1_type(type_void, type_unsigned_int));
11482         } else {
11483                 MS_BUILTIN(__readeflags,           make_function_0_type(type_unsigned_int64));
11484                 MS_BUILTIN(__writeeflags,          make_function_1_type(type_void, type_unsigned_int64));
11485         }
11486
11487 #undef MS_BUILTIN
11488 }
11489
11490 /**
11491  * Initialize the parser.
11492  */
11493 void init_parser(void)
11494 {
11495         sym_anonymous = symbol_table_insert("<anonymous>");
11496
11497         if (c_mode & _MS) {
11498                 /* add predefined symbols for extended-decl-modifier */
11499                 sym_align         = symbol_table_insert("align");
11500                 sym_allocate      = symbol_table_insert("allocate");
11501                 sym_dllimport     = symbol_table_insert("dllimport");
11502                 sym_dllexport     = symbol_table_insert("dllexport");
11503                 sym_naked         = symbol_table_insert("naked");
11504                 sym_noinline      = symbol_table_insert("noinline");
11505                 sym_returns_twice = symbol_table_insert("returns_twice");
11506                 sym_noreturn      = symbol_table_insert("noreturn");
11507                 sym_nothrow       = symbol_table_insert("nothrow");
11508                 sym_novtable      = symbol_table_insert("novtable");
11509                 sym_property      = symbol_table_insert("property");
11510                 sym_get           = symbol_table_insert("get");
11511                 sym_put           = symbol_table_insert("put");
11512                 sym_selectany     = symbol_table_insert("selectany");
11513                 sym_thread        = symbol_table_insert("thread");
11514                 sym_uuid          = symbol_table_insert("uuid");
11515                 sym_deprecated    = symbol_table_insert("deprecated");
11516                 sym_restrict      = symbol_table_insert("restrict");
11517                 sym_noalias       = symbol_table_insert("noalias");
11518         }
11519         memset(token_anchor_set, 0, sizeof(token_anchor_set));
11520
11521         init_expression_parsers();
11522         obstack_init(&temp_obst);
11523
11524         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11525         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11526 }
11527
11528 /**
11529  * Terminate the parser.
11530  */
11531 void exit_parser(void)
11532 {
11533         obstack_free(&temp_obst, NULL);
11534 }