gcc50: Disconnect from buildworld.
[dragonfly.git] / contrib / gcc-5.0 / gcc / c-family / c-common.c
1 /* Subroutines shared by all languages that are variants of C.
2    Copyright (C) 1992-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #define GCC_C_COMMON_C
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "input.h"
26 #include "c-common.h"
27 #include "tm.h"
28 #include "intl.h"
29 #include "tree.h"
30 #include "fold-const.h"
31 #include "stor-layout.h"
32 #include "calls.h"
33 #include "stringpool.h"
34 #include "attribs.h"
35 #include "varasm.h"
36 #include "trans-mem.h"
37 #include "flags.h"
38 #include "c-pragma.h"
39 #include "c-objc.h"
40 #include "tm_p.h"
41 #include "obstack.h"
42 #include "cpplib.h"
43 #include "target.h"
44 #include "common/common-target.h"
45 #include "langhooks.h"
46 #include "tree-inline.h"
47 #include "toplev.h"
48 #include "diagnostic.h"
49 #include "tree-iterator.h"
50 #include "hashtab.h"
51 #include "opts.h"
52 #include "hash-map.h"
53 #include "is-a.h"
54 #include "plugin-api.h"
55 #include "vec.h"
56 #include "hash-set.h"
57 #include "machmode.h"
58 #include "hard-reg-set.h"
59 #include "input.h"
60 #include "function.h"
61 #include "ipa-ref.h"
62 #include "cgraph.h"
63 #include "target-def.h"
64 #include "gimplify.h"
65 #include "wide-int-print.h"
66 #include "gimple-expr.h"
67
68 cpp_reader *parse_in;           /* Declared in c-pragma.h.  */
69
70 /* Mode used to build pointers (VOIDmode means ptr_mode).  */
71
72 machine_mode c_default_pointer_mode = VOIDmode;
73
74 /* The following symbols are subsumed in the c_global_trees array, and
75    listed here individually for documentation purposes.
76
77    INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
78
79         tree short_integer_type_node;
80         tree long_integer_type_node;
81         tree long_long_integer_type_node;
82
83         tree short_unsigned_type_node;
84         tree long_unsigned_type_node;
85         tree long_long_unsigned_type_node;
86
87         tree truthvalue_type_node;
88         tree truthvalue_false_node;
89         tree truthvalue_true_node;
90
91         tree ptrdiff_type_node;
92
93         tree unsigned_char_type_node;
94         tree signed_char_type_node;
95         tree wchar_type_node;
96
97         tree char16_type_node;
98         tree char32_type_node;
99
100         tree float_type_node;
101         tree double_type_node;
102         tree long_double_type_node;
103
104         tree complex_integer_type_node;
105         tree complex_float_type_node;
106         tree complex_double_type_node;
107         tree complex_long_double_type_node;
108
109         tree dfloat32_type_node;
110         tree dfloat64_type_node;
111         tree_dfloat128_type_node;
112
113         tree intQI_type_node;
114         tree intHI_type_node;
115         tree intSI_type_node;
116         tree intDI_type_node;
117         tree intTI_type_node;
118
119         tree unsigned_intQI_type_node;
120         tree unsigned_intHI_type_node;
121         tree unsigned_intSI_type_node;
122         tree unsigned_intDI_type_node;
123         tree unsigned_intTI_type_node;
124
125         tree widest_integer_literal_type_node;
126         tree widest_unsigned_literal_type_node;
127
128    Nodes for types `void *' and `const void *'.
129
130         tree ptr_type_node, const_ptr_type_node;
131
132    Nodes for types `char *' and `const char *'.
133
134         tree string_type_node, const_string_type_node;
135
136    Type `char[SOMENUMBER]'.
137    Used when an array of char is needed and the size is irrelevant.
138
139         tree char_array_type_node;
140
141    Type `wchar_t[SOMENUMBER]' or something like it.
142    Used when a wide string literal is created.
143
144         tree wchar_array_type_node;
145
146    Type `char16_t[SOMENUMBER]' or something like it.
147    Used when a UTF-16 string literal is created.
148
149         tree char16_array_type_node;
150
151    Type `char32_t[SOMENUMBER]' or something like it.
152    Used when a UTF-32 string literal is created.
153
154         tree char32_array_type_node;
155
156    Type `int ()' -- used for implicit declaration of functions.
157
158         tree default_function_type;
159
160    A VOID_TYPE node, packaged in a TREE_LIST.
161
162         tree void_list_node;
163
164   The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
165   and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
166   VAR_DECLS, but C++ does.)
167
168         tree function_name_decl_node;
169         tree pretty_function_name_decl_node;
170         tree c99_function_name_decl_node;
171
172   Stack of nested function name VAR_DECLs.
173
174         tree saved_function_name_decls;
175
176 */
177
178 tree c_global_trees[CTI_MAX];
179 \f
180 /* Switches common to the C front ends.  */
181
182 /* Nonzero means don't output line number information.  */
183
184 char flag_no_line_commands;
185
186 /* Nonzero causes -E output not to be done, but directives such as
187    #define that have side effects are still obeyed.  */
188
189 char flag_no_output;
190
191 /* Nonzero means dump macros in some fashion.  */
192
193 char flag_dump_macros;
194
195 /* Nonzero means pass #include lines through to the output.  */
196
197 char flag_dump_includes;
198
199 /* Nonzero means process PCH files while preprocessing.  */
200
201 bool flag_pch_preprocess;
202
203 /* The file name to which we should write a precompiled header, or
204    NULL if no header will be written in this compile.  */
205
206 const char *pch_file;
207
208 /* Nonzero if an ISO standard was selected.  It rejects macros in the
209    user's namespace.  */
210 int flag_iso;
211
212 /* C/ObjC language option variables.  */
213
214
215 /* Nonzero means allow type mismatches in conditional expressions;
216    just make their values `void'.  */
217
218 int flag_cond_mismatch;
219
220 /* Nonzero means enable C89 Amendment 1 features.  */
221
222 int flag_isoc94;
223
224 /* Nonzero means use the ISO C99 (or C11) dialect of C.  */
225
226 int flag_isoc99;
227
228 /* Nonzero means use the ISO C11 dialect of C.  */
229
230 int flag_isoc11;
231
232 /* Nonzero means that we have builtin functions, and main is an int.  */
233
234 int flag_hosted = 1;
235
236
237 /* ObjC language option variables.  */
238
239
240 /* Tells the compiler that this is a special run.  Do not perform any
241    compiling, instead we are to test some platform dependent features
242    and output a C header file with appropriate definitions.  */
243
244 int print_struct_values;
245
246 /* Tells the compiler what is the constant string class for ObjC.  */
247
248 const char *constant_string_class_name;
249
250
251 /* C++ language option variables.  */
252
253
254 /* Nonzero means generate separate instantiation control files and
255    juggle them at link time.  */
256
257 int flag_use_repository;
258
259 /* The C++ dialect being used. C++98 is the default.  */
260
261 enum cxx_dialect cxx_dialect = cxx98;
262
263 /* Maximum template instantiation depth.  This limit exists to limit the
264    time it takes to notice excessively recursive template instantiations.
265
266    The default is lower than the 1024 recommended by the C++0x standard
267    because G++ runs out of stack before 1024 with highly recursive template
268    argument deduction substitution (g++.dg/cpp0x/enum11.C).  */
269
270 int max_tinst_depth = 900;
271
272 /* The elements of `ridpointers' are identifier nodes for the reserved
273    type names and storage classes.  It is indexed by a RID_... value.  */
274 tree *ridpointers;
275
276 tree (*make_fname_decl) (location_t, tree, int);
277
278 /* Nonzero means don't warn about problems that occur when the code is
279    executed.  */
280 int c_inhibit_evaluation_warnings;
281
282 /* Whether we are building a boolean conversion inside
283    convert_for_assignment, or some other late binary operation.  If
284    build_binary_op is called for C (from code shared by C and C++) in
285    this case, then the operands have already been folded and the
286    result will not be folded again, so C_MAYBE_CONST_EXPR should not
287    be generated.  */
288 bool in_late_binary_op;
289
290 /* Whether lexing has been completed, so subsequent preprocessor
291    errors should use the compiler's input_location.  */
292 bool done_lexing = false;
293
294 /* Information about how a function name is generated.  */
295 struct fname_var_t
296 {
297   tree *const decl;     /* pointer to the VAR_DECL.  */
298   const unsigned rid;   /* RID number for the identifier.  */
299   const int pretty;     /* How pretty is it? */
300 };
301
302 /* The three ways of getting then name of the current function.  */
303
304 const struct fname_var_t fname_vars[] =
305 {
306   /* C99 compliant __func__, must be first.  */
307   {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
308   /* GCC __FUNCTION__ compliant.  */
309   {&function_name_decl_node, RID_FUNCTION_NAME, 0},
310   /* GCC __PRETTY_FUNCTION__ compliant.  */
311   {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
312   {NULL, 0, 0},
313 };
314
315 /* Global visibility options.  */
316 struct visibility_flags visibility_options;
317
318 static tree c_fully_fold_internal (tree expr, bool, bool *, bool *);
319 static tree check_case_value (location_t, tree);
320 static bool check_case_bounds (location_t, tree, tree, tree *, tree *);
321
322 static tree handle_packed_attribute (tree *, tree, tree, int, bool *);
323 static tree handle_nocommon_attribute (tree *, tree, tree, int, bool *);
324 static tree handle_common_attribute (tree *, tree, tree, int, bool *);
325 static tree handle_noreturn_attribute (tree *, tree, tree, int, bool *);
326 static tree handle_hot_attribute (tree *, tree, tree, int, bool *);
327 static tree handle_cold_attribute (tree *, tree, tree, int, bool *);
328 static tree handle_no_sanitize_address_attribute (tree *, tree, tree,
329                                                   int, bool *);
330 static tree handle_no_address_safety_analysis_attribute (tree *, tree, tree,
331                                                          int, bool *);
332 static tree handle_no_sanitize_undefined_attribute (tree *, tree, tree, int,
333                                                     bool *);
334 static tree handle_stack_protect_attribute (tree *, tree, tree, int, bool *);
335 static tree handle_noinline_attribute (tree *, tree, tree, int, bool *);
336 static tree handle_noclone_attribute (tree *, tree, tree, int, bool *);
337 static tree handle_noicf_attribute (tree *, tree, tree, int, bool *);
338 static tree handle_leaf_attribute (tree *, tree, tree, int, bool *);
339 static tree handle_always_inline_attribute (tree *, tree, tree, int,
340                                             bool *);
341 static tree handle_gnu_inline_attribute (tree *, tree, tree, int, bool *);
342 static tree handle_artificial_attribute (tree *, tree, tree, int, bool *);
343 static tree handle_flatten_attribute (tree *, tree, tree, int, bool *);
344 static tree handle_error_attribute (tree *, tree, tree, int, bool *);
345 static tree handle_used_attribute (tree *, tree, tree, int, bool *);
346 static tree handle_unused_attribute (tree *, tree, tree, int, bool *);
347 static tree handle_externally_visible_attribute (tree *, tree, tree, int,
348                                                  bool *);
349 static tree handle_no_reorder_attribute (tree *, tree, tree, int,
350                                                  bool *);
351 static tree handle_const_attribute (tree *, tree, tree, int, bool *);
352 static tree handle_transparent_union_attribute (tree *, tree, tree,
353                                                 int, bool *);
354 static tree handle_constructor_attribute (tree *, tree, tree, int, bool *);
355 static tree handle_destructor_attribute (tree *, tree, tree, int, bool *);
356 static tree handle_mode_attribute (tree *, tree, tree, int, bool *);
357 static tree handle_section_attribute (tree *, tree, tree, int, bool *);
358 static tree handle_aligned_attribute (tree *, tree, tree, int, bool *);
359 static tree handle_weak_attribute (tree *, tree, tree, int, bool *) ;
360 static tree handle_alias_ifunc_attribute (bool, tree *, tree, tree, bool *);
361 static tree handle_ifunc_attribute (tree *, tree, tree, int, bool *);
362 static tree handle_alias_attribute (tree *, tree, tree, int, bool *);
363 static tree handle_weakref_attribute (tree *, tree, tree, int, bool *) ;
364 static tree handle_visibility_attribute (tree *, tree, tree, int,
365                                          bool *);
366 static tree handle_tls_model_attribute (tree *, tree, tree, int,
367                                         bool *);
368 static tree handle_no_instrument_function_attribute (tree *, tree,
369                                                      tree, int, bool *);
370 static tree handle_malloc_attribute (tree *, tree, tree, int, bool *);
371 static tree handle_returns_twice_attribute (tree *, tree, tree, int, bool *);
372 static tree handle_no_limit_stack_attribute (tree *, tree, tree, int,
373                                              bool *);
374 static tree handle_pure_attribute (tree *, tree, tree, int, bool *);
375 static tree handle_tm_attribute (tree *, tree, tree, int, bool *);
376 static tree handle_tm_wrap_attribute (tree *, tree, tree, int, bool *);
377 static tree handle_novops_attribute (tree *, tree, tree, int, bool *);
378 static tree handle_deprecated_attribute (tree *, tree, tree, int,
379                                          bool *);
380 static tree handle_vector_size_attribute (tree *, tree, tree, int,
381                                           bool *);
382 static tree handle_nonnull_attribute (tree *, tree, tree, int, bool *);
383 static tree handle_nothrow_attribute (tree *, tree, tree, int, bool *);
384 static tree handle_cleanup_attribute (tree *, tree, tree, int, bool *);
385 static tree handle_warn_unused_result_attribute (tree *, tree, tree, int,
386                                                  bool *);
387 static tree handle_sentinel_attribute (tree *, tree, tree, int, bool *);
388 static tree handle_type_generic_attribute (tree *, tree, tree, int, bool *);
389 static tree handle_alloc_size_attribute (tree *, tree, tree, int, bool *);
390 static tree handle_alloc_align_attribute (tree *, tree, tree, int, bool *);
391 static tree handle_assume_aligned_attribute (tree *, tree, tree, int, bool *);
392 static tree handle_target_attribute (tree *, tree, tree, int, bool *);
393 static tree handle_optimize_attribute (tree *, tree, tree, int, bool *);
394 static tree ignore_attribute (tree *, tree, tree, int, bool *);
395 static tree handle_no_split_stack_attribute (tree *, tree, tree, int, bool *);
396 static tree handle_fnspec_attribute (tree *, tree, tree, int, bool *);
397 static tree handle_warn_unused_attribute (tree *, tree, tree, int, bool *);
398 static tree handle_returns_nonnull_attribute (tree *, tree, tree, int, bool *);
399 static tree handle_omp_declare_simd_attribute (tree *, tree, tree, int,
400                                                bool *);
401 static tree handle_omp_declare_target_attribute (tree *, tree, tree, int,
402                                                  bool *);
403 static tree handle_designated_init_attribute (tree *, tree, tree, int, bool *);
404 static tree handle_bnd_variable_size_attribute (tree *, tree, tree, int, bool *);
405 static tree handle_bnd_legacy (tree *, tree, tree, int, bool *);
406 static tree handle_bnd_instrument (tree *, tree, tree, int, bool *);
407
408 static void check_function_nonnull (tree, int, tree *);
409 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
410 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
411 static bool get_nonnull_operand (tree, unsigned HOST_WIDE_INT *);
412 static int resort_field_decl_cmp (const void *, const void *);
413
414 /* Reserved words.  The third field is a mask: keywords are disabled
415    if they match the mask.
416
417    Masks for languages:
418    C --std=c89: D_C99 | D_CXXONLY | D_OBJC | D_CXX_OBJC
419    C --std=c99: D_CXXONLY | D_OBJC
420    ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
421    C++ --std=c98: D_CONLY | D_CXXOX | D_OBJC
422    C++ --std=c0x: D_CONLY | D_OBJC
423    ObjC++ is like C++ except that D_OBJC is not set
424
425    If -fno-asm is used, D_ASM is added to the mask.  If
426    -fno-gnu-keywords is used, D_EXT is added.  If -fno-asm and C in
427    C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
428    In C with -Wc++-compat, we warn if D_CXXWARN is set.
429
430    Note the complication of the D_CXX_OBJC keywords.  These are
431    reserved words such as 'class'.  In C++, 'class' is a reserved
432    word.  In Objective-C++ it is too.  In Objective-C, it is a
433    reserved word too, but only if it follows an '@' sign.
434 */
435 const struct c_common_resword c_common_reswords[] =
436 {
437   { "_Alignas",         RID_ALIGNAS,   D_CONLY },
438   { "_Alignof",         RID_ALIGNOF,   D_CONLY },
439   { "_Atomic",          RID_ATOMIC,    D_CONLY },
440   { "_Bool",            RID_BOOL,      D_CONLY },
441   { "_Complex",         RID_COMPLEX,    0 },
442   { "_Cilk_spawn",      RID_CILK_SPAWN, 0 },
443   { "_Cilk_sync",       RID_CILK_SYNC,  0 },
444   { "_Cilk_for",        RID_CILK_FOR,   0 },
445   { "_Imaginary",       RID_IMAGINARY, D_CONLY },
446   { "_Decimal32",       RID_DFLOAT32,  D_CONLY | D_EXT },
447   { "_Decimal64",       RID_DFLOAT64,  D_CONLY | D_EXT },
448   { "_Decimal128",      RID_DFLOAT128, D_CONLY | D_EXT },
449   { "_Fract",           RID_FRACT,     D_CONLY | D_EXT },
450   { "_Accum",           RID_ACCUM,     D_CONLY | D_EXT },
451   { "_Sat",             RID_SAT,       D_CONLY | D_EXT },
452   { "_Static_assert",   RID_STATIC_ASSERT, D_CONLY },
453   { "_Noreturn",        RID_NORETURN,  D_CONLY },
454   { "_Generic",         RID_GENERIC,   D_CONLY },
455   { "_Thread_local",    RID_THREAD,    D_CONLY },
456   { "__FUNCTION__",     RID_FUNCTION_NAME, 0 },
457   { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
458   { "__alignof",        RID_ALIGNOF,    0 },
459   { "__alignof__",      RID_ALIGNOF,    0 },
460   { "__asm",            RID_ASM,        0 },
461   { "__asm__",          RID_ASM,        0 },
462   { "__attribute",      RID_ATTRIBUTE,  0 },
463   { "__attribute__",    RID_ATTRIBUTE,  0 },
464   { "__auto_type",      RID_AUTO_TYPE,  D_CONLY },
465   { "__bases",          RID_BASES, D_CXXONLY },
466   { "__builtin_call_with_static_chain",
467     RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
468   { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
469   { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
470   { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
471   { "__builtin_offsetof", RID_OFFSETOF, 0 },
472   { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
473   { "__builtin_va_arg", RID_VA_ARG,     0 },
474   { "__complex",        RID_COMPLEX,    0 },
475   { "__complex__",      RID_COMPLEX,    0 },
476   { "__const",          RID_CONST,      0 },
477   { "__const__",        RID_CONST,      0 },
478   { "__decltype",       RID_DECLTYPE,   D_CXXONLY },
479   { "__direct_bases",   RID_DIRECT_BASES, D_CXXONLY },
480   { "__extension__",    RID_EXTENSION,  0 },
481   { "__func__",         RID_C99_FUNCTION_NAME, 0 },
482   { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
483   { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
484   { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
485   { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
486   { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
487   { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
488   { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
489   { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
490   { "__imag",           RID_IMAGPART,   0 },
491   { "__imag__",         RID_IMAGPART,   0 },
492   { "__inline",         RID_INLINE,     0 },
493   { "__inline__",       RID_INLINE,     0 },
494   { "__is_abstract",    RID_IS_ABSTRACT, D_CXXONLY },
495   { "__is_base_of",     RID_IS_BASE_OF, D_CXXONLY },
496   { "__is_class",       RID_IS_CLASS,   D_CXXONLY },
497   { "__is_empty",       RID_IS_EMPTY,   D_CXXONLY },
498   { "__is_enum",        RID_IS_ENUM,    D_CXXONLY },
499   { "__is_final",       RID_IS_FINAL,   D_CXXONLY },
500   { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
501   { "__is_pod",         RID_IS_POD,     D_CXXONLY },
502   { "__is_polymorphic", RID_IS_POLYMORPHIC, D_CXXONLY },
503   { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
504   { "__is_trivial",     RID_IS_TRIVIAL, D_CXXONLY },
505   { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
506   { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
507   { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
508   { "__is_union",       RID_IS_UNION,   D_CXXONLY },
509   { "__label__",        RID_LABEL,      0 },
510   { "__null",           RID_NULL,       0 },
511   { "__real",           RID_REALPART,   0 },
512   { "__real__",         RID_REALPART,   0 },
513   { "__restrict",       RID_RESTRICT,   0 },
514   { "__restrict__",     RID_RESTRICT,   0 },
515   { "__signed",         RID_SIGNED,     0 },
516   { "__signed__",       RID_SIGNED,     0 },
517   { "__thread",         RID_THREAD,     0 },
518   { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
519   { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
520   { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
521   { "__typeof",         RID_TYPEOF,     0 },
522   { "__typeof__",       RID_TYPEOF,     0 },
523   { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
524   { "__volatile",       RID_VOLATILE,   0 },
525   { "__volatile__",     RID_VOLATILE,   0 },
526   { "alignas",          RID_ALIGNAS,    D_CXXONLY | D_CXX0X | D_CXXWARN },
527   { "alignof",          RID_ALIGNOF,    D_CXXONLY | D_CXX0X | D_CXXWARN },
528   { "asm",              RID_ASM,        D_ASM },
529   { "auto",             RID_AUTO,       0 },
530   { "bool",             RID_BOOL,       D_CXXONLY | D_CXXWARN },
531   { "break",            RID_BREAK,      0 },
532   { "case",             RID_CASE,       0 },
533   { "catch",            RID_CATCH,      D_CXX_OBJC | D_CXXWARN },
534   { "char",             RID_CHAR,       0 },
535   { "char16_t",         RID_CHAR16,     D_CXXONLY | D_CXX0X | D_CXXWARN },
536   { "char32_t",         RID_CHAR32,     D_CXXONLY | D_CXX0X | D_CXXWARN },
537   { "class",            RID_CLASS,      D_CXX_OBJC | D_CXXWARN },
538   { "const",            RID_CONST,      0 },
539   { "constexpr",        RID_CONSTEXPR,  D_CXXONLY | D_CXX0X | D_CXXWARN },
540   { "const_cast",       RID_CONSTCAST,  D_CXXONLY | D_CXXWARN },
541   { "continue",         RID_CONTINUE,   0 },
542   { "decltype",         RID_DECLTYPE,   D_CXXONLY | D_CXX0X | D_CXXWARN },
543   { "default",          RID_DEFAULT,    0 },
544   { "delete",           RID_DELETE,     D_CXXONLY | D_CXXWARN },
545   { "do",               RID_DO,         0 },
546   { "double",           RID_DOUBLE,     0 },
547   { "dynamic_cast",     RID_DYNCAST,    D_CXXONLY | D_CXXWARN },
548   { "else",             RID_ELSE,       0 },
549   { "enum",             RID_ENUM,       0 },
550   { "explicit",         RID_EXPLICIT,   D_CXXONLY | D_CXXWARN },
551   { "export",           RID_EXPORT,     D_CXXONLY | D_CXXWARN },
552   { "extern",           RID_EXTERN,     0 },
553   { "false",            RID_FALSE,      D_CXXONLY | D_CXXWARN },
554   { "float",            RID_FLOAT,      0 },
555   { "for",              RID_FOR,        0 },
556   { "friend",           RID_FRIEND,     D_CXXONLY | D_CXXWARN },
557   { "goto",             RID_GOTO,       0 },
558   { "if",               RID_IF,         0 },
559   { "inline",           RID_INLINE,     D_EXT89 },
560   { "int",              RID_INT,        0 },
561   { "long",             RID_LONG,       0 },
562   { "mutable",          RID_MUTABLE,    D_CXXONLY | D_CXXWARN },
563   { "namespace",        RID_NAMESPACE,  D_CXXONLY | D_CXXWARN },
564   { "new",              RID_NEW,        D_CXXONLY | D_CXXWARN },
565   { "noexcept",         RID_NOEXCEPT,   D_CXXONLY | D_CXX0X | D_CXXWARN },
566   { "nullptr",          RID_NULLPTR,    D_CXXONLY | D_CXX0X | D_CXXWARN },
567   { "operator",         RID_OPERATOR,   D_CXXONLY | D_CXXWARN },
568   { "private",          RID_PRIVATE,    D_CXX_OBJC | D_CXXWARN },
569   { "protected",        RID_PROTECTED,  D_CXX_OBJC | D_CXXWARN },
570   { "public",           RID_PUBLIC,     D_CXX_OBJC | D_CXXWARN },
571   { "register",         RID_REGISTER,   0 },
572   { "reinterpret_cast", RID_REINTCAST,  D_CXXONLY | D_CXXWARN },
573   { "restrict",         RID_RESTRICT,   D_CONLY | D_C99 },
574   { "return",           RID_RETURN,     0 },
575   { "short",            RID_SHORT,      0 },
576   { "signed",           RID_SIGNED,     0 },
577   { "sizeof",           RID_SIZEOF,     0 },
578   { "static",           RID_STATIC,     0 },
579   { "static_assert",    RID_STATIC_ASSERT, D_CXXONLY | D_CXX0X | D_CXXWARN },
580   { "static_cast",      RID_STATCAST,   D_CXXONLY | D_CXXWARN },
581   { "struct",           RID_STRUCT,     0 },
582   { "switch",           RID_SWITCH,     0 },
583   { "template",         RID_TEMPLATE,   D_CXXONLY | D_CXXWARN },
584   { "this",             RID_THIS,       D_CXXONLY | D_CXXWARN },
585   { "thread_local",     RID_THREAD,     D_CXXONLY | D_CXX0X | D_CXXWARN },
586   { "throw",            RID_THROW,      D_CXX_OBJC | D_CXXWARN },
587   { "true",             RID_TRUE,       D_CXXONLY | D_CXXWARN },
588   { "try",              RID_TRY,        D_CXX_OBJC | D_CXXWARN },
589   { "typedef",          RID_TYPEDEF,    0 },
590   { "typename",         RID_TYPENAME,   D_CXXONLY | D_CXXWARN },
591   { "typeid",           RID_TYPEID,     D_CXXONLY | D_CXXWARN },
592   { "typeof",           RID_TYPEOF,     D_ASM | D_EXT },
593   { "union",            RID_UNION,      0 },
594   { "unsigned",         RID_UNSIGNED,   0 },
595   { "using",            RID_USING,      D_CXXONLY | D_CXXWARN },
596   { "virtual",          RID_VIRTUAL,    D_CXXONLY | D_CXXWARN },
597   { "void",             RID_VOID,       0 },
598   { "volatile",         RID_VOLATILE,   0 },
599   { "wchar_t",          RID_WCHAR,      D_CXXONLY },
600   { "while",            RID_WHILE,      0 },
601   /* These Objective-C keywords are recognized only immediately after
602      an '@'.  */
603   { "compatibility_alias", RID_AT_ALIAS,        D_OBJC },
604   { "defs",             RID_AT_DEFS,            D_OBJC },
605   { "encode",           RID_AT_ENCODE,          D_OBJC },
606   { "end",              RID_AT_END,             D_OBJC },
607   { "implementation",   RID_AT_IMPLEMENTATION,  D_OBJC },
608   { "interface",        RID_AT_INTERFACE,       D_OBJC },
609   { "protocol",         RID_AT_PROTOCOL,        D_OBJC },
610   { "selector",         RID_AT_SELECTOR,        D_OBJC },
611   { "finally",          RID_AT_FINALLY,         D_OBJC },
612   { "synchronized",     RID_AT_SYNCHRONIZED,    D_OBJC },
613   { "optional",         RID_AT_OPTIONAL,        D_OBJC },
614   { "required",         RID_AT_REQUIRED,        D_OBJC },
615   { "property",         RID_AT_PROPERTY,        D_OBJC },
616   { "package",          RID_AT_PACKAGE,         D_OBJC },
617   { "synthesize",       RID_AT_SYNTHESIZE,      D_OBJC },
618   { "dynamic",          RID_AT_DYNAMIC,         D_OBJC },
619   /* These are recognized only in protocol-qualifier context
620      (see above) */
621   { "bycopy",           RID_BYCOPY,             D_OBJC },
622   { "byref",            RID_BYREF,              D_OBJC },
623   { "in",               RID_IN,                 D_OBJC },
624   { "inout",            RID_INOUT,              D_OBJC },
625   { "oneway",           RID_ONEWAY,             D_OBJC },
626   { "out",              RID_OUT,                D_OBJC },
627   /* These are recognized inside a property attribute list */
628   { "assign",           RID_ASSIGN,             D_OBJC }, 
629   { "copy",             RID_COPY,               D_OBJC }, 
630   { "getter",           RID_GETTER,             D_OBJC }, 
631   { "nonatomic",        RID_NONATOMIC,          D_OBJC }, 
632   { "readonly",         RID_READONLY,           D_OBJC }, 
633   { "readwrite",        RID_READWRITE,          D_OBJC }, 
634   { "retain",           RID_RETAIN,             D_OBJC }, 
635   { "setter",           RID_SETTER,             D_OBJC }, 
636 };
637
638 const unsigned int num_c_common_reswords =
639   sizeof c_common_reswords / sizeof (struct c_common_resword);
640
641 /* Table of machine-independent attributes common to all C-like languages.
642
643    All attributes referencing arguments should be additionally processed
644    in chkp_copy_function_type_adding_bounds for correct instrumentation
645    by Pointer Bounds Checker.
646    Current list of processed common attributes: nonnull.  */
647 const struct attribute_spec c_common_attribute_table[] =
648 {
649   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler,
650        affects_type_identity } */
651   { "packed",                 0, 0, false, false, false,
652                               handle_packed_attribute , false},
653   { "nocommon",               0, 0, true,  false, false,
654                               handle_nocommon_attribute, false},
655   { "common",                 0, 0, true,  false, false,
656                               handle_common_attribute, false },
657   /* FIXME: logically, noreturn attributes should be listed as
658      "false, true, true" and apply to function types.  But implementing this
659      would require all the places in the compiler that use TREE_THIS_VOLATILE
660      on a decl to identify non-returning functions to be located and fixed
661      to check the function type instead.  */
662   { "noreturn",               0, 0, true,  false, false,
663                               handle_noreturn_attribute, false },
664   { "volatile",               0, 0, true,  false, false,
665                               handle_noreturn_attribute, false },
666   { "stack_protect",          0, 0, true,  false, false,
667                               handle_stack_protect_attribute, false },
668   { "noinline",               0, 0, true,  false, false,
669                               handle_noinline_attribute, false },
670   { "noclone",                0, 0, true,  false, false,
671                               handle_noclone_attribute, false },
672   { "no_icf",                 0, 0, true,  false, false,
673                               handle_noicf_attribute, false },
674   { "leaf",                   0, 0, true,  false, false,
675                               handle_leaf_attribute, false },
676   { "always_inline",          0, 0, true,  false, false,
677                               handle_always_inline_attribute, false },
678   { "gnu_inline",             0, 0, true,  false, false,
679                               handle_gnu_inline_attribute, false },
680   { "artificial",             0, 0, true,  false, false,
681                               handle_artificial_attribute, false },
682   { "flatten",                0, 0, true,  false, false,
683                               handle_flatten_attribute, false },
684   { "used",                   0, 0, true,  false, false,
685                               handle_used_attribute, false },
686   { "unused",                 0, 0, false, false, false,
687                               handle_unused_attribute, false },
688   { "externally_visible",     0, 0, true,  false, false,
689                               handle_externally_visible_attribute, false },
690   { "no_reorder",             0, 0, true, false, false,
691                               handle_no_reorder_attribute, false },
692   /* The same comments as for noreturn attributes apply to const ones.  */
693   { "const",                  0, 0, true,  false, false,
694                               handle_const_attribute, false },
695   { "transparent_union",      0, 0, false, false, false,
696                               handle_transparent_union_attribute, false },
697   { "constructor",            0, 1, true,  false, false,
698                               handle_constructor_attribute, false },
699   { "destructor",             0, 1, true,  false, false,
700                               handle_destructor_attribute, false },
701   { "mode",                   1, 1, false,  true, false,
702                               handle_mode_attribute, false },
703   { "section",                1, 1, true,  false, false,
704                               handle_section_attribute, false },
705   { "aligned",                0, 1, false, false, false,
706                               handle_aligned_attribute, false },
707   { "weak",                   0, 0, true,  false, false,
708                               handle_weak_attribute, false },
709   { "ifunc",                  1, 1, true,  false, false,
710                               handle_ifunc_attribute, false },
711   { "alias",                  1, 1, true,  false, false,
712                               handle_alias_attribute, false },
713   { "weakref",                0, 1, true,  false, false,
714                               handle_weakref_attribute, false },
715   { "no_instrument_function", 0, 0, true,  false, false,
716                               handle_no_instrument_function_attribute,
717                               false },
718   { "malloc",                 0, 0, true,  false, false,
719                               handle_malloc_attribute, false },
720   { "returns_twice",          0, 0, true,  false, false,
721                               handle_returns_twice_attribute, false },
722   { "no_stack_limit",         0, 0, true,  false, false,
723                               handle_no_limit_stack_attribute, false },
724   { "pure",                   0, 0, true,  false, false,
725                               handle_pure_attribute, false },
726   { "transaction_callable",   0, 0, false, true,  false,
727                               handle_tm_attribute, false },
728   { "transaction_unsafe",     0, 0, false, true,  false,
729                               handle_tm_attribute, false },
730   { "transaction_safe",       0, 0, false, true,  false,
731                               handle_tm_attribute, false },
732   { "transaction_may_cancel_outer", 0, 0, false, true, false,
733                               handle_tm_attribute, false },
734   /* ??? These two attributes didn't make the transition from the
735      Intel language document to the multi-vendor language document.  */
736   { "transaction_pure",       0, 0, false, true,  false,
737                               handle_tm_attribute, false },
738   { "transaction_wrap",       1, 1, true,  false,  false,
739                              handle_tm_wrap_attribute, false },
740   /* For internal use (marking of builtins) only.  The name contains space
741      to prevent its usage in source code.  */
742   { "no vops",                0, 0, true,  false, false,
743                               handle_novops_attribute, false },
744   { "deprecated",             0, 1, false, false, false,
745                               handle_deprecated_attribute, false },
746   { "vector_size",            1, 1, false, true, false,
747                               handle_vector_size_attribute, false },
748   { "visibility",             1, 1, false, false, false,
749                               handle_visibility_attribute, false },
750   { "tls_model",              1, 1, true,  false, false,
751                               handle_tls_model_attribute, false },
752   { "nonnull",                0, -1, false, true, true,
753                               handle_nonnull_attribute, false },
754   { "nothrow",                0, 0, true,  false, false,
755                               handle_nothrow_attribute, false },
756   { "may_alias",              0, 0, false, true, false, NULL, false },
757   { "cleanup",                1, 1, true, false, false,
758                               handle_cleanup_attribute, false },
759   { "warn_unused_result",     0, 0, false, true, true,
760                               handle_warn_unused_result_attribute, false },
761   { "sentinel",               0, 1, false, true, true,
762                               handle_sentinel_attribute, false },
763   /* For internal use (marking of builtins) only.  The name contains space
764      to prevent its usage in source code.  */
765   { "type generic",           0, 0, false, true, true,
766                               handle_type_generic_attribute, false },
767   { "alloc_size",             1, 2, false, true, true,
768                               handle_alloc_size_attribute, false },
769   { "cold",                   0, 0, true,  false, false,
770                               handle_cold_attribute, false },
771   { "hot",                    0, 0, true,  false, false,
772                               handle_hot_attribute, false },
773   { "no_address_safety_analysis",
774                               0, 0, true, false, false,
775                               handle_no_address_safety_analysis_attribute,
776                               false },
777   { "no_sanitize_address",    0, 0, true, false, false,
778                               handle_no_sanitize_address_attribute,
779                               false },
780   { "no_sanitize_thread",     0, 0, true, false, false,
781                               handle_no_sanitize_address_attribute,
782                               false },
783   { "no_sanitize_undefined",  0, 0, true, false, false,
784                               handle_no_sanitize_undefined_attribute,
785                               false },
786   { "warning",                1, 1, true,  false, false,
787                               handle_error_attribute, false },
788   { "error",                  1, 1, true,  false, false,
789                               handle_error_attribute, false },
790   { "target",                 1, -1, true, false, false,
791                               handle_target_attribute, false },
792   { "optimize",               1, -1, true, false, false,
793                               handle_optimize_attribute, false },
794   /* For internal use only.  The leading '*' both prevents its usage in
795      source code and signals that it may be overridden by machine tables.  */
796   { "*tm regparm",            0, 0, false, true, true,
797                               ignore_attribute, false },
798   { "no_split_stack",         0, 0, true,  false, false,
799                               handle_no_split_stack_attribute, false },
800   /* For internal use (marking of builtins and runtime functions) only.
801      The name contains space to prevent its usage in source code.  */
802   { "fn spec",                1, 1, false, true, true,
803                               handle_fnspec_attribute, false },
804   { "warn_unused",            0, 0, false, false, false,
805                               handle_warn_unused_attribute, false },
806   { "returns_nonnull",        0, 0, false, true, true,
807                               handle_returns_nonnull_attribute, false },
808   { "omp declare simd",       0, -1, true,  false, false,
809                               handle_omp_declare_simd_attribute, false },
810   { "cilk simd function",     0, -1, true,  false, false,
811                               handle_omp_declare_simd_attribute, false },
812   { "omp declare target",     0, 0, true, false, false,
813                               handle_omp_declare_target_attribute, false },
814   { "alloc_align",            1, 1, false, true, true,
815                               handle_alloc_align_attribute, false },
816   { "assume_aligned",         1, 2, false, true, true,
817                               handle_assume_aligned_attribute, false },
818   { "designated_init",        0, 0, false, true, false,
819                               handle_designated_init_attribute, false },
820   { "bnd_variable_size",      0, 0, true,  false, false,
821                               handle_bnd_variable_size_attribute, false },
822   { "bnd_legacy",             0, 0, true, false, false,
823                               handle_bnd_legacy, false },
824   { "bnd_instrument",         0, 0, true, false, false,
825                               handle_bnd_instrument, false },
826   { NULL,                     0, 0, false, false, false, NULL, false }
827 };
828
829 /* Give the specifications for the format attributes, used by C and all
830    descendants.
831
832    All attributes referencing arguments should be additionally processed
833    in chkp_copy_function_type_adding_bounds for correct instrumentation
834    by Pointer Bounds Checker.
835    Current list of processed format attributes: format, format_arg.  */
836 const struct attribute_spec c_common_format_attribute_table[] =
837 {
838   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler,
839        affects_type_identity } */
840   { "format",                 3, 3, false, true,  true,
841                               handle_format_attribute, false },
842   { "format_arg",             1, 1, false, true,  true,
843                               handle_format_arg_attribute, false },
844   { NULL,                     0, 0, false, false, false, NULL, false }
845 };
846
847 /* Return identifier for address space AS.  */
848
849 const char *
850 c_addr_space_name (addr_space_t as)
851 {
852   int rid = RID_FIRST_ADDR_SPACE + as;
853   gcc_assert (ridpointers [rid]);
854   return IDENTIFIER_POINTER (ridpointers [rid]);
855 }
856
857 /* Push current bindings for the function name VAR_DECLS.  */
858
859 void
860 start_fname_decls (void)
861 {
862   unsigned ix;
863   tree saved = NULL_TREE;
864
865   for (ix = 0; fname_vars[ix].decl; ix++)
866     {
867       tree decl = *fname_vars[ix].decl;
868
869       if (decl)
870         {
871           saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
872                              saved);
873           *fname_vars[ix].decl = NULL_TREE;
874         }
875     }
876   if (saved || saved_function_name_decls)
877     /* Normally they'll have been NULL, so only push if we've got a
878        stack, or they are non-NULL.  */
879     saved_function_name_decls = tree_cons (saved, NULL_TREE,
880                                            saved_function_name_decls);
881 }
882
883 /* Finish up the current bindings, adding them into the current function's
884    statement tree.  This must be done _before_ finish_stmt_tree is called.
885    If there is no current function, we must be at file scope and no statements
886    are involved. Pop the previous bindings.  */
887
888 void
889 finish_fname_decls (void)
890 {
891   unsigned ix;
892   tree stmts = NULL_TREE;
893   tree stack = saved_function_name_decls;
894
895   for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
896     append_to_statement_list (TREE_VALUE (stack), &stmts);
897
898   if (stmts)
899     {
900       tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
901
902       if (TREE_CODE (*bodyp) == BIND_EXPR)
903         bodyp = &BIND_EXPR_BODY (*bodyp);
904
905       append_to_statement_list_force (*bodyp, &stmts);
906       *bodyp = stmts;
907     }
908
909   for (ix = 0; fname_vars[ix].decl; ix++)
910     *fname_vars[ix].decl = NULL_TREE;
911
912   if (stack)
913     {
914       /* We had saved values, restore them.  */
915       tree saved;
916
917       for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
918         {
919           tree decl = TREE_PURPOSE (saved);
920           unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
921
922           *fname_vars[ix].decl = decl;
923         }
924       stack = TREE_CHAIN (stack);
925     }
926   saved_function_name_decls = stack;
927 }
928
929 /* Return the text name of the current function, suitably prettified
930    by PRETTY_P.  Return string must be freed by caller.  */
931
932 const char *
933 fname_as_string (int pretty_p)
934 {
935   const char *name = "top level";
936   char *namep;
937   int vrb = 2, len;
938   cpp_string cstr = { 0, 0 }, strname;
939
940   if (!pretty_p)
941     {
942       name = "";
943       vrb = 0;
944     }
945
946   if (current_function_decl)
947     name = lang_hooks.decl_printable_name (current_function_decl, vrb);
948
949   len = strlen (name) + 3; /* Two for '"'s.  One for NULL.  */
950
951   namep = XNEWVEC (char, len);
952   snprintf (namep, len, "\"%s\"", name);
953   strname.text = (unsigned char *) namep;
954   strname.len = len - 1;
955
956   if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
957     {
958       XDELETEVEC (namep);
959       return (const char *) cstr.text;
960     }
961
962   return namep;
963 }
964
965 /* Return the VAR_DECL for a const char array naming the current
966    function. If the VAR_DECL has not yet been created, create it
967    now. RID indicates how it should be formatted and IDENTIFIER_NODE
968    ID is its name (unfortunately C and C++ hold the RID values of
969    keywords in different places, so we can't derive RID from ID in
970    this language independent code. LOC is the location of the
971    function.  */
972
973 tree
974 fname_decl (location_t loc, unsigned int rid, tree id)
975 {
976   unsigned ix;
977   tree decl = NULL_TREE;
978
979   for (ix = 0; fname_vars[ix].decl; ix++)
980     if (fname_vars[ix].rid == rid)
981       break;
982
983   decl = *fname_vars[ix].decl;
984   if (!decl)
985     {
986       /* If a tree is built here, it would normally have the lineno of
987          the current statement.  Later this tree will be moved to the
988          beginning of the function and this line number will be wrong.
989          To avoid this problem set the lineno to 0 here; that prevents
990          it from appearing in the RTL.  */
991       tree stmts;
992       location_t saved_location = input_location;
993       input_location = UNKNOWN_LOCATION;
994
995       stmts = push_stmt_list ();
996       decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
997       stmts = pop_stmt_list (stmts);
998       if (!IS_EMPTY_STMT (stmts))
999         saved_function_name_decls
1000           = tree_cons (decl, stmts, saved_function_name_decls);
1001       *fname_vars[ix].decl = decl;
1002       input_location = saved_location;
1003     }
1004   if (!ix && !current_function_decl)
1005     pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
1006
1007   return decl;
1008 }
1009
1010 /* Given a STRING_CST, give it a suitable array-of-chars data type.  */
1011
1012 tree
1013 fix_string_type (tree value)
1014 {
1015   int length = TREE_STRING_LENGTH (value);
1016   int nchars;
1017   tree e_type, i_type, a_type;
1018
1019   /* Compute the number of elements, for the array type.  */
1020   if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
1021     {
1022       nchars = length;
1023       e_type = char_type_node;
1024     }
1025   else if (TREE_TYPE (value) == char16_array_type_node)
1026     {
1027       nchars = length / (TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT);
1028       e_type = char16_type_node;
1029     }
1030   else if (TREE_TYPE (value) == char32_array_type_node)
1031     {
1032       nchars = length / (TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT);
1033       e_type = char32_type_node;
1034     }
1035   else
1036     {
1037       nchars = length / (TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT);
1038       e_type = wchar_type_node;
1039     }
1040
1041   /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits).  The analogous
1042      limit in C++98 Annex B is very large (65536) and is not normative,
1043      so we do not diagnose it (warn_overlength_strings is forced off
1044      in c_common_post_options).  */
1045   if (warn_overlength_strings)
1046     {
1047       const int nchars_max = flag_isoc99 ? 4095 : 509;
1048       const int relevant_std = flag_isoc99 ? 99 : 90;
1049       if (nchars - 1 > nchars_max)
1050         /* Translators: The %d after 'ISO C' will be 90 or 99.  Do not
1051            separate the %d from the 'C'.  'ISO' should not be
1052            translated, but it may be moved after 'C%d' in languages
1053            where modifiers follow nouns.  */
1054         pedwarn (input_location, OPT_Woverlength_strings,
1055                  "string length %qd is greater than the length %qd "
1056                  "ISO C%d compilers are required to support",
1057                  nchars - 1, nchars_max, relevant_std);
1058     }
1059
1060   /* Create the array type for the string constant.  The ISO C++
1061      standard says that a string literal has type `const char[N]' or
1062      `const wchar_t[N]'.  We use the same logic when invoked as a C
1063      front-end with -Wwrite-strings.
1064      ??? We should change the type of an expression depending on the
1065      state of a warning flag.  We should just be warning -- see how
1066      this is handled in the C++ front-end for the deprecated implicit
1067      conversion from string literals to `char*' or `wchar_t*'.
1068
1069      The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
1070      array type being the unqualified version of that type.
1071      Therefore, if we are constructing an array of const char, we must
1072      construct the matching unqualified array type first.  The C front
1073      end does not require this, but it does no harm, so we do it
1074      unconditionally.  */
1075   i_type = build_index_type (size_int (nchars - 1));
1076   a_type = build_array_type (e_type, i_type);
1077   if (c_dialect_cxx() || warn_write_strings)
1078     a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
1079
1080   TREE_TYPE (value) = a_type;
1081   TREE_CONSTANT (value) = 1;
1082   TREE_READONLY (value) = 1;
1083   TREE_STATIC (value) = 1;
1084   return value;
1085 }
1086 \f
1087 /* If DISABLE is true, stop issuing warnings.  This is used when
1088    parsing code that we know will not be executed.  This function may
1089    be called multiple times, and works as a stack.  */
1090
1091 static void
1092 c_disable_warnings (bool disable)
1093 {
1094   if (disable)
1095     {
1096       ++c_inhibit_evaluation_warnings;
1097       fold_defer_overflow_warnings ();
1098     }
1099 }
1100
1101 /* If ENABLE is true, reenable issuing warnings.  */
1102
1103 static void
1104 c_enable_warnings (bool enable)
1105 {
1106   if (enable)
1107     {
1108       --c_inhibit_evaluation_warnings;
1109       fold_undefer_and_ignore_overflow_warnings ();
1110     }
1111 }
1112
1113 /* Fully fold EXPR, an expression that was not folded (beyond integer
1114    constant expressions and null pointer constants) when being built
1115    up.  If IN_INIT, this is in a static initializer and certain
1116    changes are made to the folding done.  Clear *MAYBE_CONST if
1117    MAYBE_CONST is not NULL and EXPR is definitely not a constant
1118    expression because it contains an evaluated operator (in C99) or an
1119    operator outside of sizeof returning an integer constant (in C90)
1120    not permitted in constant expressions, or because it contains an
1121    evaluated arithmetic overflow.  (*MAYBE_CONST should typically be
1122    set to true by callers before calling this function.)  Return the
1123    folded expression.  Function arguments have already been folded
1124    before calling this function, as have the contents of SAVE_EXPR,
1125    TARGET_EXPR, BIND_EXPR, VA_ARG_EXPR, OBJ_TYPE_REF and
1126    C_MAYBE_CONST_EXPR.  */
1127
1128 tree
1129 c_fully_fold (tree expr, bool in_init, bool *maybe_const)
1130 {
1131   tree ret;
1132   tree eptype = NULL_TREE;
1133   bool dummy = true;
1134   bool maybe_const_itself = true;
1135   location_t loc = EXPR_LOCATION (expr);
1136
1137   /* This function is not relevant to C++ because C++ folds while
1138      parsing, and may need changes to be correct for C++ when C++
1139      stops folding while parsing.  */
1140   if (c_dialect_cxx ())
1141     gcc_unreachable ();
1142
1143   if (!maybe_const)
1144     maybe_const = &dummy;
1145   if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1146     {
1147       eptype = TREE_TYPE (expr);
1148       expr = TREE_OPERAND (expr, 0);
1149     }
1150   ret = c_fully_fold_internal (expr, in_init, maybe_const,
1151                                &maybe_const_itself);
1152   if (eptype)
1153     ret = fold_convert_loc (loc, eptype, ret);
1154   *maybe_const &= maybe_const_itself;
1155   return ret;
1156 }
1157
1158 /* Internal helper for c_fully_fold.  EXPR and IN_INIT are as for
1159    c_fully_fold.  *MAYBE_CONST_OPERANDS is cleared because of operands
1160    not permitted, while *MAYBE_CONST_ITSELF is cleared because of
1161    arithmetic overflow (for C90, *MAYBE_CONST_OPERANDS is carried from
1162    both evaluated and unevaluated subexpressions while
1163    *MAYBE_CONST_ITSELF is carried from only evaluated
1164    subexpressions).  */
1165
1166 static tree
1167 c_fully_fold_internal (tree expr, bool in_init, bool *maybe_const_operands,
1168                        bool *maybe_const_itself)
1169 {
1170   tree ret = expr;
1171   enum tree_code code = TREE_CODE (expr);
1172   enum tree_code_class kind = TREE_CODE_CLASS (code);
1173   location_t loc = EXPR_LOCATION (expr);
1174   tree op0, op1, op2, op3;
1175   tree orig_op0, orig_op1, orig_op2;
1176   bool op0_const = true, op1_const = true, op2_const = true;
1177   bool op0_const_self = true, op1_const_self = true, op2_const_self = true;
1178   bool nowarning = TREE_NO_WARNING (expr);
1179   bool unused_p;
1180
1181   /* This function is not relevant to C++ because C++ folds while
1182      parsing, and may need changes to be correct for C++ when C++
1183      stops folding while parsing.  */
1184   if (c_dialect_cxx ())
1185     gcc_unreachable ();
1186
1187   /* Constants, declarations, statements, errors, SAVE_EXPRs and
1188      anything else not counted as an expression cannot usefully be
1189      folded further at this point.  */
1190   if (!IS_EXPR_CODE_CLASS (kind)
1191       || kind == tcc_statement
1192       || code == SAVE_EXPR)
1193     return expr;
1194
1195   /* Operands of variable-length expressions (function calls) have
1196      already been folded, as have __builtin_* function calls, and such
1197      expressions cannot occur in constant expressions.  */
1198   if (kind == tcc_vl_exp)
1199     {
1200       *maybe_const_operands = false;
1201       ret = fold (expr);
1202       goto out;
1203     }
1204
1205   if (code == C_MAYBE_CONST_EXPR)
1206     {
1207       tree pre = C_MAYBE_CONST_EXPR_PRE (expr);
1208       tree inner = C_MAYBE_CONST_EXPR_EXPR (expr);
1209       if (C_MAYBE_CONST_EXPR_NON_CONST (expr))
1210         *maybe_const_operands = false;
1211       if (C_MAYBE_CONST_EXPR_INT_OPERANDS (expr))
1212         *maybe_const_itself = false;
1213       if (pre && !in_init)
1214         ret = build2 (COMPOUND_EXPR, TREE_TYPE (expr), pre, inner);
1215       else
1216         ret = inner;
1217       goto out;
1218     }
1219
1220   /* Assignment, increment, decrement, function call and comma
1221      operators, and statement expressions, cannot occur in constant
1222      expressions if evaluated / outside of sizeof.  (Function calls
1223      were handled above, though VA_ARG_EXPR is treated like a function
1224      call here, and statement expressions are handled through
1225      C_MAYBE_CONST_EXPR to avoid folding inside them.)  */
1226   switch (code)
1227     {
1228     case MODIFY_EXPR:
1229     case PREDECREMENT_EXPR:
1230     case PREINCREMENT_EXPR:
1231     case POSTDECREMENT_EXPR:
1232     case POSTINCREMENT_EXPR:
1233     case COMPOUND_EXPR:
1234       *maybe_const_operands = false;
1235       break;
1236
1237     case VA_ARG_EXPR:
1238     case TARGET_EXPR:
1239     case BIND_EXPR:
1240     case OBJ_TYPE_REF:
1241       *maybe_const_operands = false;
1242       ret = fold (expr);
1243       goto out;
1244
1245     default:
1246       break;
1247     }
1248
1249   /* Fold individual tree codes as appropriate.  */
1250   switch (code)
1251     {
1252     case COMPOUND_LITERAL_EXPR:
1253       /* Any non-constancy will have been marked in a containing
1254          C_MAYBE_CONST_EXPR; there is no more folding to do here.  */
1255       goto out;
1256
1257     case COMPONENT_REF:
1258       orig_op0 = op0 = TREE_OPERAND (expr, 0);
1259       op1 = TREE_OPERAND (expr, 1);
1260       op2 = TREE_OPERAND (expr, 2);
1261       op0 = c_fully_fold_internal (op0, in_init, maybe_const_operands,
1262                                    maybe_const_itself);
1263       STRIP_TYPE_NOPS (op0);
1264       if (op0 != orig_op0)
1265         ret = build3 (COMPONENT_REF, TREE_TYPE (expr), op0, op1, op2);
1266       if (ret != expr)
1267         {
1268           TREE_READONLY (ret) = TREE_READONLY (expr);
1269           TREE_THIS_VOLATILE (ret) = TREE_THIS_VOLATILE (expr);
1270         }
1271       goto out;
1272
1273     case ARRAY_REF:
1274       orig_op0 = op0 = TREE_OPERAND (expr, 0);
1275       orig_op1 = op1 = TREE_OPERAND (expr, 1);
1276       op2 = TREE_OPERAND (expr, 2);
1277       op3 = TREE_OPERAND (expr, 3);
1278       op0 = c_fully_fold_internal (op0, in_init, maybe_const_operands,
1279                                    maybe_const_itself);
1280       STRIP_TYPE_NOPS (op0);
1281       op1 = c_fully_fold_internal (op1, in_init, maybe_const_operands,
1282                                    maybe_const_itself);
1283       STRIP_TYPE_NOPS (op1);
1284       op1 = decl_constant_value_for_optimization (op1);
1285       if (op0 != orig_op0 || op1 != orig_op1)
1286         ret = build4 (ARRAY_REF, TREE_TYPE (expr), op0, op1, op2, op3);
1287       if (ret != expr)
1288         {
1289           TREE_READONLY (ret) = TREE_READONLY (expr);
1290           TREE_SIDE_EFFECTS (ret) = TREE_SIDE_EFFECTS (expr);
1291           TREE_THIS_VOLATILE (ret) = TREE_THIS_VOLATILE (expr);
1292         }
1293       ret = fold (ret);
1294       goto out;
1295
1296     case COMPOUND_EXPR:
1297     case MODIFY_EXPR:
1298     case PREDECREMENT_EXPR:
1299     case PREINCREMENT_EXPR:
1300     case POSTDECREMENT_EXPR:
1301     case POSTINCREMENT_EXPR:
1302     case PLUS_EXPR:
1303     case MINUS_EXPR:
1304     case MULT_EXPR:
1305     case POINTER_PLUS_EXPR:
1306     case TRUNC_DIV_EXPR:
1307     case CEIL_DIV_EXPR:
1308     case FLOOR_DIV_EXPR:
1309     case TRUNC_MOD_EXPR:
1310     case RDIV_EXPR:
1311     case EXACT_DIV_EXPR:
1312     case LSHIFT_EXPR:
1313     case RSHIFT_EXPR:
1314     case BIT_IOR_EXPR:
1315     case BIT_XOR_EXPR:
1316     case BIT_AND_EXPR:
1317     case LT_EXPR:
1318     case LE_EXPR:
1319     case GT_EXPR:
1320     case GE_EXPR:
1321     case EQ_EXPR:
1322     case NE_EXPR:
1323     case COMPLEX_EXPR:
1324     case TRUTH_AND_EXPR:
1325     case TRUTH_OR_EXPR:
1326     case TRUTH_XOR_EXPR:
1327     case UNORDERED_EXPR:
1328     case ORDERED_EXPR:
1329     case UNLT_EXPR:
1330     case UNLE_EXPR:
1331     case UNGT_EXPR:
1332     case UNGE_EXPR:
1333     case UNEQ_EXPR:
1334       /* Binary operations evaluating both arguments (increment and
1335          decrement are binary internally in GCC).  */
1336       orig_op0 = op0 = TREE_OPERAND (expr, 0);
1337       orig_op1 = op1 = TREE_OPERAND (expr, 1);
1338       op0 = c_fully_fold_internal (op0, in_init, maybe_const_operands,
1339                                    maybe_const_itself);
1340       STRIP_TYPE_NOPS (op0);
1341       if (code != MODIFY_EXPR
1342           && code != PREDECREMENT_EXPR
1343           && code != PREINCREMENT_EXPR
1344           && code != POSTDECREMENT_EXPR
1345           && code != POSTINCREMENT_EXPR)
1346         op0 = decl_constant_value_for_optimization (op0);
1347       /* The RHS of a MODIFY_EXPR was fully folded when building that
1348          expression for the sake of conversion warnings.  */
1349       if (code != MODIFY_EXPR)
1350         op1 = c_fully_fold_internal (op1, in_init, maybe_const_operands,
1351                                      maybe_const_itself);
1352       STRIP_TYPE_NOPS (op1);
1353       op1 = decl_constant_value_for_optimization (op1);
1354       if (op0 != orig_op0 || op1 != orig_op1 || in_init)
1355         ret = in_init
1356           ? fold_build2_initializer_loc (loc, code, TREE_TYPE (expr), op0, op1)
1357           : fold_build2_loc (loc, code, TREE_TYPE (expr), op0, op1);
1358       else
1359         ret = fold (expr);
1360       if (TREE_OVERFLOW_P (ret)
1361           && !TREE_OVERFLOW_P (op0)
1362           && !TREE_OVERFLOW_P (op1))
1363         overflow_warning (EXPR_LOCATION (expr), ret);
1364       if ((code == LSHIFT_EXPR || code == RSHIFT_EXPR)
1365           && TREE_CODE (orig_op1) != INTEGER_CST
1366           && TREE_CODE (op1) == INTEGER_CST
1367           && (TREE_CODE (TREE_TYPE (orig_op0)) == INTEGER_TYPE
1368               || TREE_CODE (TREE_TYPE (orig_op0)) == FIXED_POINT_TYPE)
1369           && TREE_CODE (TREE_TYPE (orig_op1)) == INTEGER_TYPE
1370           && c_inhibit_evaluation_warnings == 0)
1371         {
1372           if (tree_int_cst_sgn (op1) < 0)
1373             warning_at (loc, 0, (code == LSHIFT_EXPR
1374                                  ? G_("left shift count is negative")
1375                                  : G_("right shift count is negative")));
1376           else if (compare_tree_int (op1,
1377                                      TYPE_PRECISION (TREE_TYPE (orig_op0)))
1378                    >= 0)
1379             warning_at (loc, 0, (code == LSHIFT_EXPR
1380                                  ? G_("left shift count >= width of type")
1381                                  : G_("right shift count >= width of type")));
1382         }
1383       if ((code == TRUNC_DIV_EXPR
1384            || code == CEIL_DIV_EXPR
1385            || code == FLOOR_DIV_EXPR
1386            || code == EXACT_DIV_EXPR
1387            || code == TRUNC_MOD_EXPR)
1388           && TREE_CODE (orig_op1) != INTEGER_CST
1389           && TREE_CODE (op1) == INTEGER_CST
1390           && (TREE_CODE (TREE_TYPE (orig_op0)) == INTEGER_TYPE
1391               || TREE_CODE (TREE_TYPE (orig_op0)) == FIXED_POINT_TYPE)
1392           && TREE_CODE (TREE_TYPE (orig_op1)) == INTEGER_TYPE)
1393         warn_for_div_by_zero (loc, op1);
1394       goto out;
1395
1396     case INDIRECT_REF:
1397     case FIX_TRUNC_EXPR:
1398     case FLOAT_EXPR:
1399     CASE_CONVERT:
1400     case ADDR_SPACE_CONVERT_EXPR:
1401     case VIEW_CONVERT_EXPR:
1402     case NON_LVALUE_EXPR:
1403     case NEGATE_EXPR:
1404     case BIT_NOT_EXPR:
1405     case TRUTH_NOT_EXPR:
1406     case ADDR_EXPR:
1407     case CONJ_EXPR:
1408     case REALPART_EXPR:
1409     case IMAGPART_EXPR:
1410       /* Unary operations.  */
1411       orig_op0 = op0 = TREE_OPERAND (expr, 0);
1412       op0 = c_fully_fold_internal (op0, in_init, maybe_const_operands,
1413                                    maybe_const_itself);
1414       STRIP_TYPE_NOPS (op0);
1415       if (code != ADDR_EXPR && code != REALPART_EXPR && code != IMAGPART_EXPR)
1416         op0 = decl_constant_value_for_optimization (op0);
1417       /* ??? Cope with user tricks that amount to offsetof.  The middle-end is
1418          not prepared to deal with them if they occur in initializers.  */
1419       if (op0 != orig_op0
1420           && code == ADDR_EXPR
1421           && (op1 = get_base_address (op0)) != NULL_TREE
1422           && TREE_CODE (op1) == INDIRECT_REF
1423           && TREE_CONSTANT (TREE_OPERAND (op1, 0)))
1424         ret = fold_convert_loc (loc, TREE_TYPE (expr), fold_offsetof_1 (op0));
1425       else if (op0 != orig_op0 || in_init)
1426         ret = in_init
1427           ? fold_build1_initializer_loc (loc, code, TREE_TYPE (expr), op0)
1428           : fold_build1_loc (loc, code, TREE_TYPE (expr), op0);
1429       else
1430         ret = fold (expr);
1431       if (code == INDIRECT_REF
1432           && ret != expr
1433           && TREE_CODE (ret) == INDIRECT_REF)
1434         {
1435           TREE_READONLY (ret) = TREE_READONLY (expr);
1436           TREE_SIDE_EFFECTS (ret) = TREE_SIDE_EFFECTS (expr);
1437           TREE_THIS_VOLATILE (ret) = TREE_THIS_VOLATILE (expr);
1438         }
1439       switch (code)
1440         {
1441         case FIX_TRUNC_EXPR:
1442         case FLOAT_EXPR:
1443         CASE_CONVERT:
1444           /* Don't warn about explicit conversions.  We will already
1445              have warned about suspect implicit conversions.  */
1446           break;
1447
1448         default:
1449           if (TREE_OVERFLOW_P (ret) && !TREE_OVERFLOW_P (op0))
1450             overflow_warning (EXPR_LOCATION (expr), ret);
1451           break;
1452         }
1453       goto out;
1454
1455     case TRUTH_ANDIF_EXPR:
1456     case TRUTH_ORIF_EXPR:
1457       /* Binary operations not necessarily evaluating both
1458          arguments.  */
1459       orig_op0 = op0 = TREE_OPERAND (expr, 0);
1460       orig_op1 = op1 = TREE_OPERAND (expr, 1);
1461       op0 = c_fully_fold_internal (op0, in_init, &op0_const, &op0_const_self);
1462       STRIP_TYPE_NOPS (op0);
1463
1464       unused_p = (op0 == (code == TRUTH_ANDIF_EXPR
1465                           ? truthvalue_false_node
1466                           : truthvalue_true_node));
1467       c_disable_warnings (unused_p);
1468       op1 = c_fully_fold_internal (op1, in_init, &op1_const, &op1_const_self);
1469       STRIP_TYPE_NOPS (op1);
1470       c_enable_warnings (unused_p);
1471
1472       if (op0 != orig_op0 || op1 != orig_op1 || in_init)
1473         ret = in_init
1474           ? fold_build2_initializer_loc (loc, code, TREE_TYPE (expr), op0, op1)
1475           : fold_build2_loc (loc, code, TREE_TYPE (expr), op0, op1);
1476       else
1477         ret = fold (expr);
1478       *maybe_const_operands &= op0_const;
1479       *maybe_const_itself &= op0_const_self;
1480       if (!(flag_isoc99
1481             && op0_const
1482             && op0_const_self
1483             && (code == TRUTH_ANDIF_EXPR
1484                 ? op0 == truthvalue_false_node
1485                 : op0 == truthvalue_true_node)))
1486         *maybe_const_operands &= op1_const;
1487       if (!(op0_const
1488             && op0_const_self
1489             && (code == TRUTH_ANDIF_EXPR
1490                 ? op0 == truthvalue_false_node
1491                 : op0 == truthvalue_true_node)))
1492         *maybe_const_itself &= op1_const_self;
1493       goto out;
1494
1495     case COND_EXPR:
1496       orig_op0 = op0 = TREE_OPERAND (expr, 0);
1497       orig_op1 = op1 = TREE_OPERAND (expr, 1);
1498       orig_op2 = op2 = TREE_OPERAND (expr, 2);
1499       op0 = c_fully_fold_internal (op0, in_init, &op0_const, &op0_const_self);
1500
1501       STRIP_TYPE_NOPS (op0);
1502       c_disable_warnings (op0 == truthvalue_false_node);
1503       op1 = c_fully_fold_internal (op1, in_init, &op1_const, &op1_const_self);
1504       STRIP_TYPE_NOPS (op1);
1505       c_enable_warnings (op0 == truthvalue_false_node);
1506
1507       c_disable_warnings (op0 == truthvalue_true_node);
1508       op2 = c_fully_fold_internal (op2, in_init, &op2_const, &op2_const_self);
1509       STRIP_TYPE_NOPS (op2);
1510       c_enable_warnings (op0 == truthvalue_true_node);
1511
1512       if (op0 != orig_op0 || op1 != orig_op1 || op2 != orig_op2)
1513         ret = fold_build3_loc (loc, code, TREE_TYPE (expr), op0, op1, op2);
1514       else
1515         ret = fold (expr);
1516       *maybe_const_operands &= op0_const;
1517       *maybe_const_itself &= op0_const_self;
1518       if (!(flag_isoc99
1519             && op0_const
1520             && op0_const_self
1521             && op0 == truthvalue_false_node))
1522         *maybe_const_operands &= op1_const;
1523       if (!(op0_const
1524             && op0_const_self
1525             && op0 == truthvalue_false_node))
1526         *maybe_const_itself &= op1_const_self;
1527       if (!(flag_isoc99
1528             && op0_const
1529             && op0_const_self
1530             && op0 == truthvalue_true_node))
1531         *maybe_const_operands &= op2_const;
1532       if (!(op0_const
1533             && op0_const_self
1534             && op0 == truthvalue_true_node))
1535         *maybe_const_itself &= op2_const_self;
1536       goto out;
1537
1538     case EXCESS_PRECISION_EXPR:
1539       /* Each case where an operand with excess precision may be
1540          encountered must remove the EXCESS_PRECISION_EXPR around
1541          inner operands and possibly put one around the whole
1542          expression or possibly convert to the semantic type (which
1543          c_fully_fold does); we cannot tell at this stage which is
1544          appropriate in any particular case.  */
1545       gcc_unreachable ();
1546
1547     default:
1548       /* Various codes may appear through folding built-in functions
1549          and their arguments.  */
1550       goto out;
1551     }
1552
1553  out:
1554   /* Some folding may introduce NON_LVALUE_EXPRs; all lvalue checks
1555      have been done by this point, so remove them again.  */
1556   nowarning |= TREE_NO_WARNING (ret);
1557   STRIP_TYPE_NOPS (ret);
1558   if (nowarning && !TREE_NO_WARNING (ret))
1559     {
1560       if (!CAN_HAVE_LOCATION_P (ret))
1561         ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
1562       TREE_NO_WARNING (ret) = 1;
1563     }
1564   if (ret != expr)
1565     protected_set_expr_location (ret, loc);
1566   return ret;
1567 }
1568
1569 /* If not optimizing, EXP is not a VAR_DECL, or EXP has array type,
1570    return EXP.  Otherwise, return either EXP or its known constant
1571    value (if it has one), but return EXP if EXP has mode BLKmode.  ???
1572    Is the BLKmode test appropriate?  */
1573
1574 tree
1575 decl_constant_value_for_optimization (tree exp)
1576 {
1577   tree ret;
1578
1579   /* This function is only used by C, for c_fully_fold and other
1580      optimization, and may not be correct for C++.  */
1581   if (c_dialect_cxx ())
1582     gcc_unreachable ();
1583
1584   if (!optimize
1585       || TREE_CODE (exp) != VAR_DECL
1586       || TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1587       || DECL_MODE (exp) == BLKmode)
1588     return exp;
1589
1590   ret = decl_constant_value (exp);
1591   /* Avoid unwanted tree sharing between the initializer and current
1592      function's body where the tree can be modified e.g. by the
1593      gimplifier.  */
1594   if (ret != exp && TREE_STATIC (exp))
1595     ret = unshare_expr (ret);
1596   return ret;
1597 }
1598
1599 /* Print a warning if a constant expression had overflow in folding.
1600    Invoke this function on every expression that the language
1601    requires to be a constant expression.
1602    Note the ANSI C standard says it is erroneous for a
1603    constant expression to overflow.  */
1604
1605 void
1606 constant_expression_warning (tree value)
1607 {
1608   if (warn_overflow && pedantic
1609       && (TREE_CODE (value) == INTEGER_CST || TREE_CODE (value) == REAL_CST
1610           || TREE_CODE (value) == FIXED_CST
1611           || TREE_CODE (value) == VECTOR_CST
1612           || TREE_CODE (value) == COMPLEX_CST)
1613       && TREE_OVERFLOW (value))
1614     pedwarn (input_location, OPT_Woverflow, "overflow in constant expression");
1615 }
1616
1617 /* The same as above but print an unconditional error.  */
1618 void
1619 constant_expression_error (tree value)
1620 {
1621   if ((TREE_CODE (value) == INTEGER_CST || TREE_CODE (value) == REAL_CST
1622        || TREE_CODE (value) == FIXED_CST
1623        || TREE_CODE (value) == VECTOR_CST
1624        || TREE_CODE (value) == COMPLEX_CST)
1625       && TREE_OVERFLOW (value))
1626     error ("overflow in constant expression");
1627 }
1628
1629 /* Print a warning if an expression had overflow in folding and its
1630    operands hadn't.
1631
1632    Invoke this function on every expression that
1633    (1) appears in the source code, and
1634    (2) is a constant expression that overflowed, and
1635    (3) is not already checked by convert_and_check;
1636    however, do not invoke this function on operands of explicit casts
1637    or when the expression is the result of an operator and any operand
1638    already overflowed.  */
1639
1640 void
1641 overflow_warning (location_t loc, tree value)
1642 {
1643   if (c_inhibit_evaluation_warnings != 0)
1644     return;
1645
1646   switch (TREE_CODE (value))
1647     {
1648     case INTEGER_CST:
1649       warning_at (loc, OPT_Woverflow, "integer overflow in expression");
1650       break;
1651
1652     case REAL_CST:
1653       warning_at (loc, OPT_Woverflow,
1654                   "floating point overflow in expression");
1655       break;
1656
1657     case FIXED_CST:
1658       warning_at (loc, OPT_Woverflow, "fixed-point overflow in expression");
1659       break;
1660
1661     case VECTOR_CST:
1662       warning_at (loc, OPT_Woverflow, "vector overflow in expression");
1663       break;
1664
1665     case COMPLEX_CST:
1666       if (TREE_CODE (TREE_REALPART (value)) == INTEGER_CST)
1667         warning_at (loc, OPT_Woverflow,
1668                     "complex integer overflow in expression");
1669       else if (TREE_CODE (TREE_REALPART (value)) == REAL_CST)
1670         warning_at (loc, OPT_Woverflow,
1671                     "complex floating point overflow in expression");
1672       break;
1673
1674     default:
1675       break;
1676     }
1677 }
1678
1679 /* Warn about uses of logical || / && operator in a context where it
1680    is likely that the bitwise equivalent was intended by the
1681    programmer.  We have seen an expression in which CODE is a binary
1682    operator used to combine expressions OP_LEFT and OP_RIGHT, which before folding
1683    had CODE_LEFT and CODE_RIGHT, into an expression of type TYPE.  */
1684 void
1685 warn_logical_operator (location_t location, enum tree_code code, tree type,
1686                        enum tree_code code_left, tree op_left,
1687                        enum tree_code ARG_UNUSED (code_right), tree op_right)
1688 {
1689   int or_op = (code == TRUTH_ORIF_EXPR || code == TRUTH_OR_EXPR);
1690   int in0_p, in1_p, in_p;
1691   tree low0, low1, low, high0, high1, high, lhs, rhs, tem;
1692   bool strict_overflow_p = false;
1693
1694   if (code != TRUTH_ANDIF_EXPR
1695       && code != TRUTH_AND_EXPR
1696       && code != TRUTH_ORIF_EXPR
1697       && code != TRUTH_OR_EXPR)
1698     return;
1699
1700   /* Warn if &&/|| are being used in a context where it is
1701      likely that the bitwise equivalent was intended by the
1702      programmer. That is, an expression such as op && MASK
1703      where op should not be any boolean expression, nor a
1704      constant, and mask seems to be a non-boolean integer constant.  */
1705   if (!truth_value_p (code_left)
1706       && INTEGRAL_TYPE_P (TREE_TYPE (op_left))
1707       && !CONSTANT_CLASS_P (op_left)
1708       && !TREE_NO_WARNING (op_left)
1709       && TREE_CODE (op_right) == INTEGER_CST
1710       && !integer_zerop (op_right)
1711       && !integer_onep (op_right))
1712     {
1713       if (or_op)
1714         warning_at (location, OPT_Wlogical_op, "logical %<or%>"
1715                     " applied to non-boolean constant");
1716       else
1717         warning_at (location, OPT_Wlogical_op, "logical %<and%>"
1718                     " applied to non-boolean constant");
1719       TREE_NO_WARNING (op_left) = true;
1720       return;
1721     }
1722
1723   /* We do not warn for constants because they are typical of macro
1724      expansions that test for features.  */
1725   if (CONSTANT_CLASS_P (op_left) || CONSTANT_CLASS_P (op_right))
1726     return;
1727
1728   /* This warning only makes sense with logical operands.  */
1729   if (!(truth_value_p (TREE_CODE (op_left))
1730         || INTEGRAL_TYPE_P (TREE_TYPE (op_left)))
1731       || !(truth_value_p (TREE_CODE (op_right))
1732            || INTEGRAL_TYPE_P (TREE_TYPE (op_right))))
1733     return;
1734
1735   /* The range computations only work with scalars.  */
1736   if (VECTOR_TYPE_P (TREE_TYPE (op_left))
1737       || VECTOR_TYPE_P (TREE_TYPE (op_right)))
1738     return;
1739
1740   /* We first test whether either side separately is trivially true
1741      (with OR) or trivially false (with AND).  If so, do not warn.
1742      This is a common idiom for testing ranges of data types in
1743      portable code.  */
1744   lhs = make_range (op_left, &in0_p, &low0, &high0, &strict_overflow_p);
1745   if (!lhs)
1746     return;
1747   if (TREE_CODE (lhs) == C_MAYBE_CONST_EXPR)
1748     lhs = C_MAYBE_CONST_EXPR_EXPR (lhs);
1749
1750   /* If this is an OR operation, invert both sides; now, the result
1751      should be always false to get a warning.  */
1752   if (or_op)
1753     in0_p = !in0_p;
1754
1755   tem = build_range_check (UNKNOWN_LOCATION, type, lhs, in0_p, low0, high0);
1756   if (tem && integer_zerop (tem))
1757     return;
1758
1759   rhs = make_range (op_right, &in1_p, &low1, &high1, &strict_overflow_p);
1760   if (!rhs)
1761     return;
1762   if (TREE_CODE (rhs) == C_MAYBE_CONST_EXPR)
1763     rhs = C_MAYBE_CONST_EXPR_EXPR (rhs);
1764
1765   /* If this is an OR operation, invert both sides; now, the result
1766      should be always false to get a warning.  */
1767   if (or_op)
1768     in1_p = !in1_p;
1769
1770   tem = build_range_check (UNKNOWN_LOCATION, type, rhs, in1_p, low1, high1);
1771   if (tem && integer_zerop (tem))
1772     return;
1773
1774   /* If both expressions have the same operand, if we can merge the
1775      ranges, and if the range test is always false, then warn.  */
1776   if (operand_equal_p (lhs, rhs, 0)
1777       && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
1778                        in1_p, low1, high1)
1779       && 0 != (tem = build_range_check (UNKNOWN_LOCATION,
1780                                         type, lhs, in_p, low, high))
1781       && integer_zerop (tem))
1782     {
1783       if (or_op)
1784         warning_at (location, OPT_Wlogical_op,
1785                     "logical %<or%> "
1786                     "of collectively exhaustive tests is always true");
1787       else
1788         warning_at (location, OPT_Wlogical_op,
1789                     "logical %<and%> "
1790                     "of mutually exclusive tests is always false");
1791     }
1792 }
1793
1794 /* Warn about logical not used on the left hand side operand of a comparison.
1795    This function assumes that the LHS is inside of TRUTH_NOT_EXPR.
1796    Do not warn if RHS is of a boolean type.  */
1797
1798 void
1799 warn_logical_not_parentheses (location_t location, enum tree_code code,
1800                               tree rhs)
1801 {
1802   if (TREE_CODE_CLASS (code) != tcc_comparison
1803       || TREE_TYPE (rhs) == NULL_TREE
1804       || TREE_CODE (TREE_TYPE (rhs)) == BOOLEAN_TYPE)
1805     return;
1806
1807   /* Don't warn for !x == 0 or !y != 0, those are equivalent to
1808      !(x == 0) or !(y != 0).  */
1809   if ((code == EQ_EXPR || code == NE_EXPR)
1810       && integer_zerop (rhs))
1811     return;
1812
1813   warning_at (location, OPT_Wlogical_not_parentheses,
1814               "logical not is only applied to the left hand side of "
1815               "comparison");
1816 }
1817
1818 /* Warn if EXP contains any computations whose results are not used.
1819    Return true if a warning is printed; false otherwise.  LOCUS is the
1820    (potential) location of the expression.  */
1821
1822 bool
1823 warn_if_unused_value (const_tree exp, location_t locus)
1824 {
1825  restart:
1826   if (TREE_USED (exp) || TREE_NO_WARNING (exp))
1827     return false;
1828
1829   /* Don't warn about void constructs.  This includes casting to void,
1830      void function calls, and statement expressions with a final cast
1831      to void.  */
1832   if (VOID_TYPE_P (TREE_TYPE (exp)))
1833     return false;
1834
1835   if (EXPR_HAS_LOCATION (exp))
1836     locus = EXPR_LOCATION (exp);
1837
1838   switch (TREE_CODE (exp))
1839     {
1840     case PREINCREMENT_EXPR:
1841     case POSTINCREMENT_EXPR:
1842     case PREDECREMENT_EXPR:
1843     case POSTDECREMENT_EXPR:
1844     case MODIFY_EXPR:
1845     case INIT_EXPR:
1846     case TARGET_EXPR:
1847     case CALL_EXPR:
1848     case TRY_CATCH_EXPR:
1849     case WITH_CLEANUP_EXPR:
1850     case EXIT_EXPR:
1851     case VA_ARG_EXPR:
1852       return false;
1853
1854     case BIND_EXPR:
1855       /* For a binding, warn if no side effect within it.  */
1856       exp = BIND_EXPR_BODY (exp);
1857       goto restart;
1858
1859     case SAVE_EXPR:
1860     case NON_LVALUE_EXPR:
1861     case NOP_EXPR:
1862       exp = TREE_OPERAND (exp, 0);
1863       goto restart;
1864
1865     case TRUTH_ORIF_EXPR:
1866     case TRUTH_ANDIF_EXPR:
1867       /* In && or ||, warn if 2nd operand has no side effect.  */
1868       exp = TREE_OPERAND (exp, 1);
1869       goto restart;
1870
1871     case COMPOUND_EXPR:
1872       if (warn_if_unused_value (TREE_OPERAND (exp, 0), locus))
1873         return true;
1874       /* Let people do `(foo (), 0)' without a warning.  */
1875       if (TREE_CONSTANT (TREE_OPERAND (exp, 1)))
1876         return false;
1877       exp = TREE_OPERAND (exp, 1);
1878       goto restart;
1879
1880     case COND_EXPR:
1881       /* If this is an expression with side effects, don't warn; this
1882          case commonly appears in macro expansions.  */
1883       if (TREE_SIDE_EFFECTS (exp))
1884         return false;
1885       goto warn;
1886
1887     case INDIRECT_REF:
1888       /* Don't warn about automatic dereferencing of references, since
1889          the user cannot control it.  */
1890       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == REFERENCE_TYPE)
1891         {
1892           exp = TREE_OPERAND (exp, 0);
1893           goto restart;
1894         }
1895       /* Fall through.  */
1896
1897     default:
1898       /* Referencing a volatile value is a side effect, so don't warn.  */
1899       if ((DECL_P (exp) || REFERENCE_CLASS_P (exp))
1900           && TREE_THIS_VOLATILE (exp))
1901         return false;
1902
1903       /* If this is an expression which has no operands, there is no value
1904          to be unused.  There are no such language-independent codes,
1905          but front ends may define such.  */
1906       if (EXPRESSION_CLASS_P (exp) && TREE_OPERAND_LENGTH (exp) == 0)
1907         return false;
1908
1909     warn:
1910       return warning_at (locus, OPT_Wunused_value, "value computed is not used");
1911     }
1912 }
1913
1914
1915 /* Print a warning about casts that might indicate violation
1916    of strict aliasing rules if -Wstrict-aliasing is used and
1917    strict aliasing mode is in effect. OTYPE is the original
1918    TREE_TYPE of EXPR, and TYPE the type we're casting to. */
1919
1920 bool
1921 strict_aliasing_warning (tree otype, tree type, tree expr)
1922 {
1923   /* Strip pointer conversion chains and get to the correct original type.  */
1924   STRIP_NOPS (expr);
1925   otype = TREE_TYPE (expr);
1926
1927   if (!(flag_strict_aliasing
1928         && POINTER_TYPE_P (type)
1929         && POINTER_TYPE_P (otype)
1930         && !VOID_TYPE_P (TREE_TYPE (type)))
1931       /* If the type we are casting to is a ref-all pointer
1932          dereferencing it is always valid.  */
1933       || TYPE_REF_CAN_ALIAS_ALL (type))
1934     return false;
1935
1936   if ((warn_strict_aliasing > 1) && TREE_CODE (expr) == ADDR_EXPR
1937       && (DECL_P (TREE_OPERAND (expr, 0))
1938           || handled_component_p (TREE_OPERAND (expr, 0))))
1939     {
1940       /* Casting the address of an object to non void pointer. Warn
1941          if the cast breaks type based aliasing.  */
1942       if (!COMPLETE_TYPE_P (TREE_TYPE (type)) && warn_strict_aliasing == 2)
1943         {
1944           warning (OPT_Wstrict_aliasing, "type-punning to incomplete type "
1945                    "might break strict-aliasing rules");
1946           return true;
1947         }
1948       else
1949         {
1950           /* warn_strict_aliasing >= 3.   This includes the default (3).
1951              Only warn if the cast is dereferenced immediately.  */
1952           alias_set_type set1 =
1953             get_alias_set (TREE_TYPE (TREE_OPERAND (expr, 0)));
1954           alias_set_type set2 = get_alias_set (TREE_TYPE (type));
1955
1956           if (set1 != set2 && set2 != 0
1957               && (set1 == 0 || !alias_sets_conflict_p (set1, set2)))
1958             {
1959               warning (OPT_Wstrict_aliasing, "dereferencing type-punned "
1960                        "pointer will break strict-aliasing rules");
1961               return true;
1962             }
1963           else if (warn_strict_aliasing == 2
1964                    && !alias_sets_must_conflict_p (set1, set2))
1965             {
1966               warning (OPT_Wstrict_aliasing, "dereferencing type-punned "
1967                        "pointer might break strict-aliasing rules");
1968               return true;
1969             }
1970         }
1971     }
1972   else
1973     if ((warn_strict_aliasing == 1) && !VOID_TYPE_P (TREE_TYPE (otype)))
1974       {
1975         /* At this level, warn for any conversions, even if an address is
1976            not taken in the same statement.  This will likely produce many
1977            false positives, but could be useful to pinpoint problems that
1978            are not revealed at higher levels.  */
1979         alias_set_type set1 = get_alias_set (TREE_TYPE (otype));
1980         alias_set_type set2 = get_alias_set (TREE_TYPE (type));
1981         if (!COMPLETE_TYPE_P (type)
1982             || !alias_sets_must_conflict_p (set1, set2))
1983           {
1984             warning (OPT_Wstrict_aliasing, "dereferencing type-punned "
1985                      "pointer might break strict-aliasing rules");
1986             return true;
1987           }
1988       }
1989
1990   return false;
1991 }
1992
1993 /* Warn about memset (&a, 0, sizeof (&a)); and similar mistakes with
1994    sizeof as last operand of certain builtins.  */
1995
1996 void
1997 sizeof_pointer_memaccess_warning (location_t *sizeof_arg_loc, tree callee,
1998                                   vec<tree, va_gc> *params, tree *sizeof_arg,
1999                                   bool (*comp_types) (tree, tree))
2000 {
2001   tree type, dest = NULL_TREE, src = NULL_TREE, tem;
2002   bool strop = false, cmp = false;
2003   unsigned int idx = ~0;
2004   location_t loc;
2005
2006   if (TREE_CODE (callee) != FUNCTION_DECL
2007       || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL
2008       || vec_safe_length (params) <= 1)
2009     return;
2010
2011   switch (DECL_FUNCTION_CODE (callee))
2012     {
2013     case BUILT_IN_STRNCMP:
2014     case BUILT_IN_STRNCASECMP:
2015       cmp = true;
2016       /* FALLTHRU */
2017     case BUILT_IN_STRNCPY:
2018     case BUILT_IN_STRNCPY_CHK:
2019     case BUILT_IN_STRNCAT:
2020     case BUILT_IN_STRNCAT_CHK:
2021     case BUILT_IN_STPNCPY:
2022     case BUILT_IN_STPNCPY_CHK:
2023       strop = true;
2024       /* FALLTHRU */
2025     case BUILT_IN_MEMCPY:
2026     case BUILT_IN_MEMCPY_CHK:
2027     case BUILT_IN_MEMMOVE:
2028     case BUILT_IN_MEMMOVE_CHK:
2029       if (params->length () < 3)
2030         return;
2031       src = (*params)[1];
2032       dest = (*params)[0];
2033       idx = 2;
2034       break;
2035     case BUILT_IN_BCOPY:
2036       if (params->length () < 3)
2037         return;
2038       src = (*params)[0];
2039       dest = (*params)[1];
2040       idx = 2;
2041       break;
2042     case BUILT_IN_MEMCMP:
2043     case BUILT_IN_BCMP:
2044       if (params->length () < 3)
2045         return;
2046       src = (*params)[1];
2047       dest = (*params)[0];
2048       idx = 2;
2049       cmp = true;
2050       break;
2051     case BUILT_IN_MEMSET:
2052     case BUILT_IN_MEMSET_CHK:
2053       if (params->length () < 3)
2054         return;
2055       dest = (*params)[0];
2056       idx = 2;
2057       break;
2058     case BUILT_IN_BZERO:
2059       dest = (*params)[0];
2060       idx = 1;
2061       break;
2062     case BUILT_IN_STRNDUP:
2063       src = (*params)[0];
2064       strop = true;
2065       idx = 1;
2066       break;
2067     case BUILT_IN_MEMCHR:
2068       if (params->length () < 3)
2069         return;
2070       src = (*params)[0];
2071       idx = 2;
2072       break;
2073     case BUILT_IN_SNPRINTF:
2074     case BUILT_IN_SNPRINTF_CHK:
2075     case BUILT_IN_VSNPRINTF:
2076     case BUILT_IN_VSNPRINTF_CHK:
2077       dest = (*params)[0];
2078       idx = 1;
2079       strop = true;
2080       break;
2081     default:
2082       break;
2083     }
2084
2085   if (idx >= 3)
2086     return;
2087
2088   if (sizeof_arg[idx] == NULL || sizeof_arg[idx] == error_mark_node)
2089     return;
2090
2091   type = TYPE_P (sizeof_arg[idx])
2092          ? sizeof_arg[idx] : TREE_TYPE (sizeof_arg[idx]);
2093   if (!POINTER_TYPE_P (type))
2094     return;
2095
2096   if (dest
2097       && (tem = tree_strip_nop_conversions (dest))
2098       && POINTER_TYPE_P (TREE_TYPE (tem))
2099       && comp_types (TREE_TYPE (TREE_TYPE (tem)), type))
2100     return;
2101
2102   if (src
2103       && (tem = tree_strip_nop_conversions (src))
2104       && POINTER_TYPE_P (TREE_TYPE (tem))
2105       && comp_types (TREE_TYPE (TREE_TYPE (tem)), type))
2106     return;
2107
2108   loc = sizeof_arg_loc[idx];
2109
2110   if (dest && !cmp)
2111     {
2112       if (!TYPE_P (sizeof_arg[idx])
2113           && operand_equal_p (dest, sizeof_arg[idx], 0)
2114           && comp_types (TREE_TYPE (dest), type))
2115         {
2116           if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
2117             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2118                         "argument to %<sizeof%> in %qD call is the same "
2119                         "expression as the destination; did you mean to "
2120                         "remove the addressof?", callee);
2121           else if ((TYPE_PRECISION (TREE_TYPE (type))
2122                     == TYPE_PRECISION (char_type_node))
2123                    || strop)
2124             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2125                         "argument to %<sizeof%> in %qD call is the same "
2126                         "expression as the destination; did you mean to "
2127                         "provide an explicit length?", callee);
2128           else
2129             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2130                         "argument to %<sizeof%> in %qD call is the same "
2131                         "expression as the destination; did you mean to "
2132                         "dereference it?", callee);
2133           return;
2134         }
2135
2136       if (POINTER_TYPE_P (TREE_TYPE (dest))
2137           && !strop
2138           && comp_types (TREE_TYPE (dest), type)
2139           && !VOID_TYPE_P (TREE_TYPE (type)))
2140         {
2141           warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2142                       "argument to %<sizeof%> in %qD call is the same "
2143                       "pointer type %qT as the destination; expected %qT "
2144                       "or an explicit length", callee, TREE_TYPE (dest),
2145                       TREE_TYPE (TREE_TYPE (dest)));
2146           return;
2147         }
2148     }
2149
2150   if (src && !cmp)
2151     {
2152       if (!TYPE_P (sizeof_arg[idx])
2153           && operand_equal_p (src, sizeof_arg[idx], 0)
2154           && comp_types (TREE_TYPE (src), type))
2155         {
2156           if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
2157             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2158                         "argument to %<sizeof%> in %qD call is the same "
2159                         "expression as the source; did you mean to "
2160                         "remove the addressof?", callee);
2161           else if ((TYPE_PRECISION (TREE_TYPE (type))
2162                     == TYPE_PRECISION (char_type_node))
2163                    || strop)
2164             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2165                         "argument to %<sizeof%> in %qD call is the same "
2166                         "expression as the source; did you mean to "
2167                         "provide an explicit length?", callee);
2168           else
2169             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2170                         "argument to %<sizeof%> in %qD call is the same "
2171                         "expression as the source; did you mean to "
2172                         "dereference it?", callee);
2173           return;
2174         }
2175
2176       if (POINTER_TYPE_P (TREE_TYPE (src))
2177           && !strop
2178           && comp_types (TREE_TYPE (src), type)
2179           && !VOID_TYPE_P (TREE_TYPE (type)))
2180         {
2181           warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2182                       "argument to %<sizeof%> in %qD call is the same "
2183                       "pointer type %qT as the source; expected %qT "
2184                       "or an explicit length", callee, TREE_TYPE (src),
2185                       TREE_TYPE (TREE_TYPE (src)));
2186           return;
2187         }
2188     }
2189
2190   if (dest)
2191     {
2192       if (!TYPE_P (sizeof_arg[idx])
2193           && operand_equal_p (dest, sizeof_arg[idx], 0)
2194           && comp_types (TREE_TYPE (dest), type))
2195         {
2196           if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
2197             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2198                         "argument to %<sizeof%> in %qD call is the same "
2199                         "expression as the first source; did you mean to "
2200                         "remove the addressof?", callee);
2201           else if ((TYPE_PRECISION (TREE_TYPE (type))
2202                     == TYPE_PRECISION (char_type_node))
2203                    || strop)
2204             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2205                         "argument to %<sizeof%> in %qD call is the same "
2206                         "expression as the first source; did you mean to "
2207                         "provide an explicit length?", callee);
2208           else
2209             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2210                         "argument to %<sizeof%> in %qD call is the same "
2211                         "expression as the first source; did you mean to "
2212                         "dereference it?", callee);
2213           return;
2214         }
2215
2216       if (POINTER_TYPE_P (TREE_TYPE (dest))
2217           && !strop
2218           && comp_types (TREE_TYPE (dest), type)
2219           && !VOID_TYPE_P (TREE_TYPE (type)))
2220         {
2221           warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2222                       "argument to %<sizeof%> in %qD call is the same "
2223                       "pointer type %qT as the first source; expected %qT "
2224                       "or an explicit length", callee, TREE_TYPE (dest),
2225                       TREE_TYPE (TREE_TYPE (dest)));
2226           return;
2227         }
2228     }
2229
2230   if (src)
2231     {
2232       if (!TYPE_P (sizeof_arg[idx])
2233           && operand_equal_p (src, sizeof_arg[idx], 0)
2234           && comp_types (TREE_TYPE (src), type))
2235         {
2236           if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
2237             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2238                         "argument to %<sizeof%> in %qD call is the same "
2239                         "expression as the second source; did you mean to "
2240                         "remove the addressof?", callee);
2241           else if ((TYPE_PRECISION (TREE_TYPE (type))
2242                     == TYPE_PRECISION (char_type_node))
2243                    || strop)
2244             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2245                         "argument to %<sizeof%> in %qD call is the same "
2246                         "expression as the second source; did you mean to "
2247                         "provide an explicit length?", callee);
2248           else
2249             warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2250                         "argument to %<sizeof%> in %qD call is the same "
2251                         "expression as the second source; did you mean to "
2252                         "dereference it?", callee);
2253           return;
2254         }
2255
2256       if (POINTER_TYPE_P (TREE_TYPE (src))
2257           && !strop
2258           && comp_types (TREE_TYPE (src), type)
2259           && !VOID_TYPE_P (TREE_TYPE (type)))
2260         {
2261           warning_at (loc, OPT_Wsizeof_pointer_memaccess,
2262                       "argument to %<sizeof%> in %qD call is the same "
2263                       "pointer type %qT as the second source; expected %qT "
2264                       "or an explicit length", callee, TREE_TYPE (src),
2265                       TREE_TYPE (TREE_TYPE (src)));
2266           return;
2267         }
2268     }
2269
2270 }
2271
2272 /* Warn for unlikely, improbable, or stupid DECL declarations
2273    of `main'.  */
2274
2275 void
2276 check_main_parameter_types (tree decl)
2277 {
2278   function_args_iterator iter;
2279   tree type;
2280   int argct = 0;
2281
2282   FOREACH_FUNCTION_ARGS (TREE_TYPE (decl), type, iter)
2283     {
2284       /* XXX void_type_node belies the abstraction.  */
2285       if (type == void_type_node || type == error_mark_node )
2286         break;
2287
2288       tree t = type;
2289       if (TYPE_ATOMIC (t))
2290           pedwarn (input_location, OPT_Wmain,
2291                    "%<_Atomic%>-qualified parameter type %qT of %q+D",
2292                    type, decl);
2293       while (POINTER_TYPE_P (t))
2294         {
2295           t = TREE_TYPE (t);
2296           if (TYPE_ATOMIC (t))
2297             pedwarn (input_location, OPT_Wmain,
2298                      "%<_Atomic%>-qualified parameter type %qT of %q+D",
2299                      type, decl);
2300         }
2301
2302       ++argct;
2303       switch (argct)
2304         {
2305         case 1:
2306           if (TYPE_MAIN_VARIANT (type) != integer_type_node)
2307             pedwarn (input_location, OPT_Wmain,
2308                      "first argument of %q+D should be %<int%>", decl);
2309           break;
2310
2311         case 2:
2312           if (TREE_CODE (type) != POINTER_TYPE
2313               || TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
2314               || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
2315                   != char_type_node))
2316             pedwarn (input_location, OPT_Wmain,
2317                      "second argument of %q+D should be %<char **%>", decl);
2318           break;
2319
2320         case 3:
2321           if (TREE_CODE (type) != POINTER_TYPE
2322               || TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
2323               || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
2324                   != char_type_node))
2325             pedwarn (input_location, OPT_Wmain,
2326                      "third argument of %q+D should probably be "
2327                      "%<char **%>", decl);
2328           break;
2329         }
2330     }
2331
2332   /* It is intentional that this message does not mention the third
2333     argument because it's only mentioned in an appendix of the
2334     standard.  */
2335   if (argct > 0 && (argct < 2 || argct > 3))
2336     pedwarn (input_location, OPT_Wmain,
2337              "%q+D takes only zero or two arguments", decl);
2338
2339   if (stdarg_p (TREE_TYPE (decl)))
2340     pedwarn (input_location, OPT_Wmain,
2341              "%q+D declared as variadic function", decl);
2342 }
2343
2344 /* vector_targets_convertible_p is used for vector pointer types.  The
2345    callers perform various checks that the qualifiers are satisfactory,
2346    while OTOH vector_targets_convertible_p ignores the number of elements
2347    in the vectors.  That's fine with vector pointers as we can consider,
2348    say, a vector of 8 elements as two consecutive vectors of 4 elements,
2349    and that does not require and conversion of the pointer values.
2350    In contrast, vector_types_convertible_p and
2351    vector_types_compatible_elements_p are used for vector value types.  */
2352 /* True if pointers to distinct types T1 and T2 can be converted to
2353    each other without an explicit cast.  Only returns true for opaque
2354    vector types.  */
2355 bool
2356 vector_targets_convertible_p (const_tree t1, const_tree t2)
2357 {
2358   if (TREE_CODE (t1) == VECTOR_TYPE && TREE_CODE (t2) == VECTOR_TYPE
2359       && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
2360       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
2361     return true;
2362
2363   return false;
2364 }
2365
2366 /* vector_types_convertible_p is used for vector value types.
2367    It could in principle call vector_targets_convertible_p as a subroutine,
2368    but then the check for vector type would be duplicated with its callers,
2369    and also the purpose of vector_targets_convertible_p would become
2370    muddled.
2371    Where vector_types_convertible_p returns true, a conversion might still be
2372    needed to make the types match.
2373    In contrast, vector_targets_convertible_p is used for vector pointer
2374    values, and vector_types_compatible_elements_p is used specifically
2375    in the context for binary operators, as a check if use is possible without
2376    conversion.  */
2377 /* True if vector types T1 and T2 can be converted to each other
2378    without an explicit cast.  If EMIT_LAX_NOTE is true, and T1 and T2
2379    can only be converted with -flax-vector-conversions yet that is not
2380    in effect, emit a note telling the user about that option if such
2381    a note has not previously been emitted.  */
2382 bool
2383 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
2384 {
2385   static bool emitted_lax_note = false;
2386   bool convertible_lax;
2387
2388   if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
2389       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
2390     return true;
2391
2392   convertible_lax =
2393     (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
2394      && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE ||
2395          TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2))
2396      && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
2397          == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
2398
2399   if (!convertible_lax || flag_lax_vector_conversions)
2400     return convertible_lax;
2401
2402   if (TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2)
2403       && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
2404     return true;
2405
2406   if (emit_lax_note && !emitted_lax_note)
2407     {
2408       emitted_lax_note = true;
2409       inform (input_location, "use -flax-vector-conversions to permit "
2410               "conversions between vectors with differing "
2411               "element types or numbers of subparts");
2412     }
2413
2414   return false;
2415 }
2416
2417 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
2418    and have vector types, V0 has the same type as V1, and the number of
2419    elements of V0, V1, MASK is the same.
2420
2421    In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
2422    called with two arguments.  In this case implementation passes the
2423    first argument twice in order to share the same tree code.  This fact
2424    could enable the mask-values being twice the vector length.  This is
2425    an implementation accident and this semantics is not guaranteed to
2426    the user.  */
2427 tree
2428 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
2429                        bool complain)
2430 {
2431   tree ret;
2432   bool wrap = true;
2433   bool maybe_const = false;
2434   bool two_arguments = false;
2435
2436   if (v1 == NULL_TREE)
2437     {
2438       two_arguments = true;
2439       v1 = v0;
2440     }
2441
2442   if (v0 == error_mark_node || v1 == error_mark_node
2443       || mask == error_mark_node)
2444     return error_mark_node;
2445
2446   if (TREE_CODE (TREE_TYPE (mask)) != VECTOR_TYPE
2447       || TREE_CODE (TREE_TYPE (TREE_TYPE (mask))) != INTEGER_TYPE)
2448     {
2449       if (complain)
2450         error_at (loc, "__builtin_shuffle last argument must "
2451                        "be an integer vector");
2452       return error_mark_node;
2453     }
2454
2455   if (TREE_CODE (TREE_TYPE (v0)) != VECTOR_TYPE
2456       || TREE_CODE (TREE_TYPE (v1)) != VECTOR_TYPE)
2457     {
2458       if (complain)
2459         error_at (loc, "__builtin_shuffle arguments must be vectors");
2460       return error_mark_node;
2461     }
2462
2463   if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
2464     {
2465       if (complain)
2466         error_at (loc, "__builtin_shuffle argument vectors must be of "
2467                        "the same type");
2468       return error_mark_node;
2469     }
2470
2471   if (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0))
2472       != TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))
2473       && TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1))
2474          != TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
2475     {
2476       if (complain)
2477         error_at (loc, "__builtin_shuffle number of elements of the "
2478                        "argument vector(s) and the mask vector should "
2479                        "be the same");
2480       return error_mark_node;
2481     }
2482
2483   if (GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
2484       != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
2485     {
2486       if (complain)
2487         error_at (loc, "__builtin_shuffle argument vector(s) inner type "
2488                        "must have the same size as inner type of the mask");
2489       return error_mark_node;
2490     }
2491
2492   if (!c_dialect_cxx ())
2493     {
2494       /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR.  */
2495       v0 = c_fully_fold (v0, false, &maybe_const);
2496       wrap &= maybe_const;
2497
2498       if (two_arguments)
2499         v1 = v0 = save_expr (v0);
2500       else
2501         {
2502           v1 = c_fully_fold (v1, false, &maybe_const);
2503           wrap &= maybe_const;
2504         }
2505
2506       mask = c_fully_fold (mask, false, &maybe_const);
2507       wrap &= maybe_const;
2508     }
2509   else if (two_arguments)
2510     v1 = v0 = save_expr (v0);
2511
2512   ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
2513
2514   if (!c_dialect_cxx () && !wrap)
2515     ret = c_wrap_maybe_const (ret, true);
2516
2517   return ret;
2518 }
2519
2520 /* Like tree.c:get_narrower, but retain conversion from C++0x scoped enum
2521    to integral type.  */
2522
2523 static tree
2524 c_common_get_narrower (tree op, int *unsignedp_ptr)
2525 {
2526   op = get_narrower (op, unsignedp_ptr);
2527
2528   if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
2529       && ENUM_IS_SCOPED (TREE_TYPE (op)))
2530     {
2531       /* C++0x scoped enumerations don't implicitly convert to integral
2532          type; if we stripped an explicit conversion to a larger type we
2533          need to replace it so common_type will still work.  */
2534       tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
2535                                           TYPE_UNSIGNED (TREE_TYPE (op)));
2536       op = fold_convert (type, op);
2537     }
2538   return op;
2539 }
2540
2541 /* This is a helper function of build_binary_op.
2542
2543    For certain operations if both args were extended from the same
2544    smaller type, do the arithmetic in that type and then extend.
2545
2546    BITWISE indicates a bitwise operation.
2547    For them, this optimization is safe only if
2548    both args are zero-extended or both are sign-extended.
2549    Otherwise, we might change the result.
2550    Eg, (short)-1 | (unsigned short)-1 is (int)-1
2551    but calculated in (unsigned short) it would be (unsigned short)-1.
2552 */
2553 tree
2554 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
2555 {
2556   int unsigned0, unsigned1;
2557   tree arg0, arg1;
2558   int uns;
2559   tree type;
2560
2561   /* Cast OP0 and OP1 to RESULT_TYPE.  Doing so prevents
2562      excessive narrowing when we call get_narrower below.  For
2563      example, suppose that OP0 is of unsigned int extended
2564      from signed char and that RESULT_TYPE is long long int.
2565      If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
2566      like
2567
2568      (long long int) (unsigned int) signed_char
2569
2570      which get_narrower would narrow down to
2571
2572      (unsigned int) signed char
2573
2574      If we do not cast OP0 first, get_narrower would return
2575      signed_char, which is inconsistent with the case of the
2576      explicit cast.  */
2577   op0 = convert (result_type, op0);
2578   op1 = convert (result_type, op1);
2579
2580   arg0 = c_common_get_narrower (op0, &unsigned0);
2581   arg1 = c_common_get_narrower (op1, &unsigned1);
2582
2583   /* UNS is 1 if the operation to be done is an unsigned one.  */
2584   uns = TYPE_UNSIGNED (result_type);
2585
2586   /* Handle the case that OP0 (or OP1) does not *contain* a conversion
2587      but it *requires* conversion to FINAL_TYPE.  */
2588
2589   if ((TYPE_PRECISION (TREE_TYPE (op0))
2590        == TYPE_PRECISION (TREE_TYPE (arg0)))
2591       && TREE_TYPE (op0) != result_type)
2592     unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2593   if ((TYPE_PRECISION (TREE_TYPE (op1))
2594        == TYPE_PRECISION (TREE_TYPE (arg1)))
2595       && TREE_TYPE (op1) != result_type)
2596     unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2597
2598   /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE.  */
2599
2600   /* For bitwise operations, signedness of nominal type
2601      does not matter.  Consider only how operands were extended.  */
2602   if (bitwise)
2603     uns = unsigned0;
2604
2605   /* Note that in all three cases below we refrain from optimizing
2606      an unsigned operation on sign-extended args.
2607      That would not be valid.  */
2608
2609   /* Both args variable: if both extended in same way
2610      from same width, do it in that width.
2611      Do it unsigned if args were zero-extended.  */
2612   if ((TYPE_PRECISION (TREE_TYPE (arg0))
2613        < TYPE_PRECISION (result_type))
2614       && (TYPE_PRECISION (TREE_TYPE (arg1))
2615           == TYPE_PRECISION (TREE_TYPE (arg0)))
2616       && unsigned0 == unsigned1
2617       && (unsigned0 || !uns))
2618     return c_common_signed_or_unsigned_type
2619       (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
2620
2621   else if (TREE_CODE (arg0) == INTEGER_CST
2622            && (unsigned1 || !uns)
2623            && (TYPE_PRECISION (TREE_TYPE (arg1))
2624                < TYPE_PRECISION (result_type))
2625            && (type
2626                = c_common_signed_or_unsigned_type (unsigned1,
2627                                                    TREE_TYPE (arg1)))
2628            && !POINTER_TYPE_P (type)
2629            && int_fits_type_p (arg0, type))
2630     return type;
2631
2632   else if (TREE_CODE (arg1) == INTEGER_CST
2633            && (unsigned0 || !uns)
2634            && (TYPE_PRECISION (TREE_TYPE (arg0))
2635                < TYPE_PRECISION (result_type))
2636            && (type
2637                = c_common_signed_or_unsigned_type (unsigned0,
2638                                                    TREE_TYPE (arg0)))
2639            && !POINTER_TYPE_P (type)
2640            && int_fits_type_p (arg1, type))
2641     return type;
2642
2643   return result_type;
2644 }
2645
2646 /* Checks if expression EXPR of real/integer type cannot be converted
2647    to the real/integer type TYPE. Function returns non-zero when:
2648         * EXPR is a constant which cannot be exactly converted to TYPE.
2649         * EXPR is not a constant and size of EXPR's type > than size of TYPE,
2650           for EXPR type and TYPE being both integers or both real.
2651         * EXPR is not a constant of real type and TYPE is an integer.
2652         * EXPR is not a constant of integer type which cannot be
2653           exactly converted to real type.
2654    Function allows conversions between types of different signedness and
2655    can return SAFE_CONVERSION (zero) in that case.  Function can produce
2656    signedness warnings if PRODUCE_WARNS is true.  */
2657
2658 enum conversion_safety
2659 unsafe_conversion_p (location_t loc, tree type, tree expr, bool produce_warns)
2660 {
2661   enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
2662   tree expr_type = TREE_TYPE (expr);
2663   loc = expansion_point_location_if_in_system_header (loc);
2664
2665   if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
2666     {
2667       /* Warn for real constant that is not an exact integer converted
2668          to integer type.  */
2669       if (TREE_CODE (expr_type) == REAL_TYPE
2670           && TREE_CODE (type) == INTEGER_TYPE)
2671         {
2672           if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
2673             give_warning = UNSAFE_REAL;
2674         }
2675       /* Warn for an integer constant that does not fit into integer type.  */
2676       else if (TREE_CODE (expr_type) == INTEGER_TYPE
2677                && TREE_CODE (type) == INTEGER_TYPE
2678                && !int_fits_type_p (expr, type))
2679         {
2680           if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
2681               && tree_int_cst_sgn (expr) < 0)
2682             {
2683               if (produce_warns)
2684                 warning_at (loc, OPT_Wsign_conversion, "negative integer"
2685                             " implicitly converted to unsigned type");
2686             }
2687           else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
2688             {
2689               if (produce_warns)
2690                 warning_at (loc, OPT_Wsign_conversion, "conversion of unsigned"
2691                             " constant value to negative integer");
2692             }
2693           else
2694             give_warning = UNSAFE_OTHER;
2695         }
2696       else if (TREE_CODE (type) == REAL_TYPE)
2697         {
2698           /* Warn for an integer constant that does not fit into real type.  */
2699           if (TREE_CODE (expr_type) == INTEGER_TYPE)
2700             {
2701               REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
2702               if (!exact_real_truncate (TYPE_MODE (type), &a))
2703                 give_warning = UNSAFE_REAL;
2704             }
2705           /* Warn for a real constant that does not fit into a smaller
2706              real type.  */
2707           else if (TREE_CODE (expr_type) == REAL_TYPE
2708                    && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
2709             {
2710               REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
2711               if (!exact_real_truncate (TYPE_MODE (type), &a))
2712                 give_warning = UNSAFE_REAL;
2713             }
2714         }
2715     }
2716   else
2717     {
2718       /* Warn for real types converted to integer types.  */
2719       if (TREE_CODE (expr_type) == REAL_TYPE
2720           && TREE_CODE (type) == INTEGER_TYPE)
2721         give_warning = UNSAFE_REAL;
2722
2723       else if (TREE_CODE (expr_type) == INTEGER_TYPE
2724                && TREE_CODE (type) == INTEGER_TYPE)
2725         {
2726           /* Don't warn about unsigned char y = 0xff, x = (int) y;  */
2727           expr = get_unwidened (expr, 0);
2728           expr_type = TREE_TYPE (expr);
2729
2730           /* Don't warn for short y; short x = ((int)y & 0xff);  */
2731           if (TREE_CODE (expr) == BIT_AND_EXPR
2732               || TREE_CODE (expr) == BIT_IOR_EXPR
2733               || TREE_CODE (expr) == BIT_XOR_EXPR)
2734             {
2735               /* If both args were extended from a shortest type,
2736                  use that type if that is safe.  */
2737               expr_type = shorten_binary_op (expr_type,
2738                                              TREE_OPERAND (expr, 0),
2739                                              TREE_OPERAND (expr, 1),
2740                                              /* bitwise */1);
2741
2742               if (TREE_CODE (expr) == BIT_AND_EXPR)
2743                 {
2744                   tree op0 = TREE_OPERAND (expr, 0);
2745                   tree op1 = TREE_OPERAND (expr, 1);
2746                   bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2747                   bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2748
2749                   /* If one of the operands is a non-negative constant
2750                      that fits in the target type, then the type of the
2751                      other operand does not matter. */
2752                   if ((TREE_CODE (op0) == INTEGER_CST
2753                        && int_fits_type_p (op0, c_common_signed_type (type))
2754                        && int_fits_type_p (op0, c_common_unsigned_type (type)))
2755                       || (TREE_CODE (op1) == INTEGER_CST
2756                           && int_fits_type_p (op1, c_common_signed_type (type))
2757                           && int_fits_type_p (op1,
2758                                               c_common_unsigned_type (type))))
2759                     return SAFE_CONVERSION;
2760                   /* If constant is unsigned and fits in the target
2761                      type, then the result will also fit.  */
2762                   else if ((TREE_CODE (op0) == INTEGER_CST
2763                             && unsigned0
2764                             && int_fits_type_p (op0, type))
2765                            || (TREE_CODE (op1) == INTEGER_CST
2766                                && unsigned1
2767                                && int_fits_type_p (op1, type)))
2768                     return SAFE_CONVERSION;
2769                 }
2770             }
2771           /* Warn for integer types converted to smaller integer types.  */
2772           if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
2773             give_warning = UNSAFE_OTHER;
2774
2775           /* When they are the same width but different signedness,
2776              then the value may change.  */
2777           else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
2778                     && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
2779                    /* Even when converted to a bigger type, if the type is
2780                       unsigned but expr is signed, then negative values
2781                       will be changed.  */
2782                     || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
2783                    && produce_warns)
2784             warning_at (loc, OPT_Wsign_conversion, "conversion to %qT from %qT "
2785                         "may change the sign of the result",
2786                         type, expr_type);
2787         }
2788
2789       /* Warn for integer types converted to real types if and only if
2790          all the range of values of the integer type cannot be
2791          represented by the real type.  */
2792       else if (TREE_CODE (expr_type) == INTEGER_TYPE
2793                && TREE_CODE (type) == REAL_TYPE)
2794         {
2795           tree type_low_bound, type_high_bound;
2796           REAL_VALUE_TYPE real_low_bound, real_high_bound;
2797
2798           /* Don't warn about char y = 0xff; float x = (int) y;  */
2799           expr = get_unwidened (expr, 0);
2800           expr_type = TREE_TYPE (expr);
2801
2802           type_low_bound = TYPE_MIN_VALUE (expr_type);
2803           type_high_bound = TYPE_MAX_VALUE (expr_type);
2804           real_low_bound = real_value_from_int_cst (0, type_low_bound);
2805           real_high_bound = real_value_from_int_cst (0, type_high_bound);
2806
2807           if (!exact_real_truncate (TYPE_MODE (type), &real_low_bound)
2808               || !exact_real_truncate (TYPE_MODE (type), &real_high_bound))
2809             give_warning = UNSAFE_OTHER;
2810         }
2811
2812       /* Warn for real types converted to smaller real types.  */
2813       else if (TREE_CODE (expr_type) == REAL_TYPE
2814                && TREE_CODE (type) == REAL_TYPE
2815                && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
2816         give_warning = UNSAFE_REAL;
2817     }
2818
2819   return give_warning;
2820 }
2821
2822 /* Warns if the conversion of EXPR to TYPE may alter a value.
2823    This is a helper function for warnings_for_convert_and_check.  */
2824
2825 static void
2826 conversion_warning (location_t loc, tree type, tree expr)
2827 {
2828   tree expr_type = TREE_TYPE (expr);
2829   enum conversion_safety conversion_kind;
2830
2831   if (!warn_conversion && !warn_sign_conversion && !warn_float_conversion)
2832     return;
2833
2834   /* This may happen, because for LHS op= RHS we preevaluate
2835      RHS and create C_MAYBE_CONST_EXPR <SAVE_EXPR <RHS>>, which
2836      means we could no longer see the code of the EXPR.  */
2837   if (TREE_CODE (expr) == C_MAYBE_CONST_EXPR)
2838     expr = C_MAYBE_CONST_EXPR_EXPR (expr);
2839   if (TREE_CODE (expr) == SAVE_EXPR)
2840     expr = TREE_OPERAND (expr, 0);
2841
2842   switch (TREE_CODE (expr))
2843     {
2844     case EQ_EXPR:
2845     case NE_EXPR:
2846     case LE_EXPR:
2847     case GE_EXPR:
2848     case LT_EXPR:
2849     case GT_EXPR:
2850     case TRUTH_ANDIF_EXPR:
2851     case TRUTH_ORIF_EXPR:
2852     case TRUTH_AND_EXPR:
2853     case TRUTH_OR_EXPR:
2854     case TRUTH_XOR_EXPR:
2855     case TRUTH_NOT_EXPR:
2856       /* Conversion from boolean to a signed:1 bit-field (which only
2857          can hold the values 0 and -1) doesn't lose information - but
2858          it does change the value.  */
2859       if (TYPE_PRECISION (type) == 1 && !TYPE_UNSIGNED (type))
2860         warning_at (loc, OPT_Wconversion,
2861                     "conversion to %qT from boolean expression", type);
2862       return;
2863
2864     case REAL_CST:
2865     case INTEGER_CST:
2866       conversion_kind = unsafe_conversion_p (loc, type, expr, true);
2867       if (conversion_kind == UNSAFE_REAL)
2868         warning_at (loc, OPT_Wfloat_conversion,
2869                     "conversion to %qT alters %qT constant value",
2870                     type, expr_type);
2871       else if (conversion_kind)
2872         warning_at (loc, OPT_Wconversion,
2873                     "conversion to %qT alters %qT constant value",
2874                     type, expr_type);
2875       return;
2876
2877     case COND_EXPR:
2878       {
2879         /* In case of COND_EXPR, we do not care about the type of
2880            COND_EXPR, only about the conversion of each operand.  */
2881         tree op1 = TREE_OPERAND (expr, 1);
2882         tree op2 = TREE_OPERAND (expr, 2);
2883         
2884         conversion_warning (loc, type, op1);
2885         conversion_warning (loc, type, op2);
2886         return;
2887       }
2888
2889     default: /* 'expr' is not a constant.  */
2890       conversion_kind = unsafe_conversion_p (loc, type, expr, true);
2891       if (conversion_kind == UNSAFE_REAL)
2892         warning_at (loc, OPT_Wfloat_conversion,
2893                     "conversion to %qT from %qT may alter its value",
2894                     type, expr_type);
2895       else if (conversion_kind)
2896         warning_at (loc, OPT_Wconversion,
2897                     "conversion to %qT from %qT may alter its value",
2898                     type, expr_type);
2899     }
2900 }
2901
2902 /* Produce warnings after a conversion. RESULT is the result of
2903    converting EXPR to TYPE.  This is a helper function for
2904    convert_and_check and cp_convert_and_check.  */
2905
2906 void
2907 warnings_for_convert_and_check (location_t loc, tree type, tree expr,
2908                                 tree result)
2909 {
2910   loc = expansion_point_location_if_in_system_header (loc);
2911
2912   if (TREE_CODE (expr) == INTEGER_CST
2913       && (TREE_CODE (type) == INTEGER_TYPE
2914           || TREE_CODE (type) == ENUMERAL_TYPE)
2915       && !int_fits_type_p (expr, type))
2916     {
2917       /* Do not diagnose overflow in a constant expression merely
2918          because a conversion overflowed.  */
2919       if (TREE_OVERFLOW (result))
2920         TREE_OVERFLOW (result) = TREE_OVERFLOW (expr);
2921
2922       if (TYPE_UNSIGNED (type))
2923         {
2924           /* This detects cases like converting -129 or 256 to
2925              unsigned char.  */
2926           if (!int_fits_type_p (expr, c_common_signed_type (type)))
2927             warning_at (loc, OPT_Woverflow,
2928                         "large integer implicitly truncated to unsigned type");
2929           else
2930             conversion_warning (loc, type, expr);
2931         }
2932       else if (!int_fits_type_p (expr, c_common_unsigned_type (type)))
2933         warning_at (loc, OPT_Woverflow,
2934                  "overflow in implicit constant conversion");
2935       /* No warning for converting 0x80000000 to int.  */
2936       else if (pedantic
2937                && (TREE_CODE (TREE_TYPE (expr)) != INTEGER_TYPE
2938                    || TYPE_PRECISION (TREE_TYPE (expr))
2939                    != TYPE_PRECISION (type)))
2940         warning_at (loc, OPT_Woverflow,
2941                     "overflow in implicit constant conversion");
2942
2943       else
2944         conversion_warning (loc, type, expr);
2945     }
2946   else if ((TREE_CODE (result) == INTEGER_CST
2947             || TREE_CODE (result) == FIXED_CST) && TREE_OVERFLOW (result))
2948     warning_at (loc, OPT_Woverflow,
2949                 "overflow in implicit constant conversion");
2950   else
2951     conversion_warning (loc, type, expr);
2952 }
2953
2954
2955 /* Convert EXPR to TYPE, warning about conversion problems with constants.
2956    Invoke this function on every expression that is converted implicitly,
2957    i.e. because of language rules and not because of an explicit cast.  */
2958
2959 tree
2960 convert_and_check (location_t loc, tree type, tree expr)
2961 {
2962   tree result;
2963   tree expr_for_warning;
2964
2965   /* Convert from a value with possible excess precision rather than
2966      via the semantic type, but do not warn about values not fitting
2967      exactly in the semantic type.  */
2968   if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
2969     {
2970       tree orig_type = TREE_TYPE (expr);
2971       expr = TREE_OPERAND (expr, 0);
2972       expr_for_warning = convert (orig_type, expr);
2973       if (orig_type == type)
2974         return expr_for_warning;
2975     }
2976   else
2977     expr_for_warning = expr;
2978
2979   if (TREE_TYPE (expr) == type)
2980     return expr;
2981
2982   result = convert (type, expr);
2983
2984   if (c_inhibit_evaluation_warnings == 0
2985       && !TREE_OVERFLOW_P (expr)
2986       && result != error_mark_node)
2987     warnings_for_convert_and_check (loc, type, expr_for_warning, result);
2988
2989   return result;
2990 }
2991 \f
2992 /* A node in a list that describes references to variables (EXPR), which are
2993    either read accesses if WRITER is zero, or write accesses, in which case
2994    WRITER is the parent of EXPR.  */
2995 struct tlist
2996 {
2997   struct tlist *next;
2998   tree expr, writer;
2999 };
3000
3001 /* Used to implement a cache the results of a call to verify_tree.  We only
3002    use this for SAVE_EXPRs.  */
3003 struct tlist_cache
3004 {
3005   struct tlist_cache *next;
3006   struct tlist *cache_before_sp;
3007   struct tlist *cache_after_sp;
3008   tree expr;
3009 };
3010
3011 /* Obstack to use when allocating tlist structures, and corresponding
3012    firstobj.  */
3013 static struct obstack tlist_obstack;
3014 static char *tlist_firstobj = 0;
3015
3016 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
3017    warnings.  */
3018 static struct tlist *warned_ids;
3019 /* SAVE_EXPRs need special treatment.  We process them only once and then
3020    cache the results.  */
3021 static struct tlist_cache *save_expr_cache;
3022
3023 static void add_tlist (struct tlist **, struct tlist *, tree, int);
3024 static void merge_tlist (struct tlist **, struct tlist *, int);
3025 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
3026 static int warning_candidate_p (tree);
3027 static bool candidate_equal_p (const_tree, const_tree);
3028 static void warn_for_collisions (struct tlist *);
3029 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
3030 static struct tlist *new_tlist (struct tlist *, tree, tree);
3031
3032 /* Create a new struct tlist and fill in its fields.  */
3033 static struct tlist *
3034 new_tlist (struct tlist *next, tree t, tree writer)
3035 {
3036   struct tlist *l;
3037   l = XOBNEW (&tlist_obstack, struct tlist);
3038   l->next = next;
3039   l->expr = t;
3040   l->writer = writer;
3041   return l;
3042 }
3043
3044 /* Add duplicates of the nodes found in ADD to the list *TO.  If EXCLUDE_WRITER
3045    is nonnull, we ignore any node we find which has a writer equal to it.  */
3046
3047 static void
3048 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
3049 {
3050   while (add)
3051     {
3052       struct tlist *next = add->next;
3053       if (!copy)
3054         add->next = *to;
3055       if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
3056         *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
3057       add = next;
3058     }
3059 }
3060
3061 /* Merge the nodes of ADD into TO.  This merging process is done so that for
3062    each variable that already exists in TO, no new node is added; however if
3063    there is a write access recorded in ADD, and an occurrence on TO is only
3064    a read access, then the occurrence in TO will be modified to record the
3065    write.  */
3066
3067 static void
3068 merge_tlist (struct tlist **to, struct tlist *add, int copy)
3069 {
3070   struct tlist **end = to;
3071
3072   while (*end)
3073     end = &(*end)->next;
3074
3075   while (add)
3076     {
3077       int found = 0;
3078       struct tlist *tmp2;
3079       struct tlist *next = add->next;
3080
3081       for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
3082         if (candidate_equal_p (tmp2->expr, add->expr))
3083           {
3084             found = 1;
3085             if (!tmp2->writer)
3086               tmp2->writer = add->writer;
3087           }
3088       if (!found)
3089         {
3090           *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
3091           end = &(*end)->next;
3092           *end = 0;
3093         }
3094       add = next;
3095     }
3096 }
3097
3098 /* WRITTEN is a variable, WRITER is its parent.  Warn if any of the variable
3099    references in list LIST conflict with it, excluding reads if ONLY writers
3100    is nonzero.  */
3101
3102 static void
3103 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
3104                        int only_writes)
3105 {
3106   struct tlist *tmp;
3107
3108   /* Avoid duplicate warnings.  */
3109   for (tmp = warned_ids; tmp; tmp = tmp->next)
3110     if (candidate_equal_p (tmp->expr, written))
3111       return;
3112
3113   while (list)
3114     {
3115       if (candidate_equal_p (list->expr, written)
3116           && !candidate_equal_p (list->writer, writer)
3117           && (!only_writes || list->writer))
3118         {
3119           warned_ids = new_tlist (warned_ids, written, NULL_TREE);
3120           warning_at (EXPR_LOC_OR_LOC (writer, input_location),
3121                       OPT_Wsequence_point, "operation on %qE may be undefined",
3122                       list->expr);
3123         }
3124       list = list->next;
3125     }
3126 }
3127
3128 /* Given a list LIST of references to variables, find whether any of these
3129    can cause conflicts due to missing sequence points.  */
3130
3131 static void
3132 warn_for_collisions (struct tlist *list)
3133 {
3134   struct tlist *tmp;
3135
3136   for (tmp = list; tmp; tmp = tmp->next)
3137     {
3138       if (tmp->writer)
3139         warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
3140     }
3141 }
3142
3143 /* Return nonzero if X is a tree that can be verified by the sequence point
3144    warnings.  */
3145 static int
3146 warning_candidate_p (tree x)
3147 {
3148   if (DECL_P (x) && DECL_ARTIFICIAL (x))
3149     return 0;
3150
3151   if (TREE_CODE (x) == BLOCK)
3152     return 0;
3153
3154   /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.c
3155      (lvalue_p) crash on TRY/CATCH. */
3156   if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
3157     return 0;
3158
3159   if (!lvalue_p (x))
3160     return 0;
3161
3162   /* No point to track non-const calls, they will never satisfy
3163      operand_equal_p.  */
3164   if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
3165     return 0;
3166
3167   if (TREE_CODE (x) == STRING_CST)
3168     return 0;
3169
3170   return 1;
3171 }
3172
3173 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
3174 static bool
3175 candidate_equal_p (const_tree x, const_tree y)
3176 {
3177   return (x == y) || (x && y && operand_equal_p (x, y, 0));
3178 }
3179
3180 /* Walk the tree X, and record accesses to variables.  If X is written by the
3181    parent tree, WRITER is the parent.
3182    We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP.  If this
3183    expression or its only operand forces a sequence point, then everything up
3184    to the sequence point is stored in PBEFORE_SP.  Everything else gets stored
3185    in PNO_SP.
3186    Once we return, we will have emitted warnings if any subexpression before
3187    such a sequence point could be undefined.  On a higher level, however, the
3188    sequence point may not be relevant, and we'll merge the two lists.
3189
3190    Example: (b++, a) + b;
3191    The call that processes the COMPOUND_EXPR will store the increment of B
3192    in PBEFORE_SP, and the use of A in PNO_SP.  The higher-level call that
3193    processes the PLUS_EXPR will need to merge the two lists so that
3194    eventually, all accesses end up on the same list (and we'll warn about the
3195    unordered subexpressions b++ and b.
3196
3197    A note on merging.  If we modify the former example so that our expression
3198    becomes
3199      (b++, b) + a
3200    care must be taken not simply to add all three expressions into the final
3201    PNO_SP list.  The function merge_tlist takes care of that by merging the
3202    before-SP list of the COMPOUND_EXPR into its after-SP list in a special
3203    way, so that no more than one access to B is recorded.  */
3204
3205 static void
3206 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
3207              tree writer)
3208 {
3209   struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
3210   enum tree_code code;
3211   enum tree_code_class cl;
3212
3213   /* X may be NULL if it is the operand of an empty statement expression
3214      ({ }).  */
3215   if (x == NULL)
3216     return;
3217
3218  restart:
3219   code = TREE_CODE (x);
3220   cl = TREE_CODE_CLASS (code);
3221
3222   if (warning_candidate_p (x))
3223     *pno_sp = new_tlist (*pno_sp, x, writer);
3224
3225   switch (code)
3226     {
3227     case CONSTRUCTOR:
3228     case SIZEOF_EXPR:
3229       return;
3230
3231     case COMPOUND_EXPR:
3232     case TRUTH_ANDIF_EXPR:
3233     case TRUTH_ORIF_EXPR:
3234       tmp_before = tmp_nosp = tmp_list3 = 0;
3235       verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
3236       warn_for_collisions (tmp_nosp);
3237       merge_tlist (pbefore_sp, tmp_before, 0);
3238       merge_tlist (pbefore_sp, tmp_nosp, 0);
3239       verify_tree (TREE_OPERAND (x, 1), &tmp_list3, pno_sp, NULL_TREE);
3240       merge_tlist (pbefore_sp, tmp_list3, 0);
3241       return;
3242
3243     case COND_EXPR:
3244       tmp_before = tmp_list2 = 0;
3245       verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
3246       warn_for_collisions (tmp_list2);
3247       merge_tlist (pbefore_sp, tmp_before, 0);
3248       merge_tlist (pbefore_sp, tmp_list2, 0);
3249
3250       tmp_list3 = tmp_nosp = 0;
3251       verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
3252       warn_for_collisions (tmp_nosp);
3253       merge_tlist (pbefore_sp, tmp_list3, 0);
3254
3255       tmp_list3 = tmp_list2 = 0;
3256       verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
3257       warn_for_collisions (tmp_list2);
3258       merge_tlist (pbefore_sp, tmp_list3, 0);
3259       /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
3260          two first, to avoid warning for (a ? b++ : b++).  */
3261       merge_tlist (&tmp_nosp, tmp_list2, 0);
3262       add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
3263       return;
3264
3265     case PREDECREMENT_EXPR:
3266     case PREINCREMENT_EXPR:
3267     case POSTDECREMENT_EXPR:
3268     case POSTINCREMENT_EXPR:
3269       verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
3270       return;
3271
3272     case MODIFY_EXPR:
3273       tmp_before = tmp_nosp = tmp_list3 = 0;
3274       verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
3275       verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
3276       /* Expressions inside the LHS are not ordered wrt. the sequence points
3277          in the RHS.  Example:
3278            *a = (a++, 2)
3279          Despite the fact that the modification of "a" is in the before_sp
3280          list (tmp_before), it conflicts with the use of "a" in the LHS.
3281          We can handle this by adding the contents of tmp_list3
3282          to those of tmp_before, and redoing the collision warnings for that
3283          list.  */
3284       add_tlist (&tmp_before, tmp_list3, x, 1);
3285       warn_for_collisions (tmp_before);
3286       /* Exclude the LHS itself here; we first have to merge it into the
3287          tmp_nosp list.  This is done to avoid warning for "a = a"; if we
3288          didn't exclude the LHS, we'd get it twice, once as a read and once
3289          as a write.  */
3290       add_tlist (pno_sp, tmp_list3, x, 0);
3291       warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
3292
3293       merge_tlist (pbefore_sp, tmp_before, 0);
3294       if (warning_candidate_p (TREE_OPERAND (x, 0)))
3295         merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
3296       add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
3297       return;
3298
3299     case CALL_EXPR:
3300       /* We need to warn about conflicts among arguments and conflicts between
3301          args and the function address.  Side effects of the function address,
3302          however, are not ordered by the sequence point of the call.  */
3303       {
3304         call_expr_arg_iterator iter;
3305         tree arg;
3306         tmp_before = tmp_nosp = 0;
3307         verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
3308         FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
3309           {
3310             tmp_list2 = tmp_list3 = 0;
3311             verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
3312             merge_tlist (&tmp_list3, tmp_list2, 0);
3313             add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
3314           }
3315         add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
3316         warn_for_collisions (tmp_before);
3317         add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
3318         return;
3319       }
3320
3321     case TREE_LIST:
3322       /* Scan all the list, e.g. indices of multi dimensional array.  */
3323       while (x)
3324         {
3325           tmp_before = tmp_nosp = 0;
3326           verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
3327           merge_tlist (&tmp_nosp, tmp_before, 0);
3328           add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
3329           x = TREE_CHAIN (x);
3330         }
3331       return;
3332
3333     case SAVE_EXPR:
3334       {
3335         struct tlist_cache *t;
3336         for (t = save_expr_cache; t; t = t->next)
3337           if (candidate_equal_p (t->expr, x))
3338             break;
3339
3340         if (!t)
3341           {
3342             t = XOBNEW (&tlist_obstack, struct tlist_cache);
3343             t->next = save_expr_cache;
3344             t->expr = x;
3345             save_expr_cache = t;
3346
3347             tmp_before = tmp_nosp = 0;
3348             verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
3349             warn_for_collisions (tmp_nosp);
3350
3351             tmp_list3 = 0;
3352             merge_tlist (&tmp_list3, tmp_nosp, 0);
3353             t->cache_before_sp = tmp_before;
3354             t->cache_after_sp = tmp_list3;
3355           }
3356         merge_tlist (pbefore_sp, t->cache_before_sp, 1);
3357         add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
3358         return;
3359       }
3360
3361     case ADDR_EXPR:
3362       x = TREE_OPERAND (x, 0);
3363       if (DECL_P (x))
3364         return;
3365       writer = 0;
3366       goto restart;
3367
3368     default:
3369       /* For other expressions, simply recurse on their operands.
3370          Manual tail recursion for unary expressions.
3371          Other non-expressions need not be processed.  */
3372       if (cl == tcc_unary)
3373         {
3374           x = TREE_OPERAND (x, 0);
3375           writer = 0;
3376           goto restart;
3377         }
3378       else if (IS_EXPR_CODE_CLASS (cl))
3379         {
3380           int lp;
3381           int max = TREE_OPERAND_LENGTH (x);
3382           for (lp = 0; lp < max; lp++)
3383             {
3384               tmp_before = tmp_nosp = 0;
3385               verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
3386               merge_tlist (&tmp_nosp, tmp_before, 0);
3387               add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
3388             }
3389         }
3390       return;
3391     }
3392 }
3393
3394 /* Try to warn for undefined behavior in EXPR due to missing sequence
3395    points.  */
3396
3397 DEBUG_FUNCTION void
3398 verify_sequence_points (tree expr)
3399 {
3400   struct tlist *before_sp = 0, *after_sp = 0;
3401
3402   warned_ids = 0;
3403   save_expr_cache = 0;
3404   if (tlist_firstobj == 0)
3405     {
3406       gcc_obstack_init (&tlist_obstack);
3407       tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
3408     }
3409
3410   verify_tree (expr, &before_sp, &after_sp, 0);
3411   warn_for_collisions (after_sp);
3412   obstack_free (&tlist_obstack, tlist_firstobj);
3413 }
3414 \f
3415 /* Validate the expression after `case' and apply default promotions.  */
3416
3417 static tree
3418 check_case_value (location_t loc, tree value)
3419 {
3420   if (value == NULL_TREE)
3421     return value;
3422
3423   if (TREE_CODE (value) == INTEGER_CST)
3424     /* Promote char or short to int.  */
3425     value = perform_integral_promotions (value);
3426   else if (value != error_mark_node)
3427     {
3428       error_at (loc, "case label does not reduce to an integer constant");
3429       value = error_mark_node;
3430     }
3431
3432   constant_expression_warning (value);
3433
3434   return value;
3435 }
3436 \f
3437 /* See if the case values LOW and HIGH are in the range of the original
3438    type (i.e. before the default conversion to int) of the switch testing
3439    expression.
3440    TYPE is the promoted type of the testing expression, and ORIG_TYPE is
3441    the type before promoting it.  CASE_LOW_P is a pointer to the lower
3442    bound of the case label, and CASE_HIGH_P is the upper bound or NULL
3443    if the case is not a case range.
3444    The caller has to make sure that we are not called with NULL for
3445    CASE_LOW_P (i.e. the default case).
3446    Returns true if the case label is in range of ORIG_TYPE (saturated or
3447    untouched) or false if the label is out of range.  */
3448
3449 static bool
3450 check_case_bounds (location_t loc, tree type, tree orig_type,
3451                    tree *case_low_p, tree *case_high_p)
3452 {
3453   tree min_value, max_value;
3454   tree case_low = *case_low_p;
3455   tree case_high = case_high_p ? *case_high_p : case_low;
3456
3457   /* If there was a problem with the original type, do nothing.  */
3458   if (orig_type == error_mark_node)
3459     return true;
3460
3461   min_value = TYPE_MIN_VALUE (orig_type);
3462   max_value = TYPE_MAX_VALUE (orig_type);
3463
3464   /* Case label is less than minimum for type.  */
3465   if (tree_int_cst_compare (case_low, min_value) < 0
3466       && tree_int_cst_compare (case_high, min_value) < 0)
3467     {
3468       warning_at (loc, 0, "case label value is less than minimum value "
3469                   "for type");
3470       return false;
3471     }
3472
3473   /* Case value is greater than maximum for type.  */
3474   if (tree_int_cst_compare (case_low, max_value) > 0
3475       && tree_int_cst_compare (case_high, max_value) > 0)
3476     {
3477       warning_at (loc, 0, "case label value exceeds maximum value for type");
3478       return false;
3479     }
3480
3481   /* Saturate lower case label value to minimum.  */
3482   if (tree_int_cst_compare (case_high, min_value) >= 0
3483       && tree_int_cst_compare (case_low, min_value) < 0)
3484     {
3485       warning_at (loc, 0, "lower value in case label range"
3486                   " less than minimum value for type");
3487       case_low = min_value;
3488     }
3489
3490   /* Saturate upper case label value to maximum.  */
3491   if (tree_int_cst_compare (case_low, max_value) <= 0
3492       && tree_int_cst_compare (case_high, max_value) > 0)
3493     {
3494       warning_at (loc, 0, "upper value in case label range"
3495                   " exceeds maximum value for type");
3496       case_high = max_value;
3497     }
3498
3499   if (*case_low_p != case_low)
3500     *case_low_p = convert (type, case_low);
3501   if (case_high_p && *case_high_p != case_high)
3502     *case_high_p = convert (type, case_high);
3503
3504   return true;
3505 }
3506 \f
3507 /* Return an integer type with BITS bits of precision,
3508    that is unsigned if UNSIGNEDP is nonzero, otherwise signed.  */
3509
3510 tree
3511 c_common_type_for_size (unsigned int bits, int unsignedp)
3512 {
3513   int i;
3514
3515   if (bits == TYPE_PRECISION (integer_type_node))
3516     return unsignedp ? unsigned_type_node : integer_type_node;
3517
3518   if (bits == TYPE_PRECISION (signed_char_type_node))
3519     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
3520
3521   if (bits == TYPE_PRECISION (short_integer_type_node))
3522     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
3523
3524   if (bits == TYPE_PRECISION (long_integer_type_node))
3525     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
3526
3527   if (bits == TYPE_PRECISION (long_long_integer_type_node))
3528     return (unsignedp ? long_long_unsigned_type_node
3529             : long_long_integer_type_node);
3530
3531   for (i = 0; i < NUM_INT_N_ENTS; i ++)
3532     if (int_n_enabled_p[i]
3533         && bits == int_n_data[i].bitsize)
3534       return (unsignedp ? int_n_trees[i].unsigned_type
3535               : int_n_trees[i].signed_type);
3536
3537   if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
3538     return (unsignedp ? widest_unsigned_literal_type_node
3539             : widest_integer_literal_type_node);
3540
3541   if (bits <= TYPE_PRECISION (intQI_type_node))
3542     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
3543
3544   if (bits <= TYPE_PRECISION (intHI_type_node))
3545     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
3546
3547   if (bits <= TYPE_PRECISION (intSI_type_node))
3548     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
3549
3550   if (bits <= TYPE_PRECISION (intDI_type_node))
3551     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
3552
3553   return 0;
3554 }
3555
3556 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
3557    that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
3558    and saturating if SATP is nonzero, otherwise not saturating.  */
3559
3560 tree
3561 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
3562                                     int unsignedp, int satp)
3563 {
3564   machine_mode mode;
3565   if (ibit == 0)
3566     mode = unsignedp ? UQQmode : QQmode;
3567   else
3568     mode = unsignedp ? UHAmode : HAmode;
3569
3570   for (; mode != VOIDmode; mode = GET_MODE_WIDER_MODE (mode))
3571     if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
3572       break;
3573
3574   if (mode == VOIDmode || !targetm.scalar_mode_supported_p (mode))
3575     {
3576       sorry ("GCC cannot support operators with integer types and "
3577              "fixed-point types that have too many integral and "
3578              "fractional bits together");
3579       return 0;
3580     }
3581
3582   return c_common_type_for_mode (mode, satp);
3583 }
3584
3585 /* Used for communication between c_common_type_for_mode and
3586    c_register_builtin_type.  */
3587 tree registered_builtin_types;
3588
3589 /* Return a data type that has machine mode MODE.
3590    If the mode is an integer,
3591    then UNSIGNEDP selects between signed and unsigned types.
3592    If the mode is a fixed-point mode,
3593    then UNSIGNEDP selects between saturating and nonsaturating types.  */
3594
3595 tree
3596 c_common_type_for_mode (machine_mode mode, int unsignedp)
3597 {
3598   tree t;
3599   int i;
3600
3601   if (mode == TYPE_MODE (integer_type_node))
3602     return unsignedp ? unsigned_type_node : integer_type_node;
3603
3604   if (mode == TYPE_MODE (signed_char_type_node))
3605     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
3606
3607   if (mode == TYPE_MODE (short_integer_type_node))
3608     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
3609
3610   if (mode == TYPE_MODE (long_integer_type_node))
3611     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
3612
3613   if (mode == TYPE_MODE (long_long_integer_type_node))
3614     return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
3615
3616   for (i = 0; i < NUM_INT_N_ENTS; i ++)
3617     if (int_n_enabled_p[i]
3618         && mode == int_n_data[i].m)
3619       return (unsignedp ? int_n_trees[i].unsigned_type
3620               : int_n_trees[i].signed_type);
3621
3622   if (mode == TYPE_MODE (widest_integer_literal_type_node))
3623     return unsignedp ? widest_unsigned_literal_type_node
3624                      : widest_integer_literal_type_node;
3625
3626   if (mode == QImode)
3627     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
3628
3629   if (mode == HImode)
3630     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
3631
3632   if (mode == SImode)
3633     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
3634
3635   if (mode == DImode)
3636     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
3637
3638 #if HOST_BITS_PER_WIDE_INT >= 64
3639   if (mode == TYPE_MODE (intTI_type_node))
3640     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
3641 #endif
3642
3643   if (mode == TYPE_MODE (float_type_node))
3644     return float_type_node;
3645
3646   if (mode == TYPE_MODE (double_type_node))
3647     return double_type_node;
3648
3649   if (mode == TYPE_MODE (long_double_type_node))
3650     return long_double_type_node;
3651
3652   if (mode == TYPE_MODE (void_type_node))
3653     return void_type_node;
3654
3655   if (mode == TYPE_MODE (build_pointer_type (char_type_node)))
3656     return (unsignedp
3657             ? make_unsigned_type (GET_MODE_PRECISION (mode))
3658             : make_signed_type (GET_MODE_PRECISION (mode)));
3659
3660   if (mode == TYPE_MODE (build_pointer_type (integer_type_node)))
3661     return (unsignedp
3662             ? make_unsigned_type (GET_MODE_PRECISION (mode))
3663             : make_signed_type (GET_MODE_PRECISION (mode)));
3664
3665   if (COMPLEX_MODE_P (mode))
3666     {
3667       machine_mode inner_mode;
3668       tree inner_type;
3669
3670       if (mode == TYPE_MODE (complex_float_type_node))
3671         return complex_float_type_node;
3672       if (mode == TYPE_MODE (complex_double_type_node))
3673         return complex_double_type_node;
3674       if (mode == TYPE_MODE (complex_long_double_type_node))
3675         return complex_long_double_type_node;
3676
3677       if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
3678         return complex_integer_type_node;
3679
3680       inner_mode = GET_MODE_INNER (mode);
3681       inner_type = c_common_type_for_mode (inner_mode, unsignedp);
3682       if (inner_type != NULL_TREE)
3683         return build_complex_type (inner_type);
3684     }
3685   else if (VECTOR_MODE_P (mode))
3686     {
3687       machine_mode inner_mode = GET_MODE_INNER (mode);
3688       tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
3689       if (inner_type != NULL_TREE)
3690         return build_vector_type_for_mode (inner_type, mode);
3691     }
3692
3693   if (mode == TYPE_MODE (dfloat32_type_node))
3694     return dfloat32_type_node;
3695   if (mode == TYPE_MODE (dfloat64_type_node))
3696     return dfloat64_type_node;
3697   if (mode == TYPE_MODE (dfloat128_type_node))
3698     return dfloat128_type_node;
3699
3700   if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
3701     {
3702       if (mode == TYPE_MODE (short_fract_type_node))
3703         return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
3704       if (mode == TYPE_MODE (fract_type_node))
3705         return unsignedp ? sat_fract_type_node : fract_type_node;
3706       if (mode == TYPE_MODE (long_fract_type_node))
3707         return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
3708       if (mode == TYPE_MODE (long_long_fract_type_node))
3709         return unsignedp ? sat_long_long_fract_type_node
3710                          : long_long_fract_type_node;
3711
3712       if (mode == TYPE_MODE (unsigned_short_fract_type_node))
3713         return unsignedp ? sat_unsigned_short_fract_type_node
3714                          : unsigned_short_fract_type_node;
3715       if (mode == TYPE_MODE (unsigned_fract_type_node))
3716         return unsignedp ? sat_unsigned_fract_type_node
3717                          : unsigned_fract_type_node;
3718       if (mode == TYPE_MODE (unsigned_long_fract_type_node))
3719         return unsignedp ? sat_unsigned_long_fract_type_node
3720                          : unsigned_long_fract_type_node;
3721       if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
3722         return unsignedp ? sat_unsigned_long_long_fract_type_node
3723                          : unsigned_long_long_fract_type_node;
3724
3725       if (mode == TYPE_MODE (short_accum_type_node))
3726         return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
3727       if (mode == TYPE_MODE (accum_type_node))
3728         return unsignedp ? sat_accum_type_node : accum_type_node;
3729       if (mode == TYPE_MODE (long_accum_type_node))
3730         return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
3731       if (mode == TYPE_MODE (long_long_accum_type_node))
3732         return unsignedp ? sat_long_long_accum_type_node
3733                          : long_long_accum_type_node;
3734
3735       if (mode == TYPE_MODE (unsigned_short_accum_type_node))
3736         return unsignedp ? sat_unsigned_short_accum_type_node
3737                          : unsigned_short_accum_type_node;
3738       if (mode == TYPE_MODE (unsigned_accum_type_node))
3739         return unsignedp ? sat_unsigned_accum_type_node
3740                          : unsigned_accum_type_node;
3741       if (mode == TYPE_MODE (unsigned_long_accum_type_node))
3742         return unsignedp ? sat_unsigned_long_accum_type_node
3743                          : unsigned_long_accum_type_node;
3744       if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
3745         return unsignedp ? sat_unsigned_long_long_accum_type_node
3746                          : unsigned_long_long_accum_type_node;
3747
3748       if (mode == QQmode)
3749         return unsignedp ? sat_qq_type_node : qq_type_node;
3750       if (mode == HQmode)
3751         return unsignedp ? sat_hq_type_node : hq_type_node;
3752       if (mode == SQmode)
3753         return unsignedp ? sat_sq_type_node : sq_type_node;
3754       if (mode == DQmode)
3755         return unsignedp ? sat_dq_type_node : dq_type_node;
3756       if (mode == TQmode)
3757         return unsignedp ? sat_tq_type_node : tq_type_node;
3758
3759       if (mode == UQQmode)
3760         return unsignedp ? sat_uqq_type_node : uqq_type_node;
3761       if (mode == UHQmode)
3762         return unsignedp ? sat_uhq_type_node : uhq_type_node;
3763       if (mode == USQmode)
3764         return unsignedp ? sat_usq_type_node : usq_type_node;
3765       if (mode == UDQmode)
3766         return unsignedp ? sat_udq_type_node : udq_type_node;
3767       if (mode == UTQmode)
3768         return unsignedp ? sat_utq_type_node : utq_type_node;
3769
3770       if (mode == HAmode)
3771         return unsignedp ? sat_ha_type_node : ha_type_node;
3772       if (mode == SAmode)
3773         return unsignedp ? sat_sa_type_node : sa_type_node;
3774       if (mode == DAmode)
3775         return unsignedp ? sat_da_type_node : da_type_node;
3776       if (mode == TAmode)
3777         return unsignedp ? sat_ta_type_node : ta_type_node;
3778
3779       if (mode == UHAmode)
3780         return unsignedp ? sat_uha_type_node : uha_type_node;
3781       if (mode == USAmode)
3782         return unsignedp ? sat_usa_type_node : usa_type_node;
3783       if (mode == UDAmode)
3784         return unsignedp ? sat_uda_type_node : uda_type_node;
3785       if (mode == UTAmode)
3786         return unsignedp ? sat_uta_type_node : uta_type_node;
3787     }
3788
3789   for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
3790     if (TYPE_MODE (TREE_VALUE (t)) == mode
3791         && !!unsignedp == !!TYPE_UNSIGNED (TREE_VALUE (t)))
3792       return TREE_VALUE (t);
3793
3794   return 0;
3795 }
3796
3797 tree
3798 c_common_unsigned_type (tree type)
3799 {
3800   return c_common_signed_or_unsigned_type (1, type);
3801 }
3802
3803 /* Return a signed type the same as TYPE in other respects.  */
3804
3805 tree
3806 c_common_signed_type (tree type)
3807 {
3808   return c_common_signed_or_unsigned_type (0, type);
3809 }
3810
3811 /* Return a type the same as TYPE except unsigned or
3812    signed according to UNSIGNEDP.  */
3813
3814 tree
3815 c_common_signed_or_unsigned_type (int unsignedp, tree type)
3816 {
3817   tree type1;
3818   int i;
3819
3820   /* This block of code emulates the behavior of the old
3821      c_common_unsigned_type. In particular, it returns
3822      long_unsigned_type_node if passed a long, even when a int would
3823      have the same size. This is necessary for warnings to work
3824      correctly in archs where sizeof(int) == sizeof(long) */
3825
3826   type1 = TYPE_MAIN_VARIANT (type);
3827   if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
3828     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
3829   if (type1 == integer_type_node || type1 == unsigned_type_node)
3830     return unsignedp ? unsigned_type_node : integer_type_node;
3831   if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
3832     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
3833   if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
3834     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
3835   if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
3836     return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
3837
3838   for (i = 0; i < NUM_INT_N_ENTS; i ++)
3839     if (int_n_enabled_p[i]
3840         && (type1 == int_n_trees[i].unsigned_type
3841             || type1 == int_n_trees[i].signed_type))
3842       return (unsignedp ? int_n_trees[i].unsigned_type
3843               : int_n_trees[i].signed_type);
3844
3845   if (type1 == widest_integer_literal_type_node || type1 == widest_unsigned_literal_type_node)
3846     return unsignedp ? widest_unsigned_literal_type_node : widest_integer_literal_type_node;
3847 #if HOST_BITS_PER_WIDE_INT >= 64
3848   if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
3849     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
3850 #endif
3851   if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
3852     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
3853   if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
3854     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
3855   if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
3856     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
3857   if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
3858     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
3859
3860 #define C_COMMON_FIXED_TYPES(NAME)          \
3861   if (type1 == short_ ## NAME ## _type_node \
3862       || type1 == unsigned_short_ ## NAME ## _type_node) \
3863     return unsignedp ? unsigned_short_ ## NAME ## _type_node \
3864                      : short_ ## NAME ## _type_node; \
3865   if (type1 == NAME ## _type_node \
3866       || type1 == unsigned_ ## NAME ## _type_node) \
3867     return unsignedp ? unsigned_ ## NAME ## _type_node \
3868                      : NAME ## _type_node; \
3869   if (type1 == long_ ## NAME ## _type_node \
3870       || type1 == unsigned_long_ ## NAME ## _type_node) \
3871     return unsignedp ? unsigned_long_ ## NAME ## _type_node \
3872                      : long_ ## NAME ## _type_node; \
3873   if (type1 == long_long_ ## NAME ## _type_node \
3874       || type1 == unsigned_long_long_ ## NAME ## _type_node) \
3875     return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
3876                      : long_long_ ## NAME ## _type_node;
3877
3878 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
3879   if (type1 == NAME ## _type_node \
3880       || type1 == u ## NAME ## _type_node) \
3881     return unsignedp ? u ## NAME ## _type_node \
3882                      : NAME ## _type_node;
3883
3884 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
3885   if (type1 == sat_ ## short_ ## NAME ## _type_node \
3886       || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
3887     return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
3888                      : sat_ ## short_ ## NAME ## _type_node; \
3889   if (type1 == sat_ ## NAME ## _type_node \
3890       || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
3891     return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
3892                      : sat_ ## NAME ## _type_node; \
3893   if (type1 == sat_ ## long_ ## NAME ## _type_node \
3894       || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
3895     return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
3896                      : sat_ ## long_ ## NAME ## _type_node; \
3897   if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
3898       || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
3899     return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
3900                      : sat_ ## long_long_ ## NAME ## _type_node;
3901
3902 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME)     \
3903   if (type1 == sat_ ## NAME ## _type_node \
3904       || type1 == sat_ ## u ## NAME ## _type_node) \
3905     return unsignedp ? sat_ ## u ## NAME ## _type_node \
3906                      : sat_ ## NAME ## _type_node;
3907
3908   C_COMMON_FIXED_TYPES (fract);
3909   C_COMMON_FIXED_TYPES_SAT (fract);
3910   C_COMMON_FIXED_TYPES (accum);
3911   C_COMMON_FIXED_TYPES_SAT (accum);
3912
3913   C_COMMON_FIXED_MODE_TYPES (qq);
3914   C_COMMON_FIXED_MODE_TYPES (hq);
3915   C_COMMON_FIXED_MODE_TYPES (sq);
3916   C_COMMON_FIXED_MODE_TYPES (dq);
3917   C_COMMON_FIXED_MODE_TYPES (tq);
3918   C_COMMON_FIXED_MODE_TYPES_SAT (qq);
3919   C_COMMON_FIXED_MODE_TYPES_SAT (hq);
3920   C_COMMON_FIXED_MODE_TYPES_SAT (sq);
3921   C_COMMON_FIXED_MODE_TYPES_SAT (dq);
3922   C_COMMON_FIXED_MODE_TYPES_SAT (tq);
3923   C_COMMON_FIXED_MODE_TYPES (ha);
3924   C_COMMON_FIXED_MODE_TYPES (sa);
3925   C_COMMON_FIXED_MODE_TYPES (da);
3926   C_COMMON_FIXED_MODE_TYPES (ta);
3927   C_COMMON_FIXED_MODE_TYPES_SAT (ha);
3928   C_COMMON_FIXED_MODE_TYPES_SAT (sa);
3929   C_COMMON_FIXED_MODE_TYPES_SAT (da);
3930   C_COMMON_FIXED_MODE_TYPES_SAT (ta);
3931
3932   /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
3933      the precision; they have precision set to match their range, but
3934      may use a wider mode to match an ABI.  If we change modes, we may
3935      wind up with bad conversions.  For INTEGER_TYPEs in C, must check
3936      the precision as well, so as to yield correct results for
3937      bit-field types.  C++ does not have these separate bit-field
3938      types, and producing a signed or unsigned variant of an
3939      ENUMERAL_TYPE may cause other problems as well.  */
3940
3941   if (!INTEGRAL_TYPE_P (type)
3942       || TYPE_UNSIGNED (type) == unsignedp)
3943     return type;
3944
3945 #define TYPE_OK(node)                                                       \
3946   (TYPE_MODE (type) == TYPE_MODE (node)                                     \
3947    && TYPE_PRECISION (type) == TYPE_PRECISION (node))
3948   if (TYPE_OK (signed_char_type_node))
3949     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
3950   if (TYPE_OK (integer_type_node))
3951     return unsignedp ? unsigned_type_node : integer_type_node;
3952   if (TYPE_OK (short_integer_type_node))
3953     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
3954   if (TYPE_OK (long_integer_type_node))
3955     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
3956   if (TYPE_OK (long_long_integer_type_node))
3957     return (unsignedp ? long_long_unsigned_type_node
3958             : long_long_integer_type_node);
3959
3960   for (i = 0; i < NUM_INT_N_ENTS; i ++)
3961     if (int_n_enabled_p[i]
3962         && TYPE_MODE (type) == int_n_data[i].m
3963         && TYPE_PRECISION (type) == int_n_data[i].bitsize)
3964       return (unsignedp ? int_n_trees[i].unsigned_type
3965               : int_n_trees[i].signed_type);
3966
3967   if (TYPE_OK (widest_integer_literal_type_node))
3968     return (unsignedp ? widest_unsigned_literal_type_node
3969             : widest_integer_literal_type_node);
3970
3971 #if HOST_BITS_PER_WIDE_INT >= 64
3972   if (TYPE_OK (intTI_type_node))
3973     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
3974 #endif
3975   if (TYPE_OK (intDI_type_node))
3976     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
3977   if (TYPE_OK (intSI_type_node))
3978     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
3979   if (TYPE_OK (intHI_type_node))
3980     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
3981   if (TYPE_OK (intQI_type_node))
3982     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
3983 #undef TYPE_OK
3984
3985   return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
3986 }
3987
3988 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP.  */
3989
3990 tree
3991 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
3992 {
3993   int i;
3994
3995   /* Extended integer types of the same width as a standard type have
3996      lesser rank, so those of the same width as int promote to int or
3997      unsigned int and are valid for printf formats expecting int or
3998      unsigned int.  To avoid such special cases, avoid creating
3999      extended integer types for bit-fields if a standard integer type
4000      is available.  */
4001   if (width == TYPE_PRECISION (integer_type_node))
4002     return unsignedp ? unsigned_type_node : integer_type_node;
4003   if (width == TYPE_PRECISION (signed_char_type_node))
4004     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
4005   if (width == TYPE_PRECISION (short_integer_type_node))
4006     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
4007   if (width == TYPE_PRECISION (long_integer_type_node))
4008     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
4009   if (width == TYPE_PRECISION (long_long_integer_type_node))
4010     return (unsignedp ? long_long_unsigned_type_node
4011             : long_long_integer_type_node);
4012   for (i = 0; i < NUM_INT_N_ENTS; i ++)
4013     if (int_n_enabled_p[i]
4014         && width == int_n_data[i].bitsize)
4015       return (unsignedp ? int_n_trees[i].unsigned_type
4016               : int_n_trees[i].signed_type);
4017   return build_nonstandard_integer_type (width, unsignedp);
4018 }
4019
4020 /* The C version of the register_builtin_type langhook.  */
4021
4022 void
4023 c_register_builtin_type (tree type, const char* name)
4024 {
4025   tree decl;
4026
4027   decl = build_decl (UNKNOWN_LOCATION,
4028                      TYPE_DECL, get_identifier (name), type);
4029   DECL_ARTIFICIAL (decl) = 1;
4030   if (!TYPE_NAME (type))
4031     TYPE_NAME (type) = decl;
4032   pushdecl (decl);
4033
4034   registered_builtin_types = tree_cons (0, type, registered_builtin_types);
4035 }
4036 \f
4037 /* Print an error message for invalid operands to arith operation
4038    CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
4039    LOCATION is the location of the message.  */
4040
4041 void
4042 binary_op_error (location_t location, enum tree_code code,
4043                  tree type0, tree type1)
4044 {
4045   const char *opname;
4046
4047   switch (code)
4048     {
4049     case PLUS_EXPR:
4050       opname = "+"; break;
4051     case MINUS_EXPR:
4052       opname = "-"; break;
4053     case MULT_EXPR:
4054       opname = "*"; break;
4055     case MAX_EXPR:
4056       opname = "max"; break;
4057     case MIN_EXPR:
4058       opname = "min"; break;
4059     case EQ_EXPR:
4060       opname = "=="; break;
4061     case NE_EXPR:
4062       opname = "!="; break;
4063     case LE_EXPR:
4064       opname = "<="; break;
4065     case GE_EXPR:
4066       opname = ">="; break;
4067     case LT_EXPR:
4068       opname = "<"; break;
4069     case GT_EXPR:
4070       opname = ">"; break;
4071     case LSHIFT_EXPR:
4072       opname = "<<"; break;
4073     case RSHIFT_EXPR:
4074       opname = ">>"; break;
4075     case TRUNC_MOD_EXPR:
4076     case FLOOR_MOD_EXPR:
4077       opname = "%"; break;
4078     case TRUNC_DIV_EXPR:
4079     case FLOOR_DIV_EXPR:
4080       opname = "/"; break;
4081     case BIT_AND_EXPR:
4082       opname = "&"; break;
4083     case BIT_IOR_EXPR:
4084       opname = "|"; break;
4085     case TRUTH_ANDIF_EXPR:
4086       opname = "&&"; break;
4087     case TRUTH_ORIF_EXPR:
4088       opname = "||"; break;
4089     case BIT_XOR_EXPR:
4090       opname = "^"; break;
4091     default:
4092       gcc_unreachable ();
4093     }
4094   error_at (location,
4095             "invalid operands to binary %s (have %qT and %qT)", opname,
4096             type0, type1);
4097 }
4098 \f
4099 /* Given an expression as a tree, return its original type.  Do this
4100    by stripping any conversion that preserves the sign and precision.  */
4101 static tree
4102 expr_original_type (tree expr)
4103 {
4104   STRIP_SIGN_NOPS (expr);
4105   return TREE_TYPE (expr);
4106 }
4107
4108 /* Subroutine of build_binary_op, used for comparison operations.
4109    See if the operands have both been converted from subword integer types
4110    and, if so, perhaps change them both back to their original type.
4111    This function is also responsible for converting the two operands
4112    to the proper common type for comparison.
4113
4114    The arguments of this function are all pointers to local variables
4115    of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
4116    RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
4117
4118    LOC is the location of the comparison.
4119
4120    If this function returns nonzero, it means that the comparison has
4121    a constant value.  What this function returns is an expression for
4122    that value.  */
4123
4124 tree
4125 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
4126                  tree *restype_ptr, enum tree_code *rescode_ptr)
4127 {
4128   tree type;
4129   tree op0 = *op0_ptr;
4130   tree op1 = *op1_ptr;
4131   int unsignedp0, unsignedp1;
4132   int real1, real2;
4133   tree primop0, primop1;
4134   enum tree_code code = *rescode_ptr;
4135
4136   /* Throw away any conversions to wider types
4137      already present in the operands.  */
4138
4139   primop0 = c_common_get_narrower (op0, &unsignedp0);
4140   primop1 = c_common_get_narrower (op1, &unsignedp1);
4141
4142   /* If primopN is first sign-extended from primopN's precision to opN's
4143      precision, then zero-extended from opN's precision to
4144      *restype_ptr precision, shortenings might be invalid.  */
4145   if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
4146       && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
4147       && !unsignedp0
4148       && TYPE_UNSIGNED (TREE_TYPE (op0)))
4149     primop0 = op0;
4150   if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
4151       && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
4152       && !unsignedp1
4153       && TYPE_UNSIGNED (TREE_TYPE (op1)))
4154     primop1 = op1;
4155
4156   /* Handle the case that OP0 does not *contain* a conversion
4157      but it *requires* conversion to FINAL_TYPE.  */
4158
4159   if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
4160     unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
4161   if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
4162     unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
4163
4164   /* If one of the operands must be floated, we cannot optimize.  */
4165   real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
4166   real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
4167
4168   /* If first arg is constant, swap the args (changing operation
4169      so value is preserved), for canonicalization.  Don't do this if
4170      the second arg is 0.  */
4171
4172   if (TREE_CONSTANT (primop0)
4173       && !integer_zerop (primop1) && !real_zerop (primop1)
4174       && !fixed_zerop (primop1))
4175     {
4176       tree tem = primop0;
4177       int temi = unsignedp0;
4178       primop0 = primop1;
4179       primop1 = tem;
4180       tem = op0;
4181       op0 = op1;
4182       op1 = tem;
4183       *op0_ptr = op0;
4184       *op1_ptr = op1;
4185       unsignedp0 = unsignedp1;
4186       unsignedp1 = temi;
4187       temi = real1;
4188       real1 = real2;
4189       real2 = temi;
4190
4191       switch (code)
4192         {
4193         case LT_EXPR:
4194           code = GT_EXPR;
4195           break;
4196         case GT_EXPR:
4197           code = LT_EXPR;
4198           break;
4199         case LE_EXPR:
4200           code = GE_EXPR;
4201           break;
4202         case GE_EXPR:
4203           code = LE_EXPR;
4204           break;
4205         default:
4206           break;
4207         }
4208       *rescode_ptr = code;
4209     }
4210
4211   /* If comparing an integer against a constant more bits wide,
4212      maybe we can deduce a value of 1 or 0 independent of the data.
4213      Or else truncate the constant now
4214      rather than extend the variable at run time.
4215
4216      This is only interesting if the constant is the wider arg.
4217      Also, it is not safe if the constant is unsigned and the
4218      variable arg is signed, since in this case the variable
4219      would be sign-extended and then regarded as unsigned.
4220      Our technique fails in this case because the lowest/highest
4221      possible unsigned results don't follow naturally from the
4222      lowest/highest possible values of the variable operand.
4223      For just EQ_EXPR and NE_EXPR there is another technique that
4224      could be used: see if the constant can be faithfully represented
4225      in the other operand's type, by truncating it and reextending it
4226      and see if that preserves the constant's value.  */
4227
4228   if (!real1 && !real2
4229       && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
4230       && TREE_CODE (primop1) == INTEGER_CST
4231       && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
4232     {
4233       int min_gt, max_gt, min_lt, max_lt;
4234       tree maxval, minval;
4235       /* 1 if comparison is nominally unsigned.  */
4236       int unsignedp = TYPE_UNSIGNED (*restype_ptr);
4237       tree val;
4238
4239       type = c_common_signed_or_unsigned_type (unsignedp0,
4240                                                TREE_TYPE (primop0));
4241
4242       maxval = TYPE_MAX_VALUE (type);
4243       minval = TYPE_MIN_VALUE (type);
4244
4245       if (unsignedp && !unsignedp0)
4246         *restype_ptr = c_common_signed_type (*restype_ptr);
4247
4248       if (TREE_TYPE (primop1) != *restype_ptr)
4249         {
4250           /* Convert primop1 to target type, but do not introduce
4251              additional overflow.  We know primop1 is an int_cst.  */
4252           primop1 = force_fit_type (*restype_ptr,
4253                                     wide_int::from
4254                                       (primop1,
4255                                        TYPE_PRECISION (*restype_ptr),
4256                                        TYPE_SIGN (TREE_TYPE (primop1))),
4257                                     0, TREE_OVERFLOW (primop1));
4258         }
4259       if (type != *restype_ptr)
4260         {
4261           minval = convert (*restype_ptr, minval);
4262           maxval = convert (*restype_ptr, maxval);
4263         }
4264
4265       min_gt = tree_int_cst_lt (primop1, minval);
4266       max_gt = tree_int_cst_lt (primop1, maxval);
4267       min_lt = tree_int_cst_lt (minval, primop1);
4268       max_lt = tree_int_cst_lt (maxval, primop1);
4269
4270       val = 0;
4271       /* This used to be a switch, but Genix compiler can't handle that.  */
4272       if (code == NE_EXPR)
4273         {
4274           if (max_lt || min_gt)
4275             val = truthvalue_true_node;
4276         }
4277       else if (code == EQ_EXPR)
4278         {
4279           if (max_lt || min_gt)
4280             val = truthvalue_false_node;
4281         }
4282       else if (code == LT_EXPR)
4283         {
4284           if (max_lt)
4285             val = truthvalue_true_node;
4286           if (!min_lt)
4287             val = truthvalue_false_node;
4288         }
4289       else if (code == GT_EXPR)
4290         {
4291           if (min_gt)
4292             val = truthvalue_true_node;
4293           if (!max_gt)
4294             val = truthvalue_false_node;
4295         }
4296       else if (code == LE_EXPR)
4297         {
4298           if (!max_gt)
4299             val = truthvalue_true_node;
4300           if (min_gt)
4301             val = truthvalue_false_node;
4302         }
4303       else if (code == GE_EXPR)
4304         {
4305           if (!min_lt)
4306             val = truthvalue_true_node;
4307           if (max_lt)
4308             val = truthvalue_false_node;
4309         }
4310
4311       /* If primop0 was sign-extended and unsigned comparison specd,
4312          we did a signed comparison above using the signed type bounds.
4313          But the comparison we output must be unsigned.
4314
4315          Also, for inequalities, VAL is no good; but if the signed
4316          comparison had *any* fixed result, it follows that the
4317          unsigned comparison just tests the sign in reverse
4318          (positive values are LE, negative ones GE).
4319          So we can generate an unsigned comparison
4320          against an extreme value of the signed type.  */
4321
4322       if (unsignedp && !unsignedp0)
4323         {
4324           if (val != 0)
4325             switch (code)
4326               {
4327               case LT_EXPR:
4328               case GE_EXPR:
4329                 primop1 = TYPE_MIN_VALUE (type);
4330                 val = 0;
4331                 break;
4332
4333               case LE_EXPR:
4334               case GT_EXPR:
4335                 primop1 = TYPE_MAX_VALUE (type);
4336                 val = 0;
4337                 break;
4338
4339               default:
4340                 break;
4341               }
4342           type = c_common_unsigned_type (type);
4343         }
4344
4345       if (TREE_CODE (primop0) != INTEGER_CST)
4346         {
4347           if (val == truthvalue_false_node)
4348             warning_at (loc, OPT_Wtype_limits,
4349                         "comparison is always false due to limited range of data type");
4350           if (val == truthvalue_true_node)
4351             warning_at (loc, OPT_Wtype_limits,
4352                         "comparison is always true due to limited range of data type");
4353         }
4354
4355       if (val != 0)
4356         {
4357           /* Don't forget to evaluate PRIMOP0 if it has side effects.  */
4358           if (TREE_SIDE_EFFECTS (primop0))
4359             return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
4360           return val;
4361         }
4362
4363       /* Value is not predetermined, but do the comparison
4364          in the type of the operand that is not constant.
4365          TYPE is already properly set.  */
4366     }
4367
4368   /* If either arg is decimal float and the other is float, find the
4369      proper common type to use for comparison.  */
4370   else if (real1 && real2
4371            && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
4372            && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
4373     type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
4374
4375   /* If either arg is decimal float and the other is float, fail.  */
4376   else if (real1 && real2
4377            && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
4378                || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
4379     return 0;
4380
4381   else if (real1 && real2
4382            && (TYPE_PRECISION (TREE_TYPE (primop0))
4383                == TYPE_PRECISION (TREE_TYPE (primop1))))
4384     type = TREE_TYPE (primop0);
4385
4386   /* If args' natural types are both narrower than nominal type
4387      and both extend in the same manner, compare them
4388      in the type of the wider arg.
4389      Otherwise must actually extend both to the nominal
4390      common type lest different ways of extending
4391      alter the result.
4392      (eg, (short)-1 == (unsigned short)-1  should be 0.)  */
4393
4394   else if (unsignedp0 == unsignedp1 && real1 == real2
4395            && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
4396            && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
4397     {
4398       type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
4399       type = c_common_signed_or_unsigned_type (unsignedp0
4400                                                || TYPE_UNSIGNED (*restype_ptr),
4401                                                type);
4402       /* Make sure shorter operand is extended the right way
4403          to match the longer operand.  */
4404       primop0
4405         = convert (c_common_signed_or_unsigned_type (unsignedp0,
4406                                                      TREE_TYPE (primop0)),
4407                    primop0);
4408       primop1
4409         = convert (c_common_signed_or_unsigned_type (unsignedp1,
4410                                                      TREE_TYPE (primop1)),
4411                    primop1);
4412     }
4413   else
4414     {
4415       /* Here we must do the comparison on the nominal type
4416          using the args exactly as we received them.  */
4417       type = *restype_ptr;
4418       primop0 = op0;
4419       primop1 = op1;
4420
4421       if (!real1 && !real2 && integer_zerop (primop1)
4422           && TYPE_UNSIGNED (*restype_ptr))
4423         {
4424           tree value = 0;
4425           /* All unsigned values are >= 0, so we warn.  However,
4426              if OP0 is a constant that is >= 0, the signedness of
4427              the comparison isn't an issue, so suppress the
4428              warning.  */
4429           bool warn = 
4430             warn_type_limits && !in_system_header_at (loc)
4431             && !(TREE_CODE (primop0) == INTEGER_CST
4432                  && !TREE_OVERFLOW (convert (c_common_signed_type (type),
4433                                              primop0)))
4434             /* Do not warn for enumeration types.  */
4435             && (TREE_CODE (expr_original_type (primop0)) != ENUMERAL_TYPE);
4436           
4437           switch (code)
4438             {
4439             case GE_EXPR:
4440               if (warn)
4441                 warning_at (loc, OPT_Wtype_limits,
4442                             "comparison of unsigned expression >= 0 is always true");
4443               value = truthvalue_true_node;
4444               break;
4445
4446             case LT_EXPR:
4447               if (warn)
4448                 warning_at (loc, OPT_Wtype_limits,
4449                             "comparison of unsigned expression < 0 is always false");
4450               value = truthvalue_false_node;
4451               break;
4452
4453             default:
4454               break;
4455             }
4456
4457           if (value != 0)
4458             {
4459               /* Don't forget to evaluate PRIMOP0 if it has side effects.  */
4460               if (TREE_SIDE_EFFECTS (primop0))
4461                 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
4462                                primop0, value);
4463               return value;
4464             }
4465         }
4466     }
4467
4468   *op0_ptr = convert (type, primop0);
4469   *op1_ptr = convert (type, primop1);
4470
4471   *restype_ptr = truthvalue_type_node;
4472
4473   return 0;
4474 }
4475 \f
4476 /* Return a tree for the sum or difference (RESULTCODE says which)
4477    of pointer PTROP and integer INTOP.  */
4478
4479 tree
4480 pointer_int_sum (location_t loc, enum tree_code resultcode,
4481                  tree ptrop, tree intop, bool complain)
4482 {
4483   tree size_exp, ret;
4484
4485   /* The result is a pointer of the same type that is being added.  */
4486   tree result_type = TREE_TYPE (ptrop);
4487
4488   if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
4489     {
4490       if (complain && warn_pointer_arith)
4491         pedwarn (loc, OPT_Wpointer_arith,
4492                  "pointer of type %<void *%> used in arithmetic");
4493       else if (!complain)
4494         return error_mark_node;
4495       size_exp = integer_one_node;
4496     }
4497   else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
4498     {
4499       if (complain && warn_pointer_arith)
4500         pedwarn (loc, OPT_Wpointer_arith,
4501                  "pointer to a function used in arithmetic");
4502       else if (!complain)
4503         return error_mark_node;
4504       size_exp = integer_one_node;
4505     }
4506   else
4507     size_exp = size_in_bytes (TREE_TYPE (result_type));
4508
4509   /* We are manipulating pointer values, so we don't need to warn
4510      about relying on undefined signed overflow.  We disable the
4511      warning here because we use integer types so fold won't know that
4512      they are really pointers.  */
4513   fold_defer_overflow_warnings ();
4514
4515   /* If what we are about to multiply by the size of the elements
4516      contains a constant term, apply distributive law
4517      and multiply that constant term separately.
4518      This helps produce common subexpressions.  */
4519   if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
4520       && !TREE_CONSTANT (intop)
4521       && TREE_CONSTANT (TREE_OPERAND (intop, 1))
4522       && TREE_CONSTANT (size_exp)
4523       /* If the constant comes from pointer subtraction,
4524          skip this optimization--it would cause an error.  */
4525       && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
4526       /* If the constant is unsigned, and smaller than the pointer size,
4527          then we must skip this optimization.  This is because it could cause
4528          an overflow error if the constant is negative but INTOP is not.  */
4529       && (!TYPE_UNSIGNED (TREE_TYPE (intop))
4530           || (TYPE_PRECISION (TREE_TYPE (intop))
4531               == TYPE_PRECISION (TREE_TYPE (ptrop)))))
4532     {
4533       enum tree_code subcode = resultcode;
4534       tree int_type = TREE_TYPE (intop);
4535       if (TREE_CODE (intop) == MINUS_EXPR)
4536         subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
4537       /* Convert both subexpression types to the type of intop,
4538          because weird cases involving pointer arithmetic
4539          can result in a sum or difference with different type args.  */
4540       ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
4541                                subcode, ptrop,
4542                                convert (int_type, TREE_OPERAND (intop, 1)), 1);
4543       intop = convert (int_type, TREE_OPERAND (intop, 0));
4544     }
4545
4546   /* Convert the integer argument to a type the same size as sizetype
4547      so the multiply won't overflow spuriously.  */
4548   if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
4549       || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
4550     intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
4551                                              TYPE_UNSIGNED (sizetype)), intop);
4552
4553   /* Replace the integer argument with a suitable product by the object size.
4554      Do this multiplication as signed, then convert to the appropriate type
4555      for the pointer operation and disregard an overflow that occurred only
4556      because of the sign-extension change in the latter conversion.  */
4557   {
4558     tree t = build_binary_op (loc,
4559                               MULT_EXPR, intop,
4560                               convert (TREE_TYPE (intop), size_exp), 1);
4561     intop = convert (sizetype, t);
4562     if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
4563       intop = wide_int_to_tree (TREE_TYPE (intop), intop);
4564   }
4565
4566   /* Create the sum or difference.  */
4567   if (resultcode == MINUS_EXPR)
4568     intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
4569
4570   ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
4571
4572   fold_undefer_and_ignore_overflow_warnings ();
4573
4574   return ret;
4575 }
4576 \f
4577 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
4578    and if NON_CONST is known not to be permitted in an evaluated part
4579    of a constant expression.  */
4580
4581 tree
4582 c_wrap_maybe_const (tree expr, bool non_const)
4583 {
4584   bool nowarning = TREE_NO_WARNING (expr);
4585   location_t loc = EXPR_LOCATION (expr);
4586
4587   /* This should never be called for C++.  */
4588   if (c_dialect_cxx ())
4589     gcc_unreachable ();
4590
4591   /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING.  */
4592   STRIP_TYPE_NOPS (expr);
4593   expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
4594   C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
4595   if (nowarning)
4596     TREE_NO_WARNING (expr) = 1;
4597   protected_set_expr_location (expr, loc);
4598
4599   return expr;
4600 }
4601
4602 /* Wrap a SAVE_EXPR around EXPR, if appropriate.  Like save_expr, but
4603    for C folds the inside expression and wraps a C_MAYBE_CONST_EXPR
4604    around the SAVE_EXPR if needed so that c_fully_fold does not need
4605    to look inside SAVE_EXPRs.  */
4606
4607 tree
4608 c_save_expr (tree expr)
4609 {
4610   bool maybe_const = true;
4611   if (c_dialect_cxx ())
4612     return save_expr (expr);
4613   expr = c_fully_fold (expr, false, &maybe_const);
4614   expr = save_expr (expr);
4615   if (!maybe_const)
4616     expr = c_wrap_maybe_const (expr, true);
4617   return expr;
4618 }
4619
4620 /* Return whether EXPR is a declaration whose address can never be
4621    NULL.  */
4622
4623 bool
4624 decl_with_nonnull_addr_p (const_tree expr)
4625 {
4626   return (DECL_P (expr)
4627           && (TREE_CODE (expr) == PARM_DECL
4628               || TREE_CODE (expr) == LABEL_DECL
4629               || !DECL_WEAK (expr)));
4630 }
4631
4632 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
4633    or for an `if' or `while' statement or ?..: exp.  It should already
4634    have been validated to be of suitable type; otherwise, a bad
4635    diagnostic may result.
4636
4637    The EXPR is located at LOCATION.
4638
4639    This preparation consists of taking the ordinary
4640    representation of an expression expr and producing a valid tree
4641    boolean expression describing whether expr is nonzero.  We could
4642    simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
4643    but we optimize comparisons, &&, ||, and !.
4644
4645    The resulting type should always be `truthvalue_type_node'.  */
4646
4647 tree
4648 c_common_truthvalue_conversion (location_t location, tree expr)
4649 {
4650   switch (TREE_CODE (expr))
4651     {
4652     case EQ_EXPR:   case NE_EXPR:   case UNEQ_EXPR: case LTGT_EXPR:
4653     case LE_EXPR:   case GE_EXPR:   case LT_EXPR:   case GT_EXPR:
4654     case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
4655     case ORDERED_EXPR: case UNORDERED_EXPR:
4656       if (TREE_TYPE (expr) == truthvalue_type_node)
4657         return expr;
4658       expr = build2 (TREE_CODE (expr), truthvalue_type_node,
4659                      TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
4660       goto ret;
4661
4662     case TRUTH_ANDIF_EXPR:
4663     case TRUTH_ORIF_EXPR:
4664     case TRUTH_AND_EXPR:
4665     case TRUTH_OR_EXPR:
4666     case TRUTH_XOR_EXPR:
4667       if (TREE_TYPE (expr) == truthvalue_type_node)
4668         return expr;
4669       expr = build2 (TREE_CODE (expr), truthvalue_type_node,
4670                      c_common_truthvalue_conversion (location,
4671                                                      TREE_OPERAND (expr, 0)),
4672                      c_common_truthvalue_conversion (location,
4673                                                      TREE_OPERAND (expr, 1)));
4674       goto ret;
4675
4676     case TRUTH_NOT_EXPR:
4677       if (TREE_TYPE (expr) == truthvalue_type_node)
4678         return expr;
4679       expr = build1 (TREE_CODE (expr), truthvalue_type_node,
4680                      c_common_truthvalue_conversion (location,
4681                                                      TREE_OPERAND (expr, 0)));
4682       goto ret;
4683
4684     case ERROR_MARK:
4685       return expr;
4686
4687     case INTEGER_CST:
4688       return integer_zerop (expr) ? truthvalue_false_node
4689                                   : truthvalue_true_node;
4690
4691     case REAL_CST:
4692       return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
4693              ? truthvalue_true_node
4694              : truthvalue_false_node;
4695
4696     case FIXED_CST:
4697       return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
4698                             &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
4699              ? truthvalue_true_node
4700              : truthvalue_false_node;
4701
4702     case FUNCTION_DECL:
4703       expr = build_unary_op (location, ADDR_EXPR, expr, 0);
4704       /* Fall through.  */
4705
4706     case ADDR_EXPR:
4707       {
4708         tree inner = TREE_OPERAND (expr, 0);
4709         if (decl_with_nonnull_addr_p (inner))
4710           {
4711             /* Common Ada/Pascal programmer's mistake.  */
4712             warning_at (location,
4713                         OPT_Waddress,
4714                         "the address of %qD will always evaluate as %<true%>",
4715                         inner);
4716             return truthvalue_true_node;
4717           }
4718         break;
4719       }
4720
4721     case COMPLEX_EXPR:
4722       expr = build_binary_op (EXPR_LOCATION (expr),
4723                               (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
4724                                ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
4725                 c_common_truthvalue_conversion (location,
4726                                                 TREE_OPERAND (expr, 0)),
4727                 c_common_truthvalue_conversion (location,
4728                                                 TREE_OPERAND (expr, 1)),
4729                               0);
4730       goto ret;
4731
4732     case NEGATE_EXPR:
4733     case ABS_EXPR:
4734     case FLOAT_EXPR:
4735     case EXCESS_PRECISION_EXPR:
4736       /* These don't change whether an object is nonzero or zero.  */
4737       return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
4738
4739     case LROTATE_EXPR:
4740     case RROTATE_EXPR:
4741       /* These don't change whether an object is zero or nonzero, but
4742          we can't ignore them if their second arg has side-effects.  */
4743       if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
4744         {
4745           expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
4746                          TREE_OPERAND (expr, 1),
4747                          c_common_truthvalue_conversion
4748                          (location, TREE_OPERAND (expr, 0)));
4749           goto ret;
4750         }
4751       else
4752         return c_common_truthvalue_conversion (location,
4753                                                TREE_OPERAND (expr, 0));
4754
4755     case COND_EXPR:
4756       /* Distribute the conversion into the arms of a COND_EXPR.  */
4757       if (c_dialect_cxx ())
4758         {
4759           tree op1 = TREE_OPERAND (expr, 1);
4760           tree op2 = TREE_OPERAND (expr, 2);
4761           /* In C++ one of the arms might have void type if it is throw.  */
4762           if (!VOID_TYPE_P (TREE_TYPE (op1)))
4763             op1 = c_common_truthvalue_conversion (location, op1);
4764           if (!VOID_TYPE_P (TREE_TYPE (op2)))
4765             op2 = c_common_truthvalue_conversion (location, op2);
4766           expr = fold_build3_loc (location, COND_EXPR, truthvalue_type_node,
4767                                   TREE_OPERAND (expr, 0), op1, op2);
4768           goto ret;
4769         }
4770       else
4771         {
4772           /* Folding will happen later for C.  */
4773           expr = build3 (COND_EXPR, truthvalue_type_node,
4774                          TREE_OPERAND (expr, 0),
4775                          c_common_truthvalue_conversion (location,
4776                                                          TREE_OPERAND (expr, 1)),
4777                          c_common_truthvalue_conversion (location,
4778                                                          TREE_OPERAND (expr, 2)));
4779           goto ret;
4780         }
4781
4782     CASE_CONVERT:
4783       {
4784         tree totype = TREE_TYPE (expr);
4785         tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
4786
4787         /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
4788            since that affects how `default_conversion' will behave.  */
4789         if (TREE_CODE (totype) == REFERENCE_TYPE
4790             || TREE_CODE (fromtype) == REFERENCE_TYPE)
4791           break;
4792         /* Don't strip a conversion from C++0x scoped enum, since they
4793            don't implicitly convert to other types.  */
4794         if (TREE_CODE (fromtype) == ENUMERAL_TYPE
4795             && ENUM_IS_SCOPED (fromtype))
4796           break;
4797         /* If this isn't narrowing the argument, we can ignore it.  */
4798         if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
4799           return c_common_truthvalue_conversion (location,
4800                                                  TREE_OPERAND (expr, 0));
4801       }
4802       break;
4803
4804     case MODIFY_EXPR:
4805       if (!TREE_NO_WARNING (expr)
4806           && warn_parentheses)
4807         {
4808           warning (OPT_Wparentheses,
4809                    "suggest parentheses around assignment used as truth value");
4810           TREE_NO_WARNING (expr) = 1;
4811         }
4812       break;
4813
4814     default:
4815       break;
4816     }
4817
4818   if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
4819     {
4820       tree t = (in_late_binary_op ? save_expr (expr) : c_save_expr (expr));
4821       expr = (build_binary_op
4822               (EXPR_LOCATION (expr),
4823                (TREE_SIDE_EFFECTS (expr)
4824                 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
4825         c_common_truthvalue_conversion
4826                (location,
4827                 build_unary_op (location, REALPART_EXPR, t, 0)),
4828         c_common_truthvalue_conversion
4829                (location,
4830                 build_unary_op (location, IMAGPART_EXPR, t, 0)),
4831                0));
4832       goto ret;
4833     }
4834
4835   if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
4836     {
4837       tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
4838                                           FCONST0 (TYPE_MODE
4839                                                    (TREE_TYPE (expr))));
4840       return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, 1);
4841     }
4842   else
4843     return build_binary_op (location, NE_EXPR, expr, integer_zero_node, 1);
4844
4845  ret:
4846   protected_set_expr_location (expr, location);
4847   return expr;
4848 }
4849 \f
4850 static void def_builtin_1  (enum built_in_function fncode,
4851                             const char *name,
4852                             enum built_in_class fnclass,
4853                             tree fntype, tree libtype,
4854                             bool both_p, bool fallback_p, bool nonansi_p,
4855                             tree fnattrs, bool implicit_p);
4856
4857
4858 /* Apply the TYPE_QUALS to the new DECL.  */
4859
4860 void
4861 c_apply_type_quals_to_decl (int type_quals, tree decl)
4862 {
4863   tree type = TREE_TYPE (decl);
4864
4865   if (type == error_mark_node)
4866     return;
4867
4868   if ((type_quals & TYPE_QUAL_CONST)
4869       || (type && TREE_CODE (type) == REFERENCE_TYPE))
4870     /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
4871        constructor can produce constant init, so rely on cp_finish_decl to
4872        clear TREE_READONLY if the variable has non-constant init.  */
4873     TREE_READONLY (decl) = 1;
4874   if (type_quals & TYPE_QUAL_VOLATILE)
4875     {
4876       TREE_SIDE_EFFECTS (decl) = 1;
4877       TREE_THIS_VOLATILE (decl) = 1;
4878     }
4879   if (type_quals & TYPE_QUAL_RESTRICT)
4880     {
4881       while (type && TREE_CODE (type) == ARRAY_TYPE)
4882         /* Allow 'restrict' on arrays of pointers.
4883            FIXME currently we just ignore it.  */
4884         type = TREE_TYPE (type);
4885       if (!type
4886           || !POINTER_TYPE_P (type)
4887           || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
4888         error ("invalid use of %<restrict%>");
4889     }
4890 }
4891
4892 struct c_type_hasher : ggc_hasher<tree>
4893 {
4894   static hashval_t hash (tree);
4895   static bool equal (tree, tree);
4896 };
4897
4898 /* Hash function for the problem of multiple type definitions in
4899    different files.  This must hash all types that will compare
4900    equal via comptypes to the same value.  In practice it hashes
4901    on some of the simple stuff and leaves the details to comptypes.  */
4902
4903 hashval_t
4904 c_type_hasher::hash (tree t)
4905 {
4906   int n_elements;
4907   int shift, size;
4908   tree t2;
4909   switch (TREE_CODE (t))
4910     {
4911     /* For pointers, hash on pointee type plus some swizzling.  */
4912     case POINTER_TYPE:
4913       return hash (TREE_TYPE (t)) ^ 0x3003003;
4914     /* Hash on number of elements and total size.  */
4915     case ENUMERAL_TYPE:
4916       shift = 3;
4917       t2 = TYPE_VALUES (t);
4918       break;
4919     case RECORD_TYPE:
4920       shift = 0;
4921       t2 = TYPE_FIELDS (t);
4922       break;
4923     case QUAL_UNION_TYPE:
4924       shift = 1;
4925       t2 = TYPE_FIELDS (t);
4926       break;
4927     case UNION_TYPE:
4928       shift = 2;
4929       t2 = TYPE_FIELDS (t);
4930       break;
4931     default:
4932       gcc_unreachable ();
4933     }
4934   /* FIXME: We want to use a DECL_CHAIN iteration method here, but
4935      TYPE_VALUES of ENUMERAL_TYPEs is stored as a TREE_LIST.  */
4936   n_elements = list_length (t2);
4937   /* We might have a VLA here.  */
4938   if (TREE_CODE (TYPE_SIZE (t)) != INTEGER_CST)
4939     size = 0;
4940   else
4941     size = TREE_INT_CST_LOW (TYPE_SIZE (t));
4942   return ((size << 24) | (n_elements << shift));
4943 }
4944
4945 bool
4946 c_type_hasher::equal (tree t1, tree t2)
4947 {
4948   return lang_hooks.types_compatible_p (t1, t2);
4949 }
4950
4951 static GTY(()) hash_table<c_type_hasher> *type_hash_table;
4952
4953 /* Return the typed-based alias set for T, which may be an expression
4954    or a type.  Return -1 if we don't do anything special.  */
4955
4956 alias_set_type
4957 c_common_get_alias_set (tree t)
4958 {
4959   tree u;
4960
4961   /* For VLAs, use the alias set of the element type rather than the
4962      default of alias set 0 for types compared structurally.  */
4963   if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
4964     {
4965       if (TREE_CODE (t) == ARRAY_TYPE)
4966         return get_alias_set (TREE_TYPE (t));
4967       return -1;
4968     }
4969
4970   /* Permit type-punning when accessing a union, provided the access
4971      is directly through the union.  For example, this code does not
4972      permit taking the address of a union member and then storing
4973      through it.  Even the type-punning allowed here is a GCC
4974      extension, albeit a common and useful one; the C standard says
4975      that such accesses have implementation-defined behavior.  */
4976   for (u = t;
4977        TREE_CODE (u) == COMPONENT_REF || TREE_CODE (u) == ARRAY_REF;
4978        u = TREE_OPERAND (u, 0))
4979     if (TREE_CODE (u) == COMPONENT_REF
4980         && TREE_CODE (TREE_TYPE (TREE_OPERAND (u, 0))) == UNION_TYPE)
4981       return 0;
4982
4983   /* That's all the expressions we handle specially.  */
4984   if (!TYPE_P (t))
4985     return -1;
4986
4987   /* The C standard guarantees that any object may be accessed via an
4988      lvalue that has character type.  */
4989   if (t == char_type_node
4990       || t == signed_char_type_node
4991       || t == unsigned_char_type_node)
4992     return 0;
4993
4994   /* The C standard specifically allows aliasing between signed and
4995      unsigned variants of the same type.  We treat the signed
4996      variant as canonical.  */
4997   if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
4998     {
4999       tree t1 = c_common_signed_type (t);
5000
5001       /* t1 == t can happen for boolean nodes which are always unsigned.  */
5002       if (t1 != t)
5003         return get_alias_set (t1);
5004     }
5005
5006   /* Handle the case of multiple type nodes referring to "the same" type,
5007      which occurs with IMA.  These share an alias set.  FIXME:  Currently only
5008      C90 is handled.  (In C99 type compatibility is not transitive, which
5009      complicates things mightily. The alias set splay trees can theoretically
5010      represent this, but insertion is tricky when you consider all the
5011      different orders things might arrive in.) */
5012
5013   if (c_language != clk_c || flag_isoc99)
5014     return -1;
5015
5016   /* Save time if there's only one input file.  */
5017   if (num_in_fnames == 1)
5018     return -1;
5019
5020   /* Pointers need special handling if they point to any type that
5021      needs special handling (below).  */
5022   if (TREE_CODE (t) == POINTER_TYPE)
5023     {
5024       tree t2;
5025       /* Find bottom type under any nested POINTERs.  */
5026       for (t2 = TREE_TYPE (t);
5027            TREE_CODE (t2) == POINTER_TYPE;
5028            t2 = TREE_TYPE (t2))
5029         ;
5030       if (TREE_CODE (t2) != RECORD_TYPE
5031           && TREE_CODE (t2) != ENUMERAL_TYPE
5032           && TREE_CODE (t2) != QUAL_UNION_TYPE
5033           && TREE_CODE (t2) != UNION_TYPE)
5034         return -1;
5035       if (TYPE_SIZE (t2) == 0)
5036         return -1;
5037     }
5038   /* These are the only cases that need special handling.  */
5039   if (TREE_CODE (t) != RECORD_TYPE
5040       && TREE_CODE (t) != ENUMERAL_TYPE
5041       && TREE_CODE (t) != QUAL_UNION_TYPE
5042       && TREE_CODE (t) != UNION_TYPE
5043       && TREE_CODE (t) != POINTER_TYPE)
5044     return -1;
5045   /* Undefined? */
5046   if (TYPE_SIZE (t) == 0)
5047     return -1;
5048
5049   /* Look up t in hash table.  Only one of the compatible types within each
5050      alias set is recorded in the table.  */
5051   if (!type_hash_table)
5052     type_hash_table = hash_table<c_type_hasher>::create_ggc (1021);
5053   tree *slot = type_hash_table->find_slot (t, INSERT);
5054   if (*slot != NULL)
5055     {
5056       TYPE_ALIAS_SET (t) = TYPE_ALIAS_SET ((tree)*slot);
5057       return TYPE_ALIAS_SET ((tree)*slot);
5058     }
5059   else
5060     /* Our caller will assign and record (in t) a new alias set; all we need
5061        to do is remember t in the hash table.  */
5062     *slot = t;
5063
5064   return -1;
5065 }
5066 \f
5067 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
5068    the IS_SIZEOF parameter indicates which operator is being applied.
5069    The COMPLAIN flag controls whether we should diagnose possibly
5070    ill-formed constructs or not.  LOC is the location of the SIZEOF or
5071    TYPEOF operator.  If MIN_ALIGNOF, the least alignment required for
5072    a type in any context should be returned, rather than the normal
5073    alignment for that type.  */
5074
5075 tree
5076 c_sizeof_or_alignof_type (location_t loc,
5077                           tree type, bool is_sizeof, bool min_alignof,
5078                           int complain)
5079 {
5080   const char *op_name;
5081   tree value = NULL;
5082   enum tree_code type_code = TREE_CODE (type);
5083
5084   op_name = is_sizeof ? "sizeof" : "__alignof__";
5085
5086   if (type_code == FUNCTION_TYPE)
5087     {
5088       if (is_sizeof)
5089         {
5090           if (complain && warn_pointer_arith)
5091             pedwarn (loc, OPT_Wpointer_arith,
5092                      "invalid application of %<sizeof%> to a function type");
5093           else if (!complain)
5094             return error_mark_node;
5095           value = size_one_node;
5096         }
5097       else
5098         {
5099           if (complain)
5100             {
5101               if (c_dialect_cxx ())
5102                 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
5103                          "%<alignof%> applied to a function type");
5104               else
5105                 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
5106                          "%<_Alignof%> applied to a function type");
5107             }
5108           value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
5109         }
5110     }
5111   else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
5112     {
5113       if (type_code == VOID_TYPE
5114           && complain && warn_pointer_arith)
5115         pedwarn (loc, OPT_Wpointer_arith,
5116                  "invalid application of %qs to a void type", op_name);
5117       else if (!complain)
5118         return error_mark_node;
5119       value = size_one_node;
5120     }
5121   else if (!COMPLETE_TYPE_P (type)
5122            && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
5123     {
5124       if (complain)
5125         error_at (loc, "invalid application of %qs to incomplete type %qT",
5126                   op_name, type);
5127       return error_mark_node;
5128     }
5129   else if (c_dialect_cxx () && type_code == ARRAY_TYPE
5130            && !COMPLETE_TYPE_P (TREE_TYPE (type)))
5131     {
5132       if (complain)
5133         error_at (loc, "invalid application of %qs to array type %qT of "
5134                   "incomplete element type", op_name, type);
5135       return error_mark_node;
5136     }
5137   else
5138     {
5139       if (is_sizeof)
5140         /* Convert in case a char is more than one unit.  */
5141         value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
5142                                 size_int (TYPE_PRECISION (char_type_node)
5143                                           / BITS_PER_UNIT));
5144       else if (min_alignof)
5145         value = size_int (min_align_of_type (type));
5146       else
5147         value = size_int (TYPE_ALIGN_UNIT (type));
5148     }
5149
5150   /* VALUE will have the middle-end integer type sizetype.
5151      However, we should really return a value of type `size_t',
5152      which is just a typedef for an ordinary integer type.  */
5153   value = fold_convert_loc (loc, size_type_node, value);
5154
5155   return value;
5156 }
5157
5158 /* Implement the __alignof keyword: Return the minimum required
5159    alignment of EXPR, measured in bytes.  For VAR_DECLs,
5160    FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
5161    from an "aligned" __attribute__ specification).  LOC is the
5162    location of the ALIGNOF operator.  */
5163
5164 tree
5165 c_alignof_expr (location_t loc, tree expr)
5166 {
5167   tree t;
5168
5169   if (VAR_OR_FUNCTION_DECL_P (expr))
5170     t = size_int (DECL_ALIGN_UNIT (expr));
5171
5172   else if (TREE_CODE (expr) == COMPONENT_REF
5173            && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
5174     {
5175       error_at (loc, "%<__alignof%> applied to a bit-field");
5176       t = size_one_node;
5177     }
5178   else if (TREE_CODE (expr) == COMPONENT_REF
5179            && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
5180     t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
5181
5182   else if (TREE_CODE (expr) == INDIRECT_REF)
5183     {
5184       tree t = TREE_OPERAND (expr, 0);
5185       tree best = t;
5186       int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
5187
5188       while (CONVERT_EXPR_P (t)
5189              && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
5190         {
5191           int thisalign;
5192
5193           t = TREE_OPERAND (t, 0);
5194           thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
5195           if (thisalign > bestalign)
5196             best = t, bestalign = thisalign;
5197         }
5198       return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
5199     }
5200   else
5201     return c_alignof (loc, TREE_TYPE (expr));
5202
5203   return fold_convert_loc (loc, size_type_node, t);
5204 }
5205 \f
5206 /* Handle C and C++ default attributes.  */
5207
5208 enum built_in_attribute
5209 {
5210 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
5211 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
5212 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
5213 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
5214 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
5215 #include "builtin-attrs.def"
5216 #undef DEF_ATTR_NULL_TREE
5217 #undef DEF_ATTR_INT
5218 #undef DEF_ATTR_STRING
5219 #undef DEF_ATTR_IDENT
5220 #undef DEF_ATTR_TREE_LIST
5221   ATTR_LAST
5222 };
5223
5224 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
5225
5226 static void c_init_attributes (void);
5227
5228 enum c_builtin_type
5229 {
5230 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
5231 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
5232 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
5233 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
5234 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
5235 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
5236 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
5237 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5238                             ARG6) NAME,
5239 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5240                             ARG6, ARG7) NAME,
5241 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5242                             ARG6, ARG7, ARG8) NAME,
5243 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
5244 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
5245 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
5246 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
5247 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
5248 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
5249                                 NAME,
5250 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5251                                 ARG6, ARG7) NAME,
5252 #define DEF_FUNCTION_TYPE_VAR_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5253                                  ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
5254 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
5255 #include "builtin-types.def"
5256 #undef DEF_PRIMITIVE_TYPE
5257 #undef DEF_FUNCTION_TYPE_0
5258 #undef DEF_FUNCTION_TYPE_1
5259 #undef DEF_FUNCTION_TYPE_2
5260 #undef DEF_FUNCTION_TYPE_3
5261 #undef DEF_FUNCTION_TYPE_4
5262 #undef DEF_FUNCTION_TYPE_5
5263 #undef DEF_FUNCTION_TYPE_6
5264 #undef DEF_FUNCTION_TYPE_7
5265 #undef DEF_FUNCTION_TYPE_8
5266 #undef DEF_FUNCTION_TYPE_VAR_0
5267 #undef DEF_FUNCTION_TYPE_VAR_1
5268 #undef DEF_FUNCTION_TYPE_VAR_2
5269 #undef DEF_FUNCTION_TYPE_VAR_3
5270 #undef DEF_FUNCTION_TYPE_VAR_4
5271 #undef DEF_FUNCTION_TYPE_VAR_5
5272 #undef DEF_FUNCTION_TYPE_VAR_7
5273 #undef DEF_FUNCTION_TYPE_VAR_11
5274 #undef DEF_POINTER_TYPE
5275   BT_LAST
5276 };
5277
5278 typedef enum c_builtin_type builtin_type;
5279
5280 /* A temporary array for c_common_nodes_and_builtins.  Used in
5281    communication with def_fn_type.  */
5282 static tree builtin_types[(int) BT_LAST + 1];
5283
5284 /* A helper function for c_common_nodes_and_builtins.  Build function type
5285    for DEF with return type RET and N arguments.  If VAR is true, then the
5286    function should be variadic after those N arguments.
5287
5288    Takes special care not to ICE if any of the types involved are
5289    error_mark_node, which indicates that said type is not in fact available
5290    (see builtin_type_for_size).  In which case the function type as a whole
5291    should be error_mark_node.  */
5292
5293 static void
5294 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
5295 {
5296   tree t;
5297   tree *args = XALLOCAVEC (tree, n);
5298   va_list list;
5299   int i;
5300
5301   va_start (list, n);
5302   for (i = 0; i < n; ++i)
5303     {
5304       builtin_type a = (builtin_type) va_arg (list, int);
5305       t = builtin_types[a];
5306       if (t == error_mark_node)
5307         goto egress;
5308       args[i] = t;
5309     }
5310
5311   t = builtin_types[ret];
5312   if (t == error_mark_node)
5313     goto egress;
5314   if (var)
5315     t = build_varargs_function_type_array (t, n, args);
5316   else
5317     t = build_function_type_array (t, n, args);
5318
5319  egress:
5320   builtin_types[def] = t;
5321   va_end (list);
5322 }
5323
5324 /* Build builtin functions common to both C and C++ language
5325    frontends.  */
5326
5327 static void
5328 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
5329 {
5330 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
5331   builtin_types[ENUM] = VALUE;
5332 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
5333   def_fn_type (ENUM, RETURN, 0, 0);
5334 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
5335   def_fn_type (ENUM, RETURN, 0, 1, ARG1);
5336 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
5337   def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
5338 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
5339   def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
5340 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
5341   def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
5342 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
5343   def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
5344 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5345                             ARG6)                                       \
5346   def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
5347 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5348                             ARG6, ARG7)                                 \
5349   def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
5350 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5351                             ARG6, ARG7, ARG8)                           \
5352   def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,  \
5353                ARG7, ARG8);
5354 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
5355   def_fn_type (ENUM, RETURN, 1, 0);
5356 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
5357   def_fn_type (ENUM, RETURN, 1, 1, ARG1);
5358 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
5359   def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
5360 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
5361   def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
5362 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
5363   def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
5364 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
5365   def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
5366 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5367                                 ARG6, ARG7)                             \
5368   def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
5369 #define DEF_FUNCTION_TYPE_VAR_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
5370                                  ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
5371   def_fn_type (ENUM, RETURN, 1, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,      \
5372                ARG7, ARG8, ARG9, ARG10, ARG11);
5373 #define DEF_POINTER_TYPE(ENUM, TYPE) \
5374   builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
5375
5376 #include "builtin-types.def"
5377
5378 #undef DEF_PRIMITIVE_TYPE
5379 #undef DEF_FUNCTION_TYPE_0
5380 #undef DEF_FUNCTION_TYPE_1
5381 #undef DEF_FUNCTION_TYPE_2
5382 #undef DEF_FUNCTION_TYPE_3
5383 #undef DEF_FUNCTION_TYPE_4
5384 #undef DEF_FUNCTION_TYPE_5
5385 #undef DEF_FUNCTION_TYPE_6
5386 #undef DEF_FUNCTION_TYPE_7
5387 #undef DEF_FUNCTION_TYPE_8
5388 #undef DEF_FUNCTION_TYPE_VAR_0
5389 #undef DEF_FUNCTION_TYPE_VAR_1
5390 #undef DEF_FUNCTION_TYPE_VAR_2
5391 #undef DEF_FUNCTION_TYPE_VAR_3
5392 #undef DEF_FUNCTION_TYPE_VAR_4
5393 #undef DEF_FUNCTION_TYPE_VAR_5
5394 #undef DEF_FUNCTION_TYPE_VAR_7
5395 #undef DEF_FUNCTION_TYPE_VAR_11
5396 #undef DEF_POINTER_TYPE
5397   builtin_types[(int) BT_LAST] = NULL_TREE;
5398
5399   c_init_attributes ();
5400
5401 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
5402                     NONANSI_P, ATTRS, IMPLICIT, COND)                   \
5403   if (NAME && COND)                                                     \
5404     def_builtin_1 (ENUM, NAME, CLASS,                                   \
5405                    builtin_types[(int) TYPE],                           \
5406                    builtin_types[(int) LIBTYPE],                        \
5407                    BOTH_P, FALLBACK_P, NONANSI_P,                       \
5408                    built_in_attributes[(int) ATTRS], IMPLICIT);
5409 #include "builtins.def"
5410 #undef DEF_BUILTIN
5411
5412   targetm.init_builtins ();
5413
5414   build_common_builtin_nodes ();
5415
5416   if (flag_cilkplus)
5417     cilk_init_builtins ();
5418 }
5419
5420 /* Like get_identifier, but avoid warnings about null arguments when
5421    the argument may be NULL for targets where GCC lacks stdint.h type
5422    information.  */
5423
5424 static inline tree
5425 c_get_ident (const char *id)
5426 {
5427   return get_identifier (id);
5428 }
5429
5430 /* Build tree nodes and builtin functions common to both C and C++ language
5431    frontends.  */
5432
5433 void
5434 c_common_nodes_and_builtins (void)
5435 {
5436   int char16_type_size;
5437   int char32_type_size;
5438   int wchar_type_size;
5439   tree array_domain_type;
5440   tree va_list_ref_type_node;
5441   tree va_list_arg_type_node;
5442   int i;
5443
5444   build_common_tree_nodes (flag_signed_char, flag_short_double);
5445
5446   /* Define `int' and `char' first so that dbx will output them first.  */
5447   record_builtin_type (RID_INT, NULL, integer_type_node);
5448   record_builtin_type (RID_CHAR, "char", char_type_node);
5449
5450   /* `signed' is the same as `int'.  FIXME: the declarations of "signed",
5451      "unsigned long", "long long unsigned" and "unsigned short" were in C++
5452      but not C.  Are the conditionals here needed?  */
5453   if (c_dialect_cxx ())
5454     record_builtin_type (RID_SIGNED, NULL, integer_type_node);
5455   record_builtin_type (RID_LONG, "long int", long_integer_type_node);
5456   record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
5457   record_builtin_type (RID_MAX, "long unsigned int",
5458                        long_unsigned_type_node);
5459
5460   for (i = 0; i < NUM_INT_N_ENTS; i ++)
5461     {
5462       char name[25];
5463
5464       sprintf (name, "__int%d", int_n_data[i].bitsize);
5465       record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
5466                            int_n_trees[i].signed_type);
5467       sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
5468       record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
5469     }
5470
5471   if (c_dialect_cxx ())
5472     record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
5473   record_builtin_type (RID_MAX, "long long int",
5474                        long_long_integer_type_node);
5475   record_builtin_type (RID_MAX, "long long unsigned int",
5476                        long_long_unsigned_type_node);
5477   if (c_dialect_cxx ())
5478     record_builtin_type (RID_MAX, "long long unsigned",
5479                          long_long_unsigned_type_node);
5480   record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
5481   record_builtin_type (RID_MAX, "short unsigned int",
5482                        short_unsigned_type_node);
5483   if (c_dialect_cxx ())
5484     record_builtin_type (RID_MAX, "unsigned short",
5485                          short_unsigned_type_node);
5486
5487   /* Define both `signed char' and `unsigned char'.  */
5488   record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
5489   record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
5490
5491   /* These are types that c_common_type_for_size and
5492      c_common_type_for_mode use.  */
5493   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5494                                          TYPE_DECL, NULL_TREE,
5495                                          intQI_type_node));
5496   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5497                                          TYPE_DECL, NULL_TREE,
5498                                          intHI_type_node));
5499   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5500                                          TYPE_DECL, NULL_TREE,
5501                                          intSI_type_node));
5502   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5503                                          TYPE_DECL, NULL_TREE,
5504                                          intDI_type_node));
5505 #if HOST_BITS_PER_WIDE_INT >= 64
5506   /* Note that this is different than the __int128 type that's part of
5507      the generic __intN support.  */
5508   if (targetm.scalar_mode_supported_p (TImode))
5509     lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5510                                            TYPE_DECL,
5511                                            get_identifier ("__int128_t"),
5512                                            intTI_type_node));
5513 #endif
5514   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5515                                          TYPE_DECL, NULL_TREE,
5516                                          unsigned_intQI_type_node));
5517   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5518                                          TYPE_DECL, NULL_TREE,
5519                                          unsigned_intHI_type_node));
5520   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5521                                          TYPE_DECL, NULL_TREE,
5522                                          unsigned_intSI_type_node));
5523   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5524                                          TYPE_DECL, NULL_TREE,
5525                                          unsigned_intDI_type_node));
5526 #if HOST_BITS_PER_WIDE_INT >= 64
5527   if (targetm.scalar_mode_supported_p (TImode))
5528     lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5529                                            TYPE_DECL,
5530                                            get_identifier ("__uint128_t"),
5531                                            unsigned_intTI_type_node));
5532 #endif
5533
5534   /* Create the widest literal types.  */
5535   widest_integer_literal_type_node
5536     = make_signed_type (HOST_BITS_PER_WIDE_INT * 2);
5537   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5538                                          TYPE_DECL, NULL_TREE,
5539                                          widest_integer_literal_type_node));
5540
5541   widest_unsigned_literal_type_node
5542     = make_unsigned_type (HOST_BITS_PER_WIDE_INT * 2);
5543   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5544                                          TYPE_DECL, NULL_TREE,
5545                                          widest_unsigned_literal_type_node));
5546
5547   signed_size_type_node = c_common_signed_type (size_type_node);
5548
5549   pid_type_node =
5550     TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
5551
5552   record_builtin_type (RID_FLOAT, NULL, float_type_node);
5553   record_builtin_type (RID_DOUBLE, NULL, double_type_node);
5554   record_builtin_type (RID_MAX, "long double", long_double_type_node);
5555
5556   /* Only supported decimal floating point extension if the target
5557      actually supports underlying modes. */
5558   if (targetm.scalar_mode_supported_p (SDmode)
5559       && targetm.scalar_mode_supported_p (DDmode)
5560       && targetm.scalar_mode_supported_p (TDmode))
5561     {
5562       record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
5563       record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
5564       record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
5565     }
5566
5567   if (targetm.fixed_point_supported_p ())
5568     {
5569       record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
5570       record_builtin_type (RID_FRACT, NULL, fract_type_node);
5571       record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
5572       record_builtin_type (RID_MAX, "long long _Fract",
5573                            long_long_fract_type_node);
5574       record_builtin_type (RID_MAX, "unsigned short _Fract",
5575                            unsigned_short_fract_type_node);
5576       record_builtin_type (RID_MAX, "unsigned _Fract",
5577                            unsigned_fract_type_node);
5578       record_builtin_type (RID_MAX, "unsigned long _Fract",
5579                            unsigned_long_fract_type_node);
5580       record_builtin_type (RID_MAX, "unsigned long long _Fract",
5581                            unsigned_long_long_fract_type_node);
5582       record_builtin_type (RID_MAX, "_Sat short _Fract",
5583                            sat_short_fract_type_node);
5584       record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
5585       record_builtin_type (RID_MAX, "_Sat long _Fract",
5586                            sat_long_fract_type_node);
5587       record_builtin_type (RID_MAX, "_Sat long long _Fract",
5588                            sat_long_long_fract_type_node);
5589       record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
5590                            sat_unsigned_short_fract_type_node);
5591       record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
5592                            sat_unsigned_fract_type_node);
5593       record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
5594                            sat_unsigned_long_fract_type_node);
5595       record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
5596                            sat_unsigned_long_long_fract_type_node);
5597       record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
5598       record_builtin_type (RID_ACCUM, NULL, accum_type_node);
5599       record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
5600       record_builtin_type (RID_MAX, "long long _Accum",
5601                            long_long_accum_type_node);
5602       record_builtin_type (RID_MAX, "unsigned short _Accum",
5603                            unsigned_short_accum_type_node);
5604       record_builtin_type (RID_MAX, "unsigned _Accum",
5605                            unsigned_accum_type_node);
5606       record_builtin_type (RID_MAX, "unsigned long _Accum",
5607                            unsigned_long_accum_type_node);
5608       record_builtin_type (RID_MAX, "unsigned long long _Accum",
5609                            unsigned_long_long_accum_type_node);
5610       record_builtin_type (RID_MAX, "_Sat short _Accum",
5611                            sat_short_accum_type_node);
5612       record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
5613       record_builtin_type (RID_MAX, "_Sat long _Accum",
5614                            sat_long_accum_type_node);
5615       record_builtin_type (RID_MAX, "_Sat long long _Accum",
5616                           sat_long_long_accum_type_node);
5617       record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
5618                            sat_unsigned_short_accum_type_node);
5619       record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
5620                            sat_unsigned_accum_type_node);
5621       record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
5622                            sat_unsigned_long_accum_type_node);
5623       record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
5624                            sat_unsigned_long_long_accum_type_node);
5625
5626     }
5627
5628   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5629                                          TYPE_DECL,
5630                                          get_identifier ("complex int"),
5631                                          complex_integer_type_node));
5632   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5633                                          TYPE_DECL,
5634                                          get_identifier ("complex float"),
5635                                          complex_float_type_node));
5636   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
5637                                          TYPE_DECL,
5638                                          get_identifier ("complex double"),
5639                                          complex_double_type_node));
5640   lang_hooks.decls.pushdecl
5641     (build_decl (UNKNOWN_LOCATION,
5642                  TYPE_DECL, get_identifier ("complex long double"),
5643                  complex_long_double_type_node));
5644
5645   if (c_dialect_cxx ())
5646     /* For C++, make fileptr_type_node a distinct void * type until
5647        FILE type is defined.  */
5648     fileptr_type_node = build_variant_type_copy (ptr_type_node);
5649
5650   record_builtin_type (RID_VOID, NULL, void_type_node);
5651
5652   /* Set the TYPE_NAME for any variants that were built before
5653      record_builtin_type gave names to the built-in types. */
5654   {
5655     tree void_name = TYPE_NAME (void_type_node);
5656     TYPE_NAME (void_type_node) = NULL_TREE;
5657     TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
5658       = void_name;
5659     TYPE_NAME (void_type_node) = void_name;
5660   }
5661
5662   void_list_node = build_void_list_node ();
5663
5664   /* Make a type to be the domain of a few array types
5665      whose domains don't really matter.
5666      200 is small enough that it always fits in size_t
5667      and large enough that it can hold most function names for the
5668      initializations of __FUNCTION__ and __PRETTY_FUNCTION__.  */
5669   array_domain_type = build_index_type (size_int (200));
5670
5671   /* Make a type for arrays of characters.
5672      With luck nothing will ever really depend on the length of this
5673      array type.  */
5674   char_array_type_node
5675     = build_array_type (char_type_node, array_domain_type);
5676
5677   string_type_node = build_pointer_type (char_type_node);
5678   const_string_type_node
5679     = build_pointer_type (build_qualified_type
5680                           (char_type_node, TYPE_QUAL_CONST));
5681
5682   /* This is special for C++ so functions can be overloaded.  */
5683   wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
5684   wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
5685   wchar_type_size = TYPE_PRECISION (wchar_type_node);
5686   underlying_wchar_type_node = wchar_type_node;
5687   if (c_dialect_cxx ())
5688     {
5689       if (TYPE_UNSIGNED (wchar_type_node))
5690         wchar_type_node = make_unsigned_type (wchar_type_size);
5691       else
5692         wchar_type_node = make_signed_type (wchar_type_size);
5693       record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
5694     }
5695
5696   /* This is for wide string constants.  */
5697   wchar_array_type_node
5698     = build_array_type (wchar_type_node, array_domain_type);
5699
5700   /* Define 'char16_t'.  */
5701   char16_type_node = get_identifier (CHAR16_TYPE);
5702   char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
5703   char16_type_size = TYPE_PRECISION (char16_type_node);
5704   if (c_dialect_cxx ())
5705     {
5706       char16_type_node = make_unsigned_type (char16_type_size);
5707
5708       if (cxx_dialect >= cxx11)
5709         record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
5710     }
5711
5712   /* This is for UTF-16 string constants.  */
5713   char16_array_type_node
5714     = build_array_type (char16_type_node, array_domain_type);
5715
5716   /* Define 'char32_t'.  */
5717   char32_type_node = get_identifier (CHAR32_TYPE);
5718   char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
5719   char32_type_size = TYPE_PRECISION (char32_type_node);
5720   if (c_dialect_cxx ())
5721     {
5722       char32_type_node = make_unsigned_type (char32_type_size);
5723
5724       if (cxx_dialect >= cxx11)
5725         record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
5726     }
5727
5728   /* This is for UTF-32 string constants.  */
5729   char32_array_type_node
5730     = build_array_type (char32_type_node, array_domain_type);
5731
5732   wint_type_node =
5733     TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
5734
5735   intmax_type_node =
5736     TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
5737   uintmax_type_node =
5738     TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
5739
5740   if (SIG_ATOMIC_TYPE)
5741     sig_atomic_type_node =
5742       TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
5743   if (INT8_TYPE)
5744     int8_type_node =
5745       TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
5746   if (INT16_TYPE)
5747     int16_type_node =
5748       TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
5749   if (INT32_TYPE)
5750     int32_type_node =
5751       TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
5752   if (INT64_TYPE)
5753     int64_type_node =
5754       TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
5755   if (UINT8_TYPE)
5756     uint8_type_node =
5757       TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
5758   if (UINT16_TYPE)
5759     c_uint16_type_node = uint16_type_node =
5760       TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
5761   if (UINT32_TYPE)
5762     c_uint32_type_node = uint32_type_node =
5763       TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
5764   if (UINT64_TYPE)
5765     c_uint64_type_node = uint64_type_node =
5766       TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
5767   if (INT_LEAST8_TYPE)
5768     int_least8_type_node =
5769       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
5770   if (INT_LEAST16_TYPE)
5771     int_least16_type_node =
5772       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
5773   if (INT_LEAST32_TYPE)
5774     int_least32_type_node =
5775       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
5776   if (INT_LEAST64_TYPE)
5777     int_least64_type_node =
5778       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
5779   if (UINT_LEAST8_TYPE)
5780     uint_least8_type_node =
5781       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
5782   if (UINT_LEAST16_TYPE)
5783     uint_least16_type_node =
5784       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
5785   if (UINT_LEAST32_TYPE)
5786     uint_least32_type_node =
5787       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
5788   if (UINT_LEAST64_TYPE)
5789     uint_least64_type_node =
5790       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
5791   if (INT_FAST8_TYPE)
5792     int_fast8_type_node =
5793       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
5794   if (INT_FAST16_TYPE)
5795     int_fast16_type_node =
5796       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
5797   if (INT_FAST32_TYPE)
5798     int_fast32_type_node =
5799       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
5800   if (INT_FAST64_TYPE)
5801     int_fast64_type_node =
5802       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
5803   if (UINT_FAST8_TYPE)
5804     uint_fast8_type_node =
5805       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
5806   if (UINT_FAST16_TYPE)
5807     uint_fast16_type_node =
5808       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
5809   if (UINT_FAST32_TYPE)
5810     uint_fast32_type_node =
5811       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
5812   if (UINT_FAST64_TYPE)
5813     uint_fast64_type_node =
5814       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
5815   if (INTPTR_TYPE)
5816     intptr_type_node =
5817       TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
5818   if (UINTPTR_TYPE)
5819     uintptr_type_node =
5820       TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
5821
5822   default_function_type
5823     = build_varargs_function_type_list (integer_type_node, NULL_TREE);
5824   ptrdiff_type_node
5825     = TREE_TYPE (identifier_global_value (get_identifier (PTRDIFF_TYPE)));
5826   unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
5827
5828   lang_hooks.decls.pushdecl
5829     (build_decl (UNKNOWN_LOCATION,
5830                  TYPE_DECL, get_identifier ("__builtin_va_list"),
5831                  va_list_type_node));
5832   if (targetm.enum_va_list_p)
5833     {
5834       int l;
5835       const char *pname;
5836       tree ptype;
5837
5838       for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
5839         {
5840           lang_hooks.decls.pushdecl
5841             (build_decl (UNKNOWN_LOCATION,
5842                          TYPE_DECL, get_identifier (pname),
5843                          ptype));
5844
5845         }
5846     }
5847
5848   if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
5849     {
5850       va_list_arg_type_node = va_list_ref_type_node =
5851         build_pointer_type (TREE_TYPE (va_list_type_node));
5852     }
5853   else
5854     {
5855       va_list_arg_type_node = va_list_type_node;
5856       va_list_ref_type_node = build_reference_type (va_list_type_node);
5857     }
5858
5859   if (!flag_preprocess_only)
5860     c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
5861
5862   main_identifier_node = get_identifier ("main");
5863
5864   /* Create the built-in __null node.  It is important that this is
5865      not shared.  */
5866   null_node = make_int_cst (1, 1);
5867   TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
5868
5869   /* Since builtin_types isn't gc'ed, don't export these nodes.  */
5870   memset (builtin_types, 0, sizeof (builtin_types));
5871 }
5872
5873 /* The number of named compound-literals generated thus far.  */
5874 static GTY(()) int compound_literal_number;
5875
5876 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal.  */
5877
5878 void
5879 set_compound_literal_name (tree decl)
5880 {
5881   char *name;
5882   ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
5883                            compound_literal_number);
5884   compound_literal_number++;
5885   DECL_NAME (decl) = get_identifier (name);
5886 }
5887
5888 tree
5889 build_va_arg (location_t loc, tree expr, tree type)
5890 {
5891   expr = build1 (VA_ARG_EXPR, type, expr);
5892   SET_EXPR_LOCATION (expr, loc);
5893   return expr;
5894 }
5895
5896
5897 /* Linked list of disabled built-in functions.  */
5898
5899 typedef struct disabled_builtin
5900 {
5901   const char *name;
5902   struct disabled_builtin *next;
5903 } disabled_builtin;
5904 static disabled_builtin *disabled_builtins = NULL;
5905
5906 static bool builtin_function_disabled_p (const char *);
5907
5908 /* Disable a built-in function specified by -fno-builtin-NAME.  If NAME
5909    begins with "__builtin_", give an error.  */
5910
5911 void
5912 disable_builtin_function (const char *name)
5913 {
5914   if (strncmp (name, "__builtin_", strlen ("__builtin_")) == 0)
5915     error ("cannot disable built-in function %qs", name);
5916   else
5917     {
5918       disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
5919       new_disabled_builtin->name = name;
5920       new_disabled_builtin->next = disabled_builtins;
5921       disabled_builtins = new_disabled_builtin;
5922     }
5923 }
5924
5925
5926 /* Return true if the built-in function NAME has been disabled, false
5927    otherwise.  */
5928
5929 static bool
5930 builtin_function_disabled_p (const char *name)
5931 {
5932   disabled_builtin *p;
5933   for (p = disabled_builtins; p != NULL; p = p->next)
5934     {
5935       if (strcmp (name, p->name) == 0)
5936         return true;
5937     }
5938   return false;
5939 }
5940
5941
5942 /* Worker for DEF_BUILTIN.
5943    Possibly define a builtin function with one or two names.
5944    Does not declare a non-__builtin_ function if flag_no_builtin, or if
5945    nonansi_p and flag_no_nonansi_builtin.  */
5946
5947 static void
5948 def_builtin_1 (enum built_in_function fncode,
5949                const char *name,
5950                enum built_in_class fnclass,
5951                tree fntype, tree libtype,
5952                bool both_p, bool fallback_p, bool nonansi_p,
5953                tree fnattrs, bool implicit_p)
5954 {
5955   tree decl;
5956   const char *libname;
5957
5958   if (fntype == error_mark_node)
5959     return;
5960
5961   gcc_assert ((!both_p && !fallback_p)
5962               || !strncmp (name, "__builtin_",
5963                            strlen ("__builtin_")));
5964
5965   libname = name + strlen ("__builtin_");
5966   decl = add_builtin_function (name, fntype, fncode, fnclass,
5967                                (fallback_p ? libname : NULL),
5968                                fnattrs);
5969
5970   set_builtin_decl (fncode, decl, implicit_p);
5971
5972   if (both_p
5973       && !flag_no_builtin && !builtin_function_disabled_p (libname)
5974       && !(nonansi_p && flag_no_nonansi_builtin))
5975     add_builtin_function (libname, libtype, fncode, fnclass,
5976                           NULL, fnattrs);
5977 }
5978 \f
5979 /* Nonzero if the type T promotes to int.  This is (nearly) the
5980    integral promotions defined in ISO C99 6.3.1.1/2.  */
5981
5982 bool
5983 c_promoting_integer_type_p (const_tree t)
5984 {
5985   switch (TREE_CODE (t))
5986     {
5987     case INTEGER_TYPE:
5988       return (TYPE_MAIN_VARIANT (t) == char_type_node
5989               || TYPE_MAIN_VARIANT (t) == signed_char_type_node
5990               || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
5991               || TYPE_MAIN_VARIANT (t) == short_integer_type_node
5992               || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
5993               || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
5994
5995     case ENUMERAL_TYPE:
5996       /* ??? Technically all enumerations not larger than an int
5997          promote to an int.  But this is used along code paths
5998          that only want to notice a size change.  */
5999       return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
6000
6001     case BOOLEAN_TYPE:
6002       return 1;
6003
6004     default:
6005       return 0;
6006     }
6007 }
6008
6009 /* Return 1 if PARMS specifies a fixed number of parameters
6010    and none of their types is affected by default promotions.  */
6011
6012 int
6013 self_promoting_args_p (const_tree parms)
6014 {
6015   const_tree t;
6016   for (t = parms; t; t = TREE_CHAIN (t))
6017     {
6018       tree type = TREE_VALUE (t);
6019
6020       if (type == error_mark_node)
6021         continue;
6022
6023       if (TREE_CHAIN (t) == 0 && type != void_type_node)
6024         return 0;
6025
6026       if (type == 0)
6027         return 0;
6028
6029       if (TYPE_MAIN_VARIANT (type) == float_type_node)
6030         return 0;
6031
6032       if (c_promoting_integer_type_p (type))
6033         return 0;
6034     }
6035   return 1;
6036 }
6037
6038 /* Recursively remove any '*' or '&' operator from TYPE.  */
6039 tree
6040 strip_pointer_operator (tree t)
6041 {
6042   while (POINTER_TYPE_P (t))
6043     t = TREE_TYPE (t);
6044   return t;
6045 }
6046
6047 /* Recursively remove pointer or array type from TYPE. */
6048 tree
6049 strip_pointer_or_array_types (tree t)
6050 {
6051   while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
6052     t = TREE_TYPE (t);
6053   return t;
6054 }
6055
6056 /* Used to compare case labels.  K1 and K2 are actually tree nodes
6057    representing case labels, or NULL_TREE for a `default' label.
6058    Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
6059    K2, and 0 if K1 and K2 are equal.  */
6060
6061 int
6062 case_compare (splay_tree_key k1, splay_tree_key k2)
6063 {
6064   /* Consider a NULL key (such as arises with a `default' label) to be
6065      smaller than anything else.  */
6066   if (!k1)
6067     return k2 ? -1 : 0;
6068   else if (!k2)
6069     return k1 ? 1 : 0;
6070
6071   return tree_int_cst_compare ((tree) k1, (tree) k2);
6072 }
6073
6074 /* Process a case label, located at LOC, for the range LOW_VALUE
6075    ... HIGH_VALUE.  If LOW_VALUE and HIGH_VALUE are both NULL_TREE
6076    then this case label is actually a `default' label.  If only
6077    HIGH_VALUE is NULL_TREE, then case label was declared using the
6078    usual C/C++ syntax, rather than the GNU case range extension.
6079    CASES is a tree containing all the case ranges processed so far;
6080    COND is the condition for the switch-statement itself.  Returns the
6081    CASE_LABEL_EXPR created, or ERROR_MARK_NODE if no CASE_LABEL_EXPR
6082    is created.  */
6083
6084 tree
6085 c_add_case_label (location_t loc, splay_tree cases, tree cond, tree orig_type,
6086                   tree low_value, tree high_value)
6087 {
6088   tree type;
6089   tree label;
6090   tree case_label;
6091   splay_tree_node node;
6092
6093   /* Create the LABEL_DECL itself.  */
6094   label = create_artificial_label (loc);
6095
6096   /* If there was an error processing the switch condition, bail now
6097      before we get more confused.  */
6098   if (!cond || cond == error_mark_node)
6099     goto error_out;
6100
6101   if ((low_value && TREE_TYPE (low_value)
6102        && POINTER_TYPE_P (TREE_TYPE (low_value)))
6103       || (high_value && TREE_TYPE (high_value)
6104           && POINTER_TYPE_P (TREE_TYPE (high_value))))
6105     {
6106       error_at (loc, "pointers are not permitted as case values");
6107       goto error_out;
6108     }
6109
6110   /* Case ranges are a GNU extension.  */
6111   if (high_value)
6112     pedwarn (loc, OPT_Wpedantic,
6113              "range expressions in switch statements are non-standard");
6114
6115   type = TREE_TYPE (cond);
6116   if (low_value)
6117     {
6118       low_value = check_case_value (loc, low_value);
6119       low_value = convert_and_check (loc, type, low_value);
6120       if (low_value == error_mark_node)
6121         goto error_out;
6122     }
6123   if (high_value)
6124     {
6125       high_value = check_case_value (loc, high_value);
6126       high_value = convert_and_check (loc, type, high_value);
6127       if (high_value == error_mark_node)
6128         goto error_out;
6129     }
6130
6131   if (low_value && high_value)
6132     {
6133       /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
6134          really a case range, even though it was written that way.
6135          Remove the HIGH_VALUE to simplify later processing.  */
6136       if (tree_int_cst_equal (low_value, high_value))
6137         high_value = NULL_TREE;
6138       else if (!tree_int_cst_lt (low_value, high_value))
6139         warning_at (loc, 0, "empty range specified");
6140     }
6141
6142   /* See if the case is in range of the type of the original testing
6143      expression.  If both low_value and high_value are out of range,
6144      don't insert the case label and return NULL_TREE.  */
6145   if (low_value
6146       && !check_case_bounds (loc, type, orig_type,
6147                              &low_value, high_value ? &high_value : NULL))
6148     return NULL_TREE;
6149
6150   /* Look up the LOW_VALUE in the table of case labels we already
6151      have.  */
6152   node = splay_tree_lookup (cases, (splay_tree_key) low_value);
6153   /* If there was not an exact match, check for overlapping ranges.
6154      There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
6155      that's a `default' label and the only overlap is an exact match.  */
6156   if (!node && (low_value || high_value))
6157     {
6158       splay_tree_node low_bound;
6159       splay_tree_node high_bound;
6160
6161       /* Even though there wasn't an exact match, there might be an
6162          overlap between this case range and another case range.
6163          Since we've (inductively) not allowed any overlapping case
6164          ranges, we simply need to find the greatest low case label
6165          that is smaller that LOW_VALUE, and the smallest low case
6166          label that is greater than LOW_VALUE.  If there is an overlap
6167          it will occur in one of these two ranges.  */
6168       low_bound = splay_tree_predecessor (cases,
6169                                           (splay_tree_key) low_value);
6170       high_bound = splay_tree_successor (cases,
6171                                          (splay_tree_key) low_value);
6172
6173       /* Check to see if the LOW_BOUND overlaps.  It is smaller than
6174          the LOW_VALUE, so there is no need to check unless the
6175          LOW_BOUND is in fact itself a case range.  */
6176       if (low_bound
6177           && CASE_HIGH ((tree) low_bound->value)
6178           && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
6179                                     low_value) >= 0)
6180         node = low_bound;
6181       /* Check to see if the HIGH_BOUND overlaps.  The low end of that
6182          range is bigger than the low end of the current range, so we
6183          are only interested if the current range is a real range, and
6184          not an ordinary case label.  */
6185       else if (high_bound
6186                && high_value
6187                && (tree_int_cst_compare ((tree) high_bound->key,
6188                                          high_value)
6189                    <= 0))
6190         node = high_bound;
6191     }
6192   /* If there was an overlap, issue an error.  */
6193   if (node)
6194     {
6195       tree duplicate = CASE_LABEL ((tree) node->value);
6196
6197       if (high_value)
6198         {
6199           error_at (loc, "duplicate (or overlapping) case value");
6200           error_at (DECL_SOURCE_LOCATION (duplicate),
6201                     "this is the first entry overlapping that value");
6202         }
6203       else if (low_value)
6204         {
6205           error_at (loc, "duplicate case value") ;
6206           error_at (DECL_SOURCE_LOCATION (duplicate), "previously used here");
6207         }
6208       else
6209         {
6210           error_at (loc, "multiple default labels in one switch");
6211           error_at (DECL_SOURCE_LOCATION (duplicate),
6212                     "this is the first default label");
6213         }
6214       goto error_out;
6215     }
6216
6217   /* Add a CASE_LABEL to the statement-tree.  */
6218   case_label = add_stmt (build_case_label (low_value, high_value, label));
6219   /* Register this case label in the splay tree.  */
6220   splay_tree_insert (cases,
6221                      (splay_tree_key) low_value,
6222                      (splay_tree_value) case_label);
6223
6224   return case_label;
6225
6226  error_out:
6227   /* Add a label so that the back-end doesn't think that the beginning of
6228      the switch is unreachable.  Note that we do not add a case label, as
6229      that just leads to duplicates and thence to failure later on.  */
6230   if (!cases->root)
6231     {
6232       tree t = create_artificial_label (loc);
6233       add_stmt (build_stmt (loc, LABEL_EXPR, t));
6234     }
6235   return error_mark_node;
6236 }
6237
6238 /* Subroutines of c_do_switch_warnings, called via splay_tree_foreach.
6239    Used to verify that case values match up with enumerator values.  */
6240
6241 static void
6242 match_case_to_enum_1 (tree key, tree type, tree label)
6243 {
6244   char buf[WIDE_INT_PRINT_BUFFER_SIZE];
6245
6246   if (tree_fits_uhwi_p (key))
6247     print_dec (key, buf, UNSIGNED);
6248   else if (tree_fits_shwi_p (key))
6249     print_dec (key, buf, SIGNED);
6250   else
6251     print_hex (key, buf);
6252
6253   if (TYPE_NAME (type) == 0)
6254     warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
6255                 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
6256                 "case value %qs not in enumerated type",
6257                 buf);
6258   else
6259     warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
6260                 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
6261                 "case value %qs not in enumerated type %qT",
6262                 buf, type);
6263 }
6264
6265 /* Subroutine of c_do_switch_warnings, called via splay_tree_foreach.
6266    Used to verify that case values match up with enumerator values.  */
6267
6268 static int
6269 match_case_to_enum (splay_tree_node node, void *data)
6270 {
6271   tree label = (tree) node->value;
6272   tree type = (tree) data;
6273
6274   /* Skip default case.  */
6275   if (!CASE_LOW (label))
6276     return 0;
6277
6278   /* If CASE_LOW_SEEN is not set, that means CASE_LOW did not appear
6279      when we did our enum->case scan.  Reset our scratch bit after.  */
6280   if (!CASE_LOW_SEEN (label))
6281     match_case_to_enum_1 (CASE_LOW (label), type, label);
6282   else
6283     CASE_LOW_SEEN (label) = 0;
6284
6285   /* If CASE_HIGH is non-null, we have a range.  If CASE_HIGH_SEEN is
6286      not set, that means that CASE_HIGH did not appear when we did our
6287      enum->case scan.  Reset our scratch bit after.  */
6288   if (CASE_HIGH (label))
6289     {
6290       if (!CASE_HIGH_SEEN (label))
6291         match_case_to_enum_1 (CASE_HIGH (label), type, label);
6292       else
6293         CASE_HIGH_SEEN (label) = 0;
6294     }
6295
6296   return 0;
6297 }
6298
6299 /* Handle -Wswitch*.  Called from the front end after parsing the
6300    switch construct.  */
6301 /* ??? Should probably be somewhere generic, since other languages
6302    besides C and C++ would want this.  At the moment, however, C/C++
6303    are the only tree-ssa languages that support enumerations at all,
6304    so the point is moot.  */
6305
6306 void
6307 c_do_switch_warnings (splay_tree cases, location_t switch_location,
6308                       tree type, tree cond)
6309 {
6310   splay_tree_node default_node;
6311   splay_tree_node node;
6312   tree chain;
6313
6314   if (!warn_switch && !warn_switch_enum && !warn_switch_default)
6315     return;
6316
6317   default_node = splay_tree_lookup (cases, (splay_tree_key) NULL);
6318   if (!default_node)
6319     warning_at (switch_location, OPT_Wswitch_default,
6320                 "switch missing default case");
6321
6322   /* From here on, we only care about about enumerated types.  */
6323   if (!type || TREE_CODE (type) != ENUMERAL_TYPE)
6324     return;
6325
6326   /* From here on, we only care about -Wswitch and -Wswitch-enum.  */
6327   if (!warn_switch_enum && !warn_switch)
6328     return;
6329
6330   /* Check the cases.  Warn about case values which are not members of
6331      the enumerated type.  For -Wswitch-enum, or for -Wswitch when
6332      there is no default case, check that exactly all enumeration
6333      literals are covered by the cases.  */
6334
6335   /* Clearing COND if it is not an integer constant simplifies
6336      the tests inside the loop below.  */
6337   if (TREE_CODE (cond) != INTEGER_CST)
6338     cond = NULL_TREE;
6339
6340   /* The time complexity here is O(N*lg(N)) worst case, but for the
6341       common case of monotonically increasing enumerators, it is
6342       O(N), since the nature of the splay tree will keep the next
6343       element adjacent to the root at all times.  */
6344
6345   for (chain = TYPE_VALUES (type); chain; chain = TREE_CHAIN (chain))
6346     {
6347       tree value = TREE_VALUE (chain);
6348       if (TREE_CODE (value) == CONST_DECL)
6349         value = DECL_INITIAL (value);
6350       node = splay_tree_lookup (cases, (splay_tree_key) value);
6351       if (node)
6352         {
6353           /* Mark the CASE_LOW part of the case entry as seen.  */
6354           tree label = (tree) node->value;
6355           CASE_LOW_SEEN (label) = 1;
6356           continue;
6357         }
6358
6359       /* Even though there wasn't an exact match, there might be a
6360          case range which includes the enumerator's value.  */
6361       node = splay_tree_predecessor (cases, (splay_tree_key) value);
6362       if (node && CASE_HIGH ((tree) node->value))
6363         {
6364           tree label = (tree) node->value;
6365           int cmp = tree_int_cst_compare (CASE_HIGH (label), value);
6366           if (cmp >= 0)
6367             {
6368               /* If we match the upper bound exactly, mark the CASE_HIGH
6369                  part of the case entry as seen.  */
6370               if (cmp == 0)
6371                 CASE_HIGH_SEEN (label) = 1;
6372               continue;
6373             }
6374         }
6375
6376       /* We've now determined that this enumerated literal isn't
6377          handled by the case labels of the switch statement.  */
6378
6379       /* If the switch expression is a constant, we only really care
6380          about whether that constant is handled by the switch.  */
6381       if (cond && tree_int_cst_compare (cond, value))
6382         continue;
6383
6384       /* If there is a default_node, the only relevant option is
6385          Wswitch-enum.  Otherwise, if both are enabled then we prefer
6386          to warn using -Wswitch because -Wswitch is enabled by -Wall
6387          while -Wswitch-enum is explicit.  */
6388       warning_at (switch_location,
6389                   (default_node || !warn_switch
6390                    ? OPT_Wswitch_enum
6391                    : OPT_Wswitch),
6392                   "enumeration value %qE not handled in switch",
6393                   TREE_PURPOSE (chain));
6394     }
6395
6396   /* Warn if there are case expressions that don't correspond to
6397      enumerators.  This can occur since C and C++ don't enforce
6398      type-checking of assignments to enumeration variables.
6399
6400      The time complexity here is now always O(N) worst case, since
6401      we should have marked both the lower bound and upper bound of
6402      every disjoint case label, with CASE_LOW_SEEN and CASE_HIGH_SEEN
6403      above.  This scan also resets those fields.  */
6404
6405   splay_tree_foreach (cases, match_case_to_enum, type);
6406 }
6407
6408 /* Finish an expression taking the address of LABEL (an
6409    IDENTIFIER_NODE).  Returns an expression for the address.
6410
6411    LOC is the location for the expression returned.  */
6412
6413 tree
6414 finish_label_address_expr (tree label, location_t loc)
6415 {
6416   tree result;
6417
6418   pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
6419
6420   if (label == error_mark_node)
6421     return error_mark_node;
6422
6423   label = lookup_label (label);
6424   if (label == NULL_TREE)
6425     result = null_pointer_node;
6426   else
6427     {
6428       TREE_USED (label) = 1;
6429       result = build1 (ADDR_EXPR, ptr_type_node, label);
6430       /* The current function is not necessarily uninlinable.
6431          Computed gotos are incompatible with inlining, but the value
6432          here could be used only in a diagnostic, for example.  */
6433       protected_set_expr_location (result, loc);
6434     }
6435
6436   return result;
6437 }
6438 \f
6439
6440 /* Given a boolean expression ARG, return a tree representing an increment
6441    or decrement (as indicated by CODE) of ARG.  The front end must check for
6442    invalid cases (e.g., decrement in C++).  */
6443 tree
6444 boolean_increment (enum tree_code code, tree arg)
6445 {
6446   tree val;
6447   tree true_res = build_int_cst (TREE_TYPE (arg), 1);
6448
6449   arg = stabilize_reference (arg);
6450   switch (code)
6451     {
6452     case PREINCREMENT_EXPR:
6453       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
6454       break;
6455     case POSTINCREMENT_EXPR:
6456       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
6457       arg = save_expr (arg);
6458       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
6459       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
6460       break;
6461     case PREDECREMENT_EXPR:
6462       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
6463                     invert_truthvalue_loc (input_location, arg));
6464       break;
6465     case POSTDECREMENT_EXPR:
6466       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
6467                     invert_truthvalue_loc (input_location, arg));
6468       arg = save_expr (arg);
6469       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
6470       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
6471       break;
6472     default:
6473       gcc_unreachable ();
6474     }
6475   TREE_SIDE_EFFECTS (val) = 1;
6476   return val;
6477 }
6478 \f
6479 /* Built-in macros for stddef.h and stdint.h, that require macros
6480    defined in this file.  */
6481 void
6482 c_stddef_cpp_builtins(void)
6483 {
6484   builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
6485   builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
6486   builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
6487   builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
6488   builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
6489   builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
6490   builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
6491   builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
6492   if (SIG_ATOMIC_TYPE)
6493     builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
6494   if (INT8_TYPE)
6495     builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
6496   if (INT16_TYPE)
6497     builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
6498   if (INT32_TYPE)
6499     builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
6500   if (INT64_TYPE)
6501     builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
6502   if (UINT8_TYPE)
6503     builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
6504   if (UINT16_TYPE)
6505     builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
6506   if (UINT32_TYPE)
6507     builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
6508   if (UINT64_TYPE)
6509     builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
6510   if (INT_LEAST8_TYPE)
6511     builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
6512   if (INT_LEAST16_TYPE)
6513     builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
6514   if (INT_LEAST32_TYPE)
6515     builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
6516   if (INT_LEAST64_TYPE)
6517     builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
6518   if (UINT_LEAST8_TYPE)
6519     builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
6520   if (UINT_LEAST16_TYPE)
6521     builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
6522   if (UINT_LEAST32_TYPE)
6523     builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
6524   if (UINT_LEAST64_TYPE)
6525     builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
6526   if (INT_FAST8_TYPE)
6527     builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
6528   if (INT_FAST16_TYPE)
6529     builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
6530   if (INT_FAST32_TYPE)
6531     builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
6532   if (INT_FAST64_TYPE)
6533     builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
6534   if (UINT_FAST8_TYPE)
6535     builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
6536   if (UINT_FAST16_TYPE)
6537     builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
6538   if (UINT_FAST32_TYPE)
6539     builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
6540   if (UINT_FAST64_TYPE)
6541     builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
6542   if (INTPTR_TYPE)
6543     builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
6544   if (UINTPTR_TYPE)
6545     builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
6546 }
6547
6548 static void
6549 c_init_attributes (void)
6550 {
6551   /* Fill in the built_in_attributes array.  */
6552 #define DEF_ATTR_NULL_TREE(ENUM)                                \
6553   built_in_attributes[(int) ENUM] = NULL_TREE;
6554 #define DEF_ATTR_INT(ENUM, VALUE)                               \
6555   built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
6556 #define DEF_ATTR_STRING(ENUM, VALUE)                            \
6557   built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
6558 #define DEF_ATTR_IDENT(ENUM, STRING)                            \
6559   built_in_attributes[(int) ENUM] = get_identifier (STRING);
6560 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
6561   built_in_attributes[(int) ENUM]                       \
6562     = tree_cons (built_in_attributes[(int) PURPOSE],    \
6563                  built_in_attributes[(int) VALUE],      \
6564                  built_in_attributes[(int) CHAIN]);
6565 #include "builtin-attrs.def"
6566 #undef DEF_ATTR_NULL_TREE
6567 #undef DEF_ATTR_INT
6568 #undef DEF_ATTR_IDENT
6569 #undef DEF_ATTR_TREE_LIST
6570 }
6571
6572 /* Returns TRUE iff the attribute indicated by ATTR_ID takes a plain
6573    identifier as an argument, so the front end shouldn't look it up.  */
6574
6575 bool
6576 attribute_takes_identifier_p (const_tree attr_id)
6577 {
6578   const struct attribute_spec *spec = lookup_attribute_spec (attr_id);
6579   if (spec == NULL)
6580     /* Unknown attribute that we'll end up ignoring, return true so we
6581        don't complain about an identifier argument.  */
6582     return true;
6583   else if (!strcmp ("mode", spec->name)
6584            || !strcmp ("format", spec->name)
6585            || !strcmp ("cleanup", spec->name))
6586     return true;
6587   else
6588     return targetm.attribute_takes_identifier_p (attr_id);
6589 }
6590
6591 /* Attribute handlers common to C front ends.  */
6592
6593 /* Handle a "packed" attribute; arguments as in
6594    struct attribute_spec.handler.  */
6595
6596 static tree
6597 handle_packed_attribute (tree *node, tree name, tree ARG_UNUSED (args),
6598                          int flags, bool *no_add_attrs)
6599 {
6600   if (TYPE_P (*node))
6601     {
6602       if (!(flags & (int) ATTR_FLAG_TYPE_IN_PLACE))
6603         *node = build_variant_type_copy (*node);
6604       TYPE_PACKED (*node) = 1;
6605     }
6606   else if (TREE_CODE (*node) == FIELD_DECL)
6607     {
6608       if (TYPE_ALIGN (TREE_TYPE (*node)) <= BITS_PER_UNIT
6609           /* Still pack bitfields.  */
6610           && ! DECL_INITIAL (*node))
6611         warning (OPT_Wattributes,
6612                  "%qE attribute ignored for field of type %qT",
6613                  name, TREE_TYPE (*node));
6614       else
6615         DECL_PACKED (*node) = 1;
6616     }
6617   /* We can't set DECL_PACKED for a VAR_DECL, because the bit is
6618      used for DECL_REGISTER.  It wouldn't mean anything anyway.
6619      We can't set DECL_PACKED on the type of a TYPE_DECL, because
6620      that changes what the typedef is typing.  */
6621   else
6622     {
6623       warning (OPT_Wattributes, "%qE attribute ignored", name);
6624       *no_add_attrs = true;
6625     }
6626
6627   return NULL_TREE;
6628 }
6629
6630 /* Handle a "nocommon" attribute; arguments as in
6631    struct attribute_spec.handler.  */
6632
6633 static tree
6634 handle_nocommon_attribute (tree *node, tree name,
6635                            tree ARG_UNUSED (args),
6636                            int ARG_UNUSED (flags), bool *no_add_attrs)
6637 {
6638   if (TREE_CODE (*node) == VAR_DECL)
6639     DECL_COMMON (*node) = 0;
6640   else
6641     {
6642       warning (OPT_Wattributes, "%qE attribute ignored", name);
6643       *no_add_attrs = true;
6644     }
6645
6646   return NULL_TREE;
6647 }
6648
6649 /* Handle a "common" attribute; arguments as in
6650    struct attribute_spec.handler.  */
6651
6652 static tree
6653 handle_common_attribute (tree *node, tree name, tree ARG_UNUSED (args),
6654                          int ARG_UNUSED (flags), bool *no_add_attrs)
6655 {
6656   if (TREE_CODE (*node) == VAR_DECL)
6657     DECL_COMMON (*node) = 1;
6658   else
6659     {
6660       warning (OPT_Wattributes, "%qE attribute ignored", name);
6661       *no_add_attrs = true;
6662     }
6663
6664   return NULL_TREE;
6665 }
6666
6667 /* Handle a "noreturn" attribute; arguments as in
6668    struct attribute_spec.handler.  */
6669
6670 static tree
6671 handle_noreturn_attribute (tree *node, tree name, tree ARG_UNUSED (args),
6672                            int ARG_UNUSED (flags), bool *no_add_attrs)
6673 {
6674   tree type = TREE_TYPE (*node);
6675
6676   /* See FIXME comment in c_common_attribute_table.  */
6677   if (TREE_CODE (*node) == FUNCTION_DECL
6678       || objc_method_decl (TREE_CODE (*node)))
6679     TREE_THIS_VOLATILE (*node) = 1;
6680   else if (TREE_CODE (type) == POINTER_TYPE
6681            && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
6682     TREE_TYPE (*node)
6683       = (build_qualified_type
6684          (build_pointer_type
6685           (build_type_variant (TREE_TYPE (type),
6686                                TYPE_READONLY (TREE_TYPE (type)), 1)),
6687           TYPE_QUALS (type)));
6688   else
6689     {
6690       warning (OPT_Wattributes, "%qE attribute ignored", name);
6691       *no_add_attrs = true;
6692     }
6693
6694   return NULL_TREE;
6695 }
6696
6697 /* Handle a "hot" and attribute; arguments as in
6698    struct attribute_spec.handler.  */
6699
6700 static tree
6701 handle_hot_attribute (tree *node, tree name, tree ARG_UNUSED (args),
6702                       int ARG_UNUSED (flags), bool *no_add_attrs)
6703 {
6704   if (TREE_CODE (*node) == FUNCTION_DECL
6705       || TREE_CODE (*node) == LABEL_DECL)
6706     {
6707       if (lookup_attribute ("cold", DECL_ATTRIBUTES (*node)) != NULL)
6708         {
6709           warning (OPT_Wattributes, "%qE attribute ignored due to conflict "
6710                    "with attribute %qs", name, "cold");
6711           *no_add_attrs = true;
6712         }
6713       /* Most of the rest of the hot processing is done later with
6714          lookup_attribute.  */
6715     }
6716   else
6717     {
6718       warning (OPT_Wattributes, "%qE attribute ignored", name);
6719       *no_add_attrs = true;
6720     }
6721
6722   return NULL_TREE;
6723 }
6724
6725 /* Handle a "cold" and attribute; arguments as in
6726    struct attribute_spec.handler.  */
6727
6728 static tree
6729 handle_cold_attribute (tree *node, tree name, tree ARG_UNUSED (args),
6730                        int ARG_UNUSED (flags), bool *no_add_attrs)
6731 {
6732   if (TREE_CODE (*node) == FUNCTION_DECL
6733       || TREE_CODE (*node) == LABEL_DECL)
6734     {
6735       if (lookup_attribute ("hot", DECL_ATTRIBUTES (*node)) != NULL)
6736         {
6737           warning (OPT_Wattributes, "%qE attribute ignored due to conflict "
6738                    "with attribute %qs", name, "hot");
6739           *no_add_attrs = true;
6740         }
6741       /* Most of the rest of the cold processing is done later with
6742          lookup_attribute.  */
6743     }
6744   else
6745     {
6746       warning (OPT_Wattributes, "%qE attribute ignored", name);
6747       *no_add_attrs = true;
6748     }
6749
6750   return NULL_TREE;
6751 }
6752
6753 /* Handle a "no_sanitize_address" attribute; arguments as in
6754    struct attribute_spec.handler.  */
6755
6756 static tree
6757 handle_no_sanitize_address_attribute (tree *node, tree name, tree, int,
6758                                       bool *no_add_attrs)
6759 {
6760   if (TREE_CODE (*node) != FUNCTION_DECL)
6761     {
6762       warning (OPT_Wattributes, "%qE attribute ignored", name);
6763       *no_add_attrs = true;
6764     }
6765
6766   return NULL_TREE;
6767 }
6768
6769 /* Handle a "no_address_safety_analysis" attribute; arguments as in
6770    struct attribute_spec.handler.  */
6771
6772 static tree
6773 handle_no_address_safety_analysis_attribute (tree *node, tree name, tree, int,
6774                                              bool *no_add_attrs)
6775 {
6776   if (TREE_CODE (*node) != FUNCTION_DECL)
6777     warning (OPT_Wattributes, "%qE attribute ignored", name);
6778   else if (!lookup_attribute ("no_sanitize_address", DECL_ATTRIBUTES (*node)))
6779     DECL_ATTRIBUTES (*node)
6780       = tree_cons (get_identifier ("no_sanitize_address"),
6781                    NULL_TREE, DECL_ATTRIBUTES (*node));
6782   *no_add_attrs = true;
6783   return NULL_TREE;
6784 }
6785
6786 /* Handle a "no_sanitize_undefined" attribute; arguments as in
6787    struct attribute_spec.handler.  */
6788
6789 static tree
6790 handle_no_sanitize_undefined_attribute (tree *node, tree name, tree, int,
6791                                       bool *no_add_attrs)
6792 {
6793   if (TREE_CODE (*node) != FUNCTION_DECL)
6794     {
6795       warning (OPT_Wattributes, "%qE attribute ignored", name);
6796       *no_add_attrs = true;
6797     }
6798
6799   return NULL_TREE;
6800 }
6801
6802 /* Handle a "stack_protect" attribute; arguments as in
6803    struct attribute_spec.handler.  */
6804 static tree
6805 handle_stack_protect_attribute (tree *node, tree name, tree, int,
6806                                 bool *no_add_attrs)
6807 {
6808   if (TREE_CODE (*node) != FUNCTION_DECL)
6809     {
6810       warning (OPT_Wattributes, "%qE attribute ignored", name);
6811       *no_add_attrs = true;
6812     }
6813   else
6814     DECL_ATTRIBUTES (*node) 
6815       = tree_cons (get_identifier ("stack_protect"),
6816                    NULL_TREE, DECL_ATTRIBUTES (*node));
6817
6818   return NULL_TREE;
6819 }
6820
6821 /* Handle a "noinline" attribute; arguments as in
6822    struct attribute_spec.handler.  */
6823
6824 static tree
6825 handle_noinline_attribute (tree *node, tree name,
6826                            tree ARG_UNUSED (args),
6827                            int ARG_UNUSED (flags), bool *no_add_attrs)
6828 {
6829   if (TREE_CODE (*node) == FUNCTION_DECL)
6830     {
6831       if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (*node)))
6832         {
6833           warning (OPT_Wattributes, "%qE attribute ignored due to conflict "
6834                    "with attribute %qs", name, "always_inline");
6835           *no_add_attrs = true;
6836         }
6837       else
6838         DECL_UNINLINABLE (*node) = 1;
6839     }
6840   else
6841     {
6842       warning (OPT_Wattributes, "%qE attribute ignored", name);
6843       *no_add_attrs = true;
6844     }
6845
6846   return NULL_TREE;
6847 }
6848
6849 /* Handle a "noclone" attribute; arguments as in
6850    struct attribute_spec.handler.  */
6851
6852 static tree
6853 handle_noclone_attribute (tree *node, tree name,
6854                           tree ARG_UNUSED (args),
6855                           int ARG_UNUSED (flags), bool *no_add_attrs)
6856 {
6857   if (TREE_CODE (*node) != FUNCTION_DECL)
6858     {
6859       warning (OPT_Wattributes, "%qE attribute ignored", name);
6860       *no_add_attrs = true;
6861     }
6862
6863   return NULL_TREE;
6864 }
6865
6866 /* Handle a "no_icf" attribute; arguments as in
6867    struct attribute_spec.handler.  */
6868
6869 static tree
6870 handle_noicf_attribute (tree *node, tree name,
6871                         tree ARG_UNUSED (args),
6872                         int ARG_UNUSED (flags), bool *no_add_attrs)
6873 {
6874   if (TREE_CODE (*node) != FUNCTION_DECL)
6875     {
6876       warning (OPT_Wattributes, "%qE attribute ignored", name);
6877       *no_add_attrs = true;
6878     }
6879
6880   return NULL_TREE;
6881 }
6882
6883
6884 /* Handle a "always_inline" attribute; arguments as in
6885    struct attribute_spec.handler.  */
6886
6887 static tree
6888 handle_always_inline_attribute (tree *node, tree name,
6889                                 tree ARG_UNUSED (args),
6890                                 int ARG_UNUSED (flags),
6891                                 bool *no_add_attrs)
6892 {
6893   if (TREE_CODE (*node) == FUNCTION_DECL)
6894     {
6895       if (lookup_attribute ("noinline", DECL_ATTRIBUTES (*node)))
6896         {
6897           warning (OPT_Wattributes, "%qE attribute ignored due to conflict "
6898                    "with %qs attribute", name, "noinline");
6899           *no_add_attrs = true;
6900         }
6901       else
6902         /* Set the attribute and mark it for disregarding inline
6903            limits.  */
6904         DECL_DISREGARD_INLINE_LIMITS (*node) = 1;
6905     }
6906   else
6907     {
6908       warning (OPT_Wattributes, "%qE attribute ignored", name);
6909       *no_add_attrs = true;
6910     }
6911
6912   return NULL_TREE;
6913 }
6914
6915 /* Handle a "gnu_inline" attribute; arguments as in
6916    struct attribute_spec.handler.  */
6917
6918 static tree
6919 handle_gnu_inline_attribute (tree *node, tree name,
6920                              tree ARG_UNUSED (args),
6921                              int ARG_UNUSED (flags),
6922                              bool *no_add_attrs)
6923 {
6924   if (TREE_CODE (*node) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (*node))
6925     {
6926       /* Do nothing else, just set the attribute.  We'll get at
6927          it later with lookup_attribute.  */
6928     }
6929   else
6930     {
6931       warning (OPT_Wattributes, "%qE attribute ignored", name);
6932       *no_add_attrs = true;
6933     }
6934
6935   return NULL_TREE;
6936 }
6937
6938 /* Handle a "leaf" attribute; arguments as in
6939    struct attribute_spec.handler.  */
6940
6941 static tree
6942 handle_leaf_attribute (tree *node, tree name,
6943                        tree ARG_UNUSED (args),
6944                        int ARG_UNUSED (flags), bool *no_add_attrs)
6945 {
6946   if (TREE_CODE (*node) != FUNCTION_DECL)
6947     {
6948       warning (OPT_Wattributes, "%qE attribute ignored", name);
6949       *no_add_attrs = true;
6950     }
6951   if (!TREE_PUBLIC (*node))
6952     {
6953       warning (OPT_Wattributes, "%qE attribute has no effect on unit local functions", name);
6954       *no_add_attrs = true;
6955     }
6956
6957   return NULL_TREE;
6958 }
6959
6960 /* Handle an "artificial" attribute; arguments as in
6961    struct attribute_spec.handler.  */
6962
6963 static tree
6964 handle_artificial_attribute (tree *node, tree name,
6965                              tree ARG_UNUSED (args),
6966                              int ARG_UNUSED (flags),
6967                              bool *no_add_attrs)
6968 {
6969   if (TREE_CODE (*node) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (*node))
6970     {
6971       /* Do nothing else, just set the attribute.  We'll get at
6972          it later with lookup_attribute.  */
6973     }
6974   else
6975     {
6976       warning (OPT_Wattributes, "%qE attribute ignored", name);
6977       *no_add_attrs = true;
6978     }
6979
6980   return NULL_TREE;
6981 }
6982
6983 /* Handle a "flatten" attribute; arguments as in
6984    struct attribute_spec.handler.  */
6985
6986 static tree
6987 handle_flatten_attribute (tree *node, tree name,
6988                           tree args ATTRIBUTE_UNUSED,
6989                           int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
6990 {
6991   if (TREE_CODE (*node) == FUNCTION_DECL)
6992     /* Do nothing else, just set the attribute.  We'll get at
6993        it later with lookup_attribute.  */
6994     ;
6995   else
6996     {
6997       warning (OPT_Wattributes, "%qE attribute ignored", name);
6998       *no_add_attrs = true;
6999     }
7000
7001   return NULL_TREE;
7002 }
7003
7004 /* Handle a "warning" or "error" attribute; arguments as in
7005    struct attribute_spec.handler.  */
7006
7007 static tree
7008 handle_error_attribute (tree *node, tree name, tree args,
7009                         int ARG_UNUSED (flags), bool *no_add_attrs)
7010 {
7011   if (TREE_CODE (*node) == FUNCTION_DECL
7012       && TREE_CODE (TREE_VALUE (args)) == STRING_CST)
7013     /* Do nothing else, just set the attribute.  We'll get at
7014        it later with lookup_attribute.  */
7015     ;
7016   else
7017     {
7018       warning (OPT_Wattributes, "%qE attribute ignored", name);
7019       *no_add_attrs = true;
7020     }
7021
7022   return NULL_TREE;
7023 }
7024
7025 /* Handle a "used" attribute; arguments as in
7026    struct attribute_spec.handler.  */
7027
7028 static tree
7029 handle_used_attribute (tree *pnode, tree name, tree ARG_UNUSED (args),
7030                        int ARG_UNUSED (flags), bool *no_add_attrs)
7031 {
7032   tree node = *pnode;
7033
7034   if (TREE_CODE (node) == FUNCTION_DECL
7035       || (TREE_CODE (node) == VAR_DECL && TREE_STATIC (node))
7036       || (TREE_CODE (node) == TYPE_DECL))
7037     {
7038       TREE_USED (node) = 1;
7039       DECL_PRESERVE_P (node) = 1;
7040       if (TREE_CODE (node) == VAR_DECL)
7041         DECL_READ_P (node) = 1;
7042     }
7043   else
7044     {
7045       warning (OPT_Wattributes, "%qE attribute ignored", name);
7046       *no_add_attrs = true;
7047     }
7048
7049   return NULL_TREE;
7050 }
7051
7052 /* Handle a "unused" attribute; arguments as in
7053    struct attribute_spec.handler.  */
7054
7055 static tree
7056 handle_unused_attribute (tree *node, tree name, tree ARG_UNUSED (args),
7057                          int flags, bool *no_add_attrs)
7058 {
7059   if (DECL_P (*node))
7060     {
7061       tree decl = *node;
7062
7063       if (TREE_CODE (decl) == PARM_DECL
7064           || TREE_CODE (decl) == VAR_DECL
7065           || TREE_CODE (decl) == FUNCTION_DECL
7066           || TREE_CODE (decl) == LABEL_DECL
7067           || TREE_CODE (decl) == TYPE_DECL)
7068         {
7069           TREE_USED (decl) = 1;
7070           if (TREE_CODE (decl) == VAR_DECL
7071               || TREE_CODE (decl) == PARM_DECL)
7072             DECL_READ_P (decl) = 1;
7073         }
7074       else
7075         {
7076           warning (OPT_Wattributes, "%qE attribute ignored", name);
7077           *no_add_attrs = true;
7078         }
7079     }
7080   else
7081     {
7082       if (!(flags & (int) ATTR_FLAG_TYPE_IN_PLACE))
7083         *node = build_variant_type_copy (*node);
7084       TREE_USED (*node) = 1;
7085     }
7086
7087   return NULL_TREE;
7088 }
7089
7090 /* Handle a "externally_visible" attribute; arguments as in
7091    struct attribute_spec.handler.  */
7092
7093 static tree
7094 handle_externally_visible_attribute (tree *pnode, tree name,
7095                                      tree ARG_UNUSED (args),
7096                                      int ARG_UNUSED (flags),
7097                                      bool *no_add_attrs)
7098 {
7099   tree node = *pnode;
7100
7101   if (TREE_CODE (node) == FUNCTION_DECL || TREE_CODE (node) == VAR_DECL)
7102     {
7103       if ((!TREE_STATIC (node) && TREE_CODE (node) != FUNCTION_DECL
7104            && !DECL_EXTERNAL (node)) || !TREE_PUBLIC (node))
7105         {
7106           warning (OPT_Wattributes,
7107                    "%qE attribute have effect only on public objects", name);
7108           *no_add_attrs = true;
7109         }
7110     }
7111   else
7112     {
7113       warning (OPT_Wattributes, "%qE attribute ignored", name);
7114       *no_add_attrs = true;
7115     }
7116
7117   return NULL_TREE;
7118 }
7119
7120 /* Handle the "no_reorder" attribute. Arguments as in
7121    struct attribute_spec.handler. */
7122
7123 static tree
7124 handle_no_reorder_attribute (tree *pnode,
7125                              tree name,
7126                              tree,
7127                              int,
7128                              bool *no_add_attrs)
7129 {
7130   tree node = *pnode;
7131
7132   if ((TREE_CODE (node) != FUNCTION_DECL && TREE_CODE (node) != VAR_DECL)
7133         && !(TREE_STATIC (node) || DECL_EXTERNAL (node)))
7134     {
7135       warning (OPT_Wattributes,
7136                 "%qE attribute only affects top level objects",
7137                 name);
7138       *no_add_attrs = true;
7139     }
7140
7141   return NULL_TREE;
7142 }
7143
7144 /* Handle a "const" attribute; arguments as in
7145    struct attribute_spec.handler.  */
7146
7147 static tree
7148 handle_const_attribute (tree *node, tree name, tree ARG_UNUSED (args),
7149                         int ARG_UNUSED (flags), bool *no_add_attrs)
7150 {
7151   tree type = TREE_TYPE (*node);
7152
7153   /* See FIXME comment on noreturn in c_common_attribute_table.  */
7154   if (TREE_CODE (*node) == FUNCTION_DECL)
7155     TREE_READONLY (*node) = 1;
7156   else if (TREE_CODE (type) == POINTER_TYPE
7157            && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
7158     TREE_TYPE (*node)
7159       = (build_qualified_type
7160          (build_pointer_type
7161           (build_type_variant (TREE_TYPE (type), 1,
7162                                TREE_THIS_VOLATILE (TREE_TYPE (type)))),
7163           TYPE_QUALS (type)));
7164   else
7165     {
7166       warning (OPT_Wattributes, "%qE attribute ignored", name);
7167       *no_add_attrs = true;
7168     }
7169
7170   return NULL_TREE;
7171 }
7172
7173 /* Handle a "transparent_union" attribute; arguments as in
7174    struct attribute_spec.handler.  */
7175
7176 static tree
7177 handle_transparent_union_attribute (tree *node, tree name,
7178                                     tree ARG_UNUSED (args), int flags,
7179                                     bool *no_add_attrs)
7180 {
7181   tree type;
7182
7183   *no_add_attrs = true;
7184
7185
7186   if (TREE_CODE (*node) == TYPE_DECL
7187       && ! (flags & ATTR_FLAG_CXX11))
7188     node = &TREE_TYPE (*node);
7189   type = *node;
7190
7191   if (TREE_CODE (type) == UNION_TYPE)
7192     {
7193       /* Make sure that the first field will work for a transparent union.
7194          If the type isn't complete yet, leave the check to the code in
7195          finish_struct.  */
7196       if (TYPE_SIZE (type))
7197         {
7198           tree first = first_field (type);
7199           if (first == NULL_TREE
7200               || DECL_ARTIFICIAL (first)
7201               || TYPE_MODE (type) != DECL_MODE (first))
7202             goto ignored;
7203         }
7204
7205       if (!(flags & (int) ATTR_FLAG_TYPE_IN_PLACE))
7206         {
7207           /* If the type isn't complete yet, setting the flag
7208              on a variant wouldn't ever be checked.  */
7209           if (!TYPE_SIZE (type))
7210             goto ignored;
7211
7212           /* build_duplicate_type doesn't work for C++.  */
7213           if (c_dialect_cxx ())
7214             goto ignored;
7215
7216           /* A type variant isn't good enough, since we don't a cast
7217              to such a type removed as a no-op.  */
7218           *node = type = build_duplicate_type (type);
7219         }
7220
7221       TYPE_TRANSPARENT_AGGR (type) = 1;
7222       return NULL_TREE;
7223     }
7224
7225  ignored:
7226   warning (OPT_Wattributes, "%qE attribute ignored", name);
7227   return NULL_TREE;
7228 }
7229
7230 /* Subroutine of handle_{con,de}structor_attribute.  Evaluate ARGS to
7231    get the requested priority for a constructor or destructor,
7232    possibly issuing diagnostics for invalid or reserved
7233    priorities.  */
7234
7235 static priority_type
7236 get_priority (tree args, bool is_destructor)
7237 {
7238   HOST_WIDE_INT pri;
7239   tree arg;
7240
7241   if (!args)
7242     return DEFAULT_INIT_PRIORITY;
7243
7244   if (!SUPPORTS_INIT_PRIORITY)
7245     {
7246       if (is_destructor)
7247         error ("destructor priorities are not supported");
7248       else
7249         error ("constructor priorities are not supported");
7250       return DEFAULT_INIT_PRIORITY;
7251     }
7252
7253   arg = TREE_VALUE (args);
7254   if (TREE_CODE (arg) == IDENTIFIER_NODE)
7255     goto invalid;
7256   if (arg == error_mark_node)
7257     return DEFAULT_INIT_PRIORITY;
7258   arg = default_conversion (arg);
7259   if (!tree_fits_shwi_p (arg)
7260       || !INTEGRAL_TYPE_P (TREE_TYPE (arg)))
7261     goto invalid;
7262
7263   pri = tree_to_shwi (arg);
7264   if (pri < 0 || pri > MAX_INIT_PRIORITY)
7265     goto invalid;
7266
7267   if (pri <= MAX_RESERVED_INIT_PRIORITY)
7268     {
7269       if (is_destructor)
7270         warning (0,
7271                  "destructor priorities from 0 to %d are reserved "
7272                  "for the implementation",
7273                  MAX_RESERVED_INIT_PRIORITY);
7274       else
7275         warning (0,
7276                  "constructor priorities from 0 to %d are reserved "
7277                  "for the implementation",
7278                  MAX_RESERVED_INIT_PRIORITY);
7279     }
7280   return pri;
7281
7282  invalid:
7283   if (is_destructor)
7284     error ("destructor priorities must be integers from 0 to %d inclusive",
7285            MAX_INIT_PRIORITY);
7286   else
7287     error ("constructor priorities must be integers from 0 to %d inclusive",
7288            MAX_INIT_PRIORITY);
7289   return DEFAULT_INIT_PRIORITY;
7290 }
7291
7292 /* Handle a "constructor" attribute; arguments as in
7293    struct attribute_spec.handler.  */
7294
7295 static tree
7296 handle_constructor_attribute (tree *node, tree name, tree args,
7297                               int ARG_UNUSED (flags),
7298                               bool *no_add_attrs)
7299 {
7300   tree decl = *node;
7301   tree type = TREE_TYPE (decl);
7302
7303   if (TREE_CODE (decl) == FUNCTION_DECL
7304       && TREE_CODE (type) == FUNCTION_TYPE
7305       && decl_function_context (decl) == 0)
7306     {
7307       priority_type priority;
7308       DECL_STATIC_CONSTRUCTOR (decl) = 1;
7309       priority = get_priority (args, /*is_destructor=*/false);
7310       SET_DECL_INIT_PRIORITY (decl, priority);
7311       TREE_USED (decl) = 1;
7312     }
7313   else
7314     {
7315       warning (OPT_Wattributes, "%qE attribute ignored", name);
7316       *no_add_attrs = true;
7317     }
7318
7319   return NULL_TREE;
7320 }
7321
7322 /* Handle a "destructor" attribute; arguments as in
7323    struct attribute_spec.handler.  */
7324
7325 static tree
7326 handle_destructor_attribute (tree *node, tree name, tree args,
7327                              int ARG_UNUSED (flags),
7328                              bool *no_add_attrs)
7329 {
7330   tree decl = *node;
7331   tree type = TREE_TYPE (decl);
7332
7333   if (TREE_CODE (decl) == FUNCTION_DECL
7334       && TREE_CODE (type) == FUNCTION_TYPE
7335       && decl_function_context (decl) == 0)
7336     {
7337       priority_type priority;
7338       DECL_STATIC_DESTRUCTOR (decl) = 1;
7339       priority = get_priority (args, /*is_destructor=*/true);
7340       SET_DECL_FINI_PRIORITY (decl, priority);
7341       TREE_USED (decl) = 1;
7342     }
7343   else
7344     {
7345       warning (OPT_Wattributes, "%qE attribute ignored", name);
7346       *no_add_attrs = true;
7347     }
7348
7349   return NULL_TREE;
7350 }
7351
7352 /* Nonzero if the mode is a valid vector mode for this architecture.
7353    This returns nonzero even if there is no hardware support for the
7354    vector mode, but we can emulate with narrower modes.  */
7355
7356 static int
7357 vector_mode_valid_p (machine_mode mode)
7358 {
7359   enum mode_class mclass = GET_MODE_CLASS (mode);
7360   machine_mode innermode;
7361
7362   /* Doh!  What's going on?  */
7363   if (mclass != MODE_VECTOR_INT
7364       && mclass != MODE_VECTOR_FLOAT
7365       && mclass != MODE_VECTOR_FRACT
7366       && mclass != MODE_VECTOR_UFRACT
7367       && mclass != MODE_VECTOR_ACCUM
7368       && mclass != MODE_VECTOR_UACCUM)
7369     return 0;
7370
7371   /* Hardware support.  Woo hoo!  */
7372   if (targetm.vector_mode_supported_p (mode))
7373     return 1;
7374
7375   innermode = GET_MODE_INNER (mode);
7376
7377   /* We should probably return 1 if requesting V4DI and we have no DI,
7378      but we have V2DI, but this is probably very unlikely.  */
7379
7380   /* If we have support for the inner mode, we can safely emulate it.
7381      We may not have V2DI, but me can emulate with a pair of DIs.  */
7382   return targetm.scalar_mode_supported_p (innermode);
7383 }
7384
7385
7386 /* Handle a "mode" attribute; arguments as in
7387    struct attribute_spec.handler.  */
7388
7389 static tree
7390 handle_mode_attribute (tree *node, tree name, tree args,
7391                        int ARG_UNUSED (flags), bool *no_add_attrs)
7392 {
7393   tree type = *node;
7394   tree ident = TREE_VALUE (args);
7395
7396   *no_add_attrs = true;
7397
7398   if (TREE_CODE (ident) != IDENTIFIER_NODE)
7399     warning (OPT_Wattributes, "%qE attribute ignored", name);
7400   else
7401     {
7402       int j;
7403       const char *p = IDENTIFIER_POINTER (ident);
7404       int len = strlen (p);
7405       machine_mode mode = VOIDmode;
7406       tree typefm;
7407       bool valid_mode;
7408
7409       if (len > 4 && p[0] == '_' && p[1] == '_'
7410           && p[len - 1] == '_' && p[len - 2] == '_')
7411         {
7412           char *newp = (char *) alloca (len - 1);
7413
7414           strcpy (newp, &p[2]);
7415           newp[len - 4] = '\0';
7416           p = newp;
7417         }
7418
7419       /* Change this type to have a type with the specified mode.
7420          First check for the special modes.  */
7421       if (!strcmp (p, "byte"))
7422         mode = byte_mode;
7423       else if (!strcmp (p, "word"))
7424         mode = word_mode;
7425       else if (!strcmp (p, "pointer"))
7426         mode = ptr_mode;
7427       else if (!strcmp (p, "libgcc_cmp_return"))
7428         mode = targetm.libgcc_cmp_return_mode ();
7429       else if (!strcmp (p, "libgcc_shift_count"))
7430         mode = targetm.libgcc_shift_count_mode ();
7431       else if (!strcmp (p, "unwind_word"))
7432         mode = targetm.unwind_word_mode ();
7433       else
7434         for (j = 0; j < NUM_MACHINE_MODES; j++)
7435           if (!strcmp (p, GET_MODE_NAME (j)))
7436             {
7437               mode = (machine_mode) j;
7438               break;
7439             }
7440
7441       if (mode == VOIDmode)
7442         {
7443           error ("unknown machine mode %qE", ident);
7444           return NULL_TREE;
7445         }
7446
7447       valid_mode = false;
7448       switch (GET_MODE_CLASS (mode))
7449         {
7450         case MODE_INT:
7451         case MODE_PARTIAL_INT:
7452         case MODE_FLOAT:
7453         case MODE_DECIMAL_FLOAT:
7454         case MODE_FRACT:
7455         case MODE_UFRACT:
7456         case MODE_ACCUM:
7457         case MODE_UACCUM:
7458           valid_mode = targetm.scalar_mode_supported_p (mode);
7459           break;
7460
7461         case MODE_COMPLEX_INT:
7462         case MODE_COMPLEX_FLOAT:
7463           valid_mode = targetm.scalar_mode_supported_p (GET_MODE_INNER (mode));
7464           break;
7465
7466         case MODE_VECTOR_INT:
7467         case MODE_VECTOR_FLOAT:
7468         case MODE_VECTOR_FRACT:
7469         case MODE_VECTOR_UFRACT:
7470         case MODE_VECTOR_ACCUM:
7471         case MODE_VECTOR_UACCUM:
7472           warning (OPT_Wattributes, "specifying vector types with "
7473                    "__attribute__ ((mode)) is deprecated");
7474           warning (OPT_Wattributes,
7475                    "use __attribute__ ((vector_size)) instead");
7476           valid_mode = vector_mode_valid_p (mode);
7477           break;
7478
7479         default:
7480           break;
7481         }
7482       if (!valid_mode)
7483         {
7484           error ("unable to emulate %qs", p);
7485           return NULL_TREE;
7486         }
7487
7488       if (POINTER_TYPE_P (type))
7489         {
7490           addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (type));
7491           tree (*fn)(tree, machine_mode, bool);
7492
7493           if (!targetm.addr_space.valid_pointer_mode (mode, as))
7494             {
7495               error ("invalid pointer mode %qs", p);
7496               return NULL_TREE;
7497             }
7498
7499           if (TREE_CODE (type) == POINTER_TYPE)
7500             fn = build_pointer_type_for_mode;
7501           else
7502             fn = build_reference_type_for_mode;
7503           typefm = fn (TREE_TYPE (type), mode, false);
7504         }
7505       else
7506         {
7507           /* For fixed-point modes, we need to test if the signness of type
7508              and the machine mode are consistent.  */
7509           if (ALL_FIXED_POINT_MODE_P (mode)
7510               && TYPE_UNSIGNED (type) != UNSIGNED_FIXED_POINT_MODE_P (mode))
7511             {
7512               error ("signedness of type and machine mode %qs don%'t match", p);
7513               return NULL_TREE;
7514             }
7515           /* For fixed-point modes, we need to pass saturating info.  */
7516           typefm = lang_hooks.types.type_for_mode (mode,
7517                         ALL_FIXED_POINT_MODE_P (mode) ? TYPE_SATURATING (type)
7518                                                       : TYPE_UNSIGNED (type));
7519         }
7520
7521       if (typefm == NULL_TREE)
7522         {
7523           error ("no data type for mode %qs", p);
7524           return NULL_TREE;
7525         }
7526       else if (TREE_CODE (type) == ENUMERAL_TYPE)
7527         {
7528           /* For enumeral types, copy the precision from the integer
7529              type returned above.  If not an INTEGER_TYPE, we can't use
7530              this mode for this type.  */
7531           if (TREE_CODE (typefm) != INTEGER_TYPE)
7532             {
7533               error ("cannot use mode %qs for enumeral types", p);
7534               return NULL_TREE;
7535             }
7536
7537           if (flags & ATTR_FLAG_TYPE_IN_PLACE)
7538             {
7539               TYPE_PRECISION (type) = TYPE_PRECISION (typefm);
7540               typefm = type;
7541             }
7542           else
7543             {
7544               /* We cannot build a type variant, as there's code that assumes
7545                  that TYPE_MAIN_VARIANT has the same mode.  This includes the
7546                  debug generators.  Instead, create a subrange type.  This
7547                  results in all of the enumeral values being emitted only once
7548                  in the original, and the subtype gets them by reference.  */
7549               if (TYPE_UNSIGNED (type))
7550                 typefm = make_unsigned_type (TYPE_PRECISION (typefm));
7551               else
7552                 typefm = make_signed_type (TYPE_PRECISION (typefm));
7553               TREE_TYPE (typefm) = type;
7554             }
7555         }
7556       else if (VECTOR_MODE_P (mode)
7557                ? TREE_CODE (type) != TREE_CODE (TREE_TYPE (typefm))
7558                : TREE_CODE (type) != TREE_CODE (typefm))
7559         {
7560           error ("mode %qs applied to inappropriate type", p);
7561           return NULL_TREE;
7562         }
7563
7564       *node = typefm;
7565     }
7566
7567   return NULL_TREE;
7568 }
7569
7570 /* Handle a "section" attribute; arguments as in
7571    struct attribute_spec.handler.  */
7572
7573 static tree
7574 handle_section_attribute (tree *node, tree ARG_UNUSED (name), tree args,
7575                           int ARG_UNUSED (flags), bool *no_add_attrs)
7576 {
7577   tree decl = *node;
7578
7579   if (targetm_common.have_named_sections)
7580     {
7581       user_defined_section_attribute = true;
7582
7583       if ((TREE_CODE (decl) == FUNCTION_DECL
7584            || TREE_CODE (decl) == VAR_DECL)
7585           && TREE_CODE (TREE_VALUE (args)) == STRING_CST)
7586         {
7587           if (TREE_CODE (decl) == VAR_DECL
7588               && current_function_decl != NULL_TREE
7589               && !TREE_STATIC (decl))
7590             {
7591               error_at (DECL_SOURCE_LOCATION (decl),
7592                         "section attribute cannot be specified for "
7593                         "local variables");
7594               *no_add_attrs = true;
7595             }
7596
7597           /* The decl may have already been given a section attribute
7598              from a previous declaration.  Ensure they match.  */
7599           else if (DECL_SECTION_NAME (decl) != NULL
7600                    && strcmp (DECL_SECTION_NAME (decl),
7601                               TREE_STRING_POINTER (TREE_VALUE (args))) != 0)
7602             {
7603               error ("section of %q+D conflicts with previous declaration",
7604                      *node);
7605               *no_add_attrs = true;
7606             }
7607           else if (TREE_CODE (decl) == VAR_DECL
7608                    && !targetm.have_tls && targetm.emutls.tmpl_section
7609                    && DECL_THREAD_LOCAL_P (decl))
7610             {
7611               error ("section of %q+D cannot be overridden", *node);
7612               *no_add_attrs = true;
7613             }
7614           else
7615             set_decl_section_name (decl,
7616                                    TREE_STRING_POINTER (TREE_VALUE (args)));
7617         }
7618       else
7619         {
7620           error ("section attribute not allowed for %q+D", *node);
7621           *no_add_attrs = true;
7622         }
7623     }
7624   else
7625     {
7626       error_at (DECL_SOURCE_LOCATION (*node),
7627                 "section attributes are not supported for this target");
7628       *no_add_attrs = true;
7629     }
7630
7631   return NULL_TREE;
7632 }
7633
7634 /* Check whether ALIGN is a valid user-specified alignment.  If so,
7635    return its base-2 log; if not, output an error and return -1.  If
7636    ALLOW_ZERO then 0 is valid and should result in a return of -1 with
7637    no error.  */
7638 int
7639 check_user_alignment (const_tree align, bool allow_zero)
7640 {
7641   int i;
7642
7643   if (error_operand_p (align))
7644     return -1;
7645   if (TREE_CODE (align) != INTEGER_CST
7646       || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
7647     {
7648       error ("requested alignment is not an integer constant");
7649       return -1;
7650     }
7651   else if (allow_zero && integer_zerop (align))
7652     return -1;
7653   else if (tree_int_cst_sgn (align) == -1
7654            || (i = tree_log2 (align)) == -1)
7655     {
7656       error ("requested alignment is not a positive power of 2");
7657       return -1;
7658     }
7659   else if (i >= HOST_BITS_PER_INT - BITS_PER_UNIT_LOG)
7660     {
7661       error ("requested alignment is too large");
7662       return -1;
7663     }
7664   return i;
7665 }
7666
7667 /* 
7668    If in c++-11, check if the c++-11 alignment constraint with respect
7669    to fundamental alignment (in [dcl.align]) are satisfied.  If not in
7670    c++-11 mode, does nothing.
7671
7672    [dcl.align]2/ says:
7673
7674    [* if the constant expression evaluates to a fundamental alignment,
7675    the alignment requirement of the declared entity shall be the
7676    specified fundamental alignment.
7677
7678    * if the constant expression evaluates to an extended alignment
7679    and the implementation supports that alignment in the context
7680    of the declaration, the alignment of the declared entity shall
7681    be that alignment
7682
7683    * if the constant expression evaluates to an extended alignment
7684    and the implementation does not support that alignment in the
7685    context of the declaration, the program is ill-formed].  */
7686
7687 static bool
7688 check_cxx_fundamental_alignment_constraints (tree node,
7689                                              unsigned align_log,
7690                                              int flags)
7691 {
7692   bool alignment_too_large_p = false;
7693   unsigned requested_alignment = 1U << align_log;
7694   unsigned max_align = 0;
7695
7696   if ((!(flags & ATTR_FLAG_CXX11) && !warn_cxx_compat)
7697       || (node == NULL_TREE || node == error_mark_node))
7698     return true;
7699
7700   if (cxx_fundamental_alignment_p (requested_alignment))
7701     return true;
7702
7703   if (DECL_P (node))
7704     {
7705       if (TREE_STATIC (node))
7706         {
7707           /* For file scope variables and static members, the target
7708              supports alignments that are at most
7709              MAX_OFILE_ALIGNMENT.  */
7710           if (requested_alignment > (max_align = MAX_OFILE_ALIGNMENT))
7711             alignment_too_large_p = true;
7712         }
7713       else
7714         {
7715 #ifdef BIGGEST_FIELD_ALIGNMENT
7716 #define MAX_TARGET_FIELD_ALIGNMENT BIGGEST_FIELD_ALIGNMENT
7717 #else
7718 #define MAX_TARGET_FIELD_ALIGNMENT BIGGEST_ALIGNMENT
7719 #endif
7720           /* For non-static members, the target supports either
7721              alignments that at most either BIGGEST_FIELD_ALIGNMENT
7722              if it is defined or BIGGEST_ALIGNMENT.  */
7723           max_align = MAX_TARGET_FIELD_ALIGNMENT;
7724           if (TREE_CODE (node) == FIELD_DECL
7725               && requested_alignment > (max_align = MAX_TARGET_FIELD_ALIGNMENT))
7726             alignment_too_large_p = true;
7727 #undef MAX_TARGET_FIELD_ALIGNMENT
7728           /* For stack variables, the target supports at most
7729              MAX_STACK_ALIGNMENT.  */
7730           else if (decl_function_context (node) != NULL
7731                    && requested_alignment > (max_align = MAX_STACK_ALIGNMENT))
7732             alignment_too_large_p = true;
7733         }
7734     }
7735   else if (TYPE_P (node))
7736     {
7737       /* Let's be liberal for types.  */
7738       if (requested_alignment > (max_align = BIGGEST_ALIGNMENT))
7739         alignment_too_large_p = true;
7740     }
7741
7742   if (alignment_too_large_p)
7743     pedwarn (input_location, OPT_Wattributes,
7744              "requested alignment %d is larger than %d",
7745              requested_alignment, max_align);
7746
7747   return !alignment_too_large_p;
7748 }
7749
7750 /* Handle a "aligned" attribute; arguments as in
7751    struct attribute_spec.handler.  */
7752
7753 static tree
7754 handle_aligned_attribute (tree *node, tree ARG_UNUSED (name), tree args,
7755                           int flags, bool *no_add_attrs)
7756 {
7757   tree decl = NULL_TREE;
7758   tree *type = NULL;
7759   int is_type = 0;
7760   tree align_expr;
7761   int i;
7762
7763   if (args)
7764     {
7765       align_expr = TREE_VALUE (args);
7766       if (align_expr && TREE_CODE (align_expr) != IDENTIFIER_NODE
7767           && TREE_CODE (align_expr) != FUNCTION_DECL)
7768         align_expr = default_conversion (align_expr);
7769     }
7770   else
7771     align_expr = size_int (ATTRIBUTE_ALIGNED_VALUE / BITS_PER_UNIT);
7772
7773   if (DECL_P (*node))
7774     {
7775       decl = *node;
7776       type = &TREE_TYPE (decl);
7777       is_type = TREE_CODE (*node) == TYPE_DECL;
7778     }
7779   else if (TYPE_P (*node))
7780     type = node, is_type = 1;
7781
7782   if ((i = check_user_alignment (align_expr, false)) == -1
7783       || !check_cxx_fundamental_alignment_constraints (*node, i, flags))
7784     *no_add_attrs = true;
7785   else if (is_type)
7786     {
7787       if ((flags & (int) ATTR_FLAG_TYPE_IN_PLACE))
7788         /* OK, modify the type in place.  */;
7789       /* If we have a TYPE_DECL, then copy the type, so that we
7790          don't accidentally modify a builtin type.  See pushdecl.  */
7791       else if (decl && TREE_TYPE (decl) != error_mark_node
7792                && DECL_ORIGINAL_TYPE (decl) == NULL_TREE)
7793         {
7794           tree tt = TREE_TYPE (decl);
7795           *type = build_variant_type_copy (*type);
7796           DECL_ORIGINAL_TYPE (decl) = tt;
7797           TYPE_NAME (*type) = decl;
7798           TREE_USED (*type) = TREE_USED (decl);
7799           TREE_TYPE (decl) = *type;
7800         }
7801       else
7802         *type = build_variant_type_copy (*type);
7803
7804       TYPE_ALIGN (*type) = (1U << i) * BITS_PER_UNIT;
7805       TYPE_USER_ALIGN (*type) = 1;
7806     }
7807   else if (! VAR_OR_FUNCTION_DECL_P (decl)
7808            && TREE_CODE (decl) != FIELD_DECL)
7809     {
7810       error ("alignment may not be specified for %q+D", decl);
7811       *no_add_attrs = true;
7812     }
7813   else if (DECL_USER_ALIGN (decl)
7814            && DECL_ALIGN (decl) > (1U << i) * BITS_PER_UNIT)
7815     /* C++-11 [dcl.align/4]:
7816
7817            When multiple alignment-specifiers are specified for an
7818            entity, the alignment requirement shall be set to the
7819            strictest specified alignment.
7820
7821       This formally comes from the c++11 specification but we are
7822       doing it for the GNU attribute syntax as well.  */
7823     *no_add_attrs = true;
7824   else if (TREE_CODE (decl) == FUNCTION_DECL
7825            && DECL_ALIGN (decl) > (1U << i) * BITS_PER_UNIT)
7826     {
7827       if (DECL_USER_ALIGN (decl))
7828         error ("alignment for %q+D was previously specified as %d "
7829                "and may not be decreased", decl,
7830                DECL_ALIGN (decl) / BITS_PER_UNIT);
7831       else
7832         error ("alignment for %q+D must be at least %d", decl,
7833                DECL_ALIGN (decl) / BITS_PER_UNIT);
7834       *no_add_attrs = true;
7835     }
7836   else
7837     {
7838       DECL_ALIGN (decl) = (1U << i) * BITS_PER_UNIT;
7839       DECL_USER_ALIGN (decl) = 1;
7840     }
7841
7842   return NULL_TREE;
7843 }
7844
7845 /* Handle a "weak" attribute; arguments as in
7846    struct attribute_spec.handler.  */
7847
7848 static tree
7849 handle_weak_attribute (tree *node, tree name,
7850                        tree ARG_UNUSED (args),
7851                        int ARG_UNUSED (flags),
7852                        bool * ARG_UNUSED (no_add_attrs))
7853 {
7854   if (TREE_CODE (*node) == FUNCTION_DECL
7855       && DECL_DECLARED_INLINE_P (*node))
7856     {
7857       warning (OPT_Wattributes, "inline function %q+D declared weak", *node);
7858       *no_add_attrs = true;
7859     }
7860   else if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (*node)))
7861     {
7862       error ("indirect function %q+D cannot be declared weak", *node);
7863       *no_add_attrs = true;
7864       return NULL_TREE;
7865     }
7866   else if (TREE_CODE (*node) == FUNCTION_DECL
7867            || TREE_CODE (*node) == VAR_DECL)
7868     {
7869       struct symtab_node *n = symtab_node::get (*node);
7870       if (n && n->refuse_visibility_changes)
7871         error ("%+D declared weak after being used", *node);
7872       declare_weak (*node);
7873     }
7874   else
7875     warning (OPT_Wattributes, "%qE attribute ignored", name);
7876
7877   return NULL_TREE;
7878 }
7879
7880 /* Handle an "alias" or "ifunc" attribute; arguments as in
7881    struct attribute_spec.handler, except that IS_ALIAS tells us
7882    whether this is an alias as opposed to ifunc attribute.  */
7883
7884 static tree
7885 handle_alias_ifunc_attribute (bool is_alias, tree *node, tree name, tree args,
7886                               bool *no_add_attrs)
7887 {
7888   tree decl = *node;
7889
7890   if (TREE_CODE (decl) != FUNCTION_DECL
7891       && (!is_alias || TREE_CODE (decl) != VAR_DECL))
7892     {
7893       warning (OPT_Wattributes, "%qE attribute ignored", name);
7894       *no_add_attrs = true;
7895     }
7896   else if ((TREE_CODE (decl) == FUNCTION_DECL && DECL_INITIAL (decl))
7897       || (TREE_CODE (decl) != FUNCTION_DECL
7898           && TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
7899       /* A static variable declaration is always a tentative definition,
7900          but the alias is a non-tentative definition which overrides.  */
7901       || (TREE_CODE (decl) != FUNCTION_DECL
7902           && ! TREE_PUBLIC (decl) && DECL_INITIAL (decl)))
7903     {
7904       error ("%q+D defined both normally and as %qE attribute", decl, name);
7905       *no_add_attrs = true;
7906       return NULL_TREE;
7907     }
7908   else if (!is_alias
7909            && (lookup_attribute ("weak", DECL_ATTRIBUTES (decl)) 
7910                || lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))))
7911     {
7912       error ("weak %q+D cannot be defined %qE", decl, name);
7913       *no_add_attrs = true;
7914       return NULL_TREE;
7915     }                    
7916
7917   /* Note that the very first time we process a nested declaration,
7918      decl_function_context will not be set.  Indeed, *would* never
7919      be set except for the DECL_INITIAL/DECL_EXTERNAL frobbery that
7920      we do below.  After such frobbery, pushdecl would set the context.
7921      In any case, this is never what we want.  */
7922   else if (decl_function_context (decl) == 0 && current_function_decl == NULL)
7923     {
7924       tree id;
7925
7926       id = TREE_VALUE (args);
7927       if (TREE_CODE (id) != STRING_CST)
7928         {
7929           error ("attribute %qE argument not a string", name);
7930           *no_add_attrs = true;
7931           return NULL_TREE;
7932         }
7933       id = get_identifier (TREE_STRING_POINTER (id));
7934       /* This counts as a use of the object pointed to.  */
7935       TREE_USED (id) = 1;
7936
7937       if (TREE_CODE (decl) == FUNCTION_DECL)
7938         DECL_INITIAL (decl) = error_mark_node;
7939       else
7940         TREE_STATIC (decl) = 1;
7941
7942       if (!is_alias)
7943         /* ifuncs are also aliases, so set that attribute too. */
7944         DECL_ATTRIBUTES (decl)
7945           = tree_cons (get_identifier ("alias"), args, DECL_ATTRIBUTES (decl));
7946     }
7947   else
7948     {
7949       warning (OPT_Wattributes, "%qE attribute ignored", name);
7950       *no_add_attrs = true;
7951     }
7952
7953   if (decl_in_symtab_p (*node))
7954     {
7955       struct symtab_node *n = symtab_node::get (decl);
7956       if (n && n->refuse_visibility_changes)
7957         {
7958           if (is_alias)
7959             error ("%+D declared alias after being used", decl);
7960           else
7961             error ("%+D declared ifunc after being used", decl);
7962         }
7963     }
7964
7965
7966   return NULL_TREE;
7967 }
7968
7969 /* Handle an "alias" or "ifunc" attribute; arguments as in
7970    struct attribute_spec.handler.  */
7971
7972 static tree
7973 handle_ifunc_attribute (tree *node, tree name, tree args,
7974                         int ARG_UNUSED (flags), bool *no_add_attrs)
7975 {
7976   return handle_alias_ifunc_attribute (false, node, name, args, no_add_attrs);
7977 }
7978
7979 /* Handle an "alias" or "ifunc" attribute; arguments as in
7980    struct attribute_spec.handler.  */
7981
7982 static tree
7983 handle_alias_attribute (tree *node, tree name, tree args,
7984                         int ARG_UNUSED (flags), bool *no_add_attrs)
7985 {
7986   return handle_alias_ifunc_attribute (true, node, name, args, no_add_attrs);
7987 }
7988
7989 /* Handle a "weakref" attribute; arguments as in struct
7990    attribute_spec.handler.  */
7991
7992 static tree
7993 handle_weakref_attribute (tree *node, tree ARG_UNUSED (name), tree args,
7994                           int flags, bool *no_add_attrs)
7995 {
7996   tree attr = NULL_TREE;
7997
7998   /* We must ignore the attribute when it is associated with
7999      local-scoped decls, since attribute alias is ignored and many
8000      such symbols do not even have a DECL_WEAK field.  */
8001   if (decl_function_context (*node)
8002       || current_function_decl
8003       || (TREE_CODE (*node) != VAR_DECL && TREE_CODE (*node) != FUNCTION_DECL))
8004     {
8005       warning (OPT_Wattributes, "%qE attribute ignored", name);
8006       *no_add_attrs = true;
8007       return NULL_TREE;
8008     }
8009
8010   if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (*node)))
8011     {
8012       error ("indirect function %q+D cannot be declared weakref", *node);
8013       *no_add_attrs = true;
8014       return NULL_TREE;
8015     }
8016
8017   /* The idea here is that `weakref("name")' mutates into `weakref,
8018      alias("name")', and weakref without arguments, in turn,
8019      implicitly adds weak. */
8020
8021   if (args)
8022     {
8023       attr = tree_cons (get_identifier ("alias"), args, attr);
8024       attr = tree_cons (get_identifier ("weakref"), NULL_TREE, attr);
8025
8026       *no_add_attrs = true;
8027
8028       decl_attributes (node, attr, flags);
8029     }
8030   else
8031     {
8032       if (lookup_attribute ("alias", DECL_ATTRIBUTES (*node)))
8033         error_at (DECL_SOURCE_LOCATION (*node),
8034                   "weakref attribute must appear before alias attribute");
8035
8036       /* Can't call declare_weak because it wants this to be TREE_PUBLIC,
8037          and that isn't supported; and because it wants to add it to
8038          the list of weak decls, which isn't helpful.  */
8039       DECL_WEAK (*node) = 1;
8040     }
8041
8042   if (decl_in_symtab_p (*node))
8043     {
8044       struct symtab_node *n = symtab_node::get (*node);
8045       if (n && n->refuse_visibility_changes)
8046         error ("%+D declared weakref after being used", *node);
8047     }
8048
8049   return NULL_TREE;
8050 }
8051
8052 /* Handle an "visibility" attribute; arguments as in
8053    struct attribute_spec.handler.  */
8054
8055 static tree
8056 handle_visibility_attribute (tree *node, tree name, tree args,
8057                              int ARG_UNUSED (flags),
8058                              bool *ARG_UNUSED (no_add_attrs))
8059 {
8060   tree decl = *node;
8061   tree id = TREE_VALUE (args);
8062   enum symbol_visibility vis;
8063
8064   if (TYPE_P (*node))
8065     {
8066       if (TREE_CODE (*node) == ENUMERAL_TYPE)
8067         /* OK */;
8068       else if (TREE_CODE (*node) != RECORD_TYPE && TREE_CODE (*node) != UNION_TYPE)
8069         {
8070           warning (OPT_Wattributes, "%qE attribute ignored on non-class types",
8071                    name);
8072           return NULL_TREE;
8073         }
8074       else if (TYPE_FIELDS (*node))
8075         {
8076           error ("%qE attribute ignored because %qT is already defined",
8077                  name, *node);
8078           return NULL_TREE;
8079         }
8080     }
8081   else if (decl_function_context (decl) != 0 || !TREE_PUBLIC (decl))
8082     {
8083       warning (OPT_Wattributes, "%qE attribute ignored", name);
8084       return NULL_TREE;
8085     }
8086
8087   if (TREE_CODE (id) != STRING_CST)
8088     {
8089       error ("visibility argument not a string");
8090       return NULL_TREE;
8091     }
8092
8093   /*  If this is a type, set the visibility on the type decl.  */
8094   if (TYPE_P (decl))
8095     {
8096       decl = TYPE_NAME (decl);
8097       if (!decl)
8098         return NULL_TREE;
8099       if (TREE_CODE (decl) == IDENTIFIER_NODE)
8100         {
8101            warning (OPT_Wattributes, "%qE attribute ignored on types",
8102                     name);
8103            return NULL_TREE;
8104         }
8105     }
8106
8107   if (strcmp (TREE_STRING_POINTER (id), "default") == 0)
8108     vis = VISIBILITY_DEFAULT;
8109   else if (strcmp (TREE_STRING_POINTER (id), "internal") == 0)
8110     vis = VISIBILITY_INTERNAL;
8111   else if (strcmp (TREE_STRING_POINTER (id), "hidden") == 0)
8112     vis = VISIBILITY_HIDDEN;
8113   else if (strcmp (TREE_STRING_POINTER (id), "protected") == 0)
8114     vis = VISIBILITY_PROTECTED;
8115   else
8116     {
8117       error ("visibility argument must be one of \"default\", \"hidden\", \"protected\" or \"internal\"");
8118       vis = VISIBILITY_DEFAULT;
8119     }
8120
8121   if (DECL_VISIBILITY_SPECIFIED (decl)
8122       && vis != DECL_VISIBILITY (decl))
8123     {
8124       tree attributes = (TYPE_P (*node)
8125                          ? TYPE_ATTRIBUTES (*node)
8126                          : DECL_ATTRIBUTES (decl));
8127       if (lookup_attribute ("visibility", attributes))
8128         error ("%qD redeclared with different visibility", decl);
8129       else if (TARGET_DLLIMPORT_DECL_ATTRIBUTES
8130                && lookup_attribute ("dllimport", attributes))
8131         error ("%qD was declared %qs which implies default visibility",
8132                decl, "dllimport");
8133       else if (TARGET_DLLIMPORT_DECL_ATTRIBUTES
8134                && lookup_attribute ("dllexport", attributes))
8135         error ("%qD was declared %qs which implies default visibility",
8136                decl, "dllexport");
8137     }
8138
8139   DECL_VISIBILITY (decl) = vis;
8140   DECL_VISIBILITY_SPECIFIED (decl) = 1;
8141
8142   /* Go ahead and attach the attribute to the node as well.  This is needed
8143      so we can determine whether we have VISIBILITY_DEFAULT because the
8144      visibility was not specified, or because it was explicitly overridden
8145      from the containing scope.  */
8146
8147   return NULL_TREE;
8148 }
8149
8150 /* Determine the ELF symbol visibility for DECL, which is either a
8151    variable or a function.  It is an error to use this function if a
8152    definition of DECL is not available in this translation unit.
8153    Returns true if the final visibility has been determined by this
8154    function; false if the caller is free to make additional
8155    modifications.  */
8156
8157 bool
8158 c_determine_visibility (tree decl)
8159 {
8160   gcc_assert (TREE_CODE (decl) == VAR_DECL
8161               || TREE_CODE (decl) == FUNCTION_DECL);
8162
8163   /* If the user explicitly specified the visibility with an
8164      attribute, honor that.  DECL_VISIBILITY will have been set during
8165      the processing of the attribute.  We check for an explicit
8166      attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
8167      to distinguish the use of an attribute from the use of a "#pragma
8168      GCC visibility push(...)"; in the latter case we still want other
8169      considerations to be able to overrule the #pragma.  */
8170   if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
8171       || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
8172           && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
8173               || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
8174     return true;
8175
8176   /* Set default visibility to whatever the user supplied with
8177      visibility_specified depending on #pragma GCC visibility.  */
8178   if (!DECL_VISIBILITY_SPECIFIED (decl))
8179     {
8180       if (visibility_options.inpragma
8181           || DECL_VISIBILITY (decl) != default_visibility)
8182         {
8183           DECL_VISIBILITY (decl) = default_visibility;
8184           DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
8185           /* If visibility changed and DECL already has DECL_RTL, ensure
8186              symbol flags are updated.  */
8187           if (((TREE_CODE (decl) == VAR_DECL && TREE_STATIC (decl))
8188                || TREE_CODE (decl) == FUNCTION_DECL)
8189               && DECL_RTL_SET_P (decl))
8190             make_decl_rtl (decl);
8191         }
8192     }
8193   return false;
8194 }
8195
8196 /* Handle an "tls_model" attribute; arguments as in
8197    struct attribute_spec.handler.  */
8198
8199 static tree
8200 handle_tls_model_attribute (tree *node, tree name, tree args,
8201                             int ARG_UNUSED (flags), bool *no_add_attrs)
8202 {
8203   tree id;
8204   tree decl = *node;
8205   enum tls_model kind;
8206
8207   *no_add_attrs = true;
8208
8209   if (TREE_CODE (decl) != VAR_DECL || !DECL_THREAD_LOCAL_P (decl))
8210     {
8211       warning (OPT_Wattributes, "%qE attribute ignored", name);
8212       return NULL_TREE;
8213     }
8214
8215   kind = DECL_TLS_MODEL (decl);
8216   id = TREE_VALUE (args);
8217   if (TREE_CODE (id) != STRING_CST)
8218     {
8219       error ("tls_model argument not a string");
8220       return NULL_TREE;
8221     }
8222
8223   if (!strcmp (TREE_STRING_POINTER (id), "local-exec"))
8224     kind = TLS_MODEL_LOCAL_EXEC;
8225   else if (!strcmp (TREE_STRING_POINTER (id), "initial-exec"))
8226     kind = TLS_MODEL_INITIAL_EXEC;
8227   else if (!strcmp (TREE_STRING_POINTER (id), "local-dynamic"))
8228     kind = optimize ? TLS_MODEL_LOCAL_DYNAMIC : TLS_MODEL_GLOBAL_DYNAMIC;
8229   else if (!strcmp (TREE_STRING_POINTER (id), "global-dynamic"))
8230     kind = TLS_MODEL_GLOBAL_DYNAMIC;
8231   else
8232     error ("tls_model argument must be one of \"local-exec\", \"initial-exec\", \"local-dynamic\" or \"global-dynamic\"");
8233
8234   set_decl_tls_model (decl, kind);
8235   return NULL_TREE;
8236 }
8237
8238 /* Handle a "no_instrument_function" attribute; arguments as in
8239    struct attribute_spec.handler.  */
8240
8241 static tree
8242 handle_no_instrument_function_attribute (tree *node, tree name,
8243                                          tree ARG_UNUSED (args),
8244                                          int ARG_UNUSED (flags),
8245                                          bool *no_add_attrs)
8246 {
8247   tree decl = *node;
8248
8249   if (TREE_CODE (decl) != FUNCTION_DECL)
8250     {
8251       error_at (DECL_SOURCE_LOCATION (decl),
8252                 "%qE attribute applies only to functions", name);
8253       *no_add_attrs = true;
8254     }
8255   else
8256     DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl) = 1;
8257
8258   return NULL_TREE;
8259 }
8260
8261 /* Handle a "malloc" attribute; arguments as in
8262    struct attribute_spec.handler.  */
8263
8264 static tree
8265 handle_malloc_attribute (tree *node, tree name, tree ARG_UNUSED (args),
8266                          int ARG_UNUSED (flags), bool *no_add_attrs)
8267 {
8268   if (TREE_CODE (*node) == FUNCTION_DECL
8269       && POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (*node))))
8270     DECL_IS_MALLOC (*node) = 1;
8271   else
8272     {
8273       warning (OPT_Wattributes, "%qE attribute ignored", name);
8274       *no_add_attrs = true;
8275     }
8276
8277   return NULL_TREE;
8278 }
8279
8280 /* Handle a "alloc_size" attribute; arguments as in
8281    struct attribute_spec.handler.  */
8282
8283 static tree
8284 handle_alloc_size_attribute (tree *node, tree ARG_UNUSED (name), tree args,
8285                              int ARG_UNUSED (flags), bool *no_add_attrs)
8286 {
8287   unsigned arg_count = type_num_arguments (*node);
8288   for (; args; args = TREE_CHAIN (args))
8289     {
8290       tree position = TREE_VALUE (args);
8291       if (position && TREE_CODE (position) != IDENTIFIER_NODE
8292           && TREE_CODE (position) != FUNCTION_DECL)
8293         position = default_conversion (position);
8294
8295       if (!tree_fits_uhwi_p (position)
8296           || !arg_count
8297           || !IN_RANGE (tree_to_uhwi (position), 1, arg_count))
8298         {
8299           warning (OPT_Wattributes,
8300                    "alloc_size parameter outside range");
8301           *no_add_attrs = true;
8302           return NULL_TREE;
8303         }
8304     }
8305   return NULL_TREE;
8306 }
8307
8308 /* Handle a "alloc_align" attribute; arguments as in
8309    struct attribute_spec.handler.  */
8310
8311 static tree
8312 handle_alloc_align_attribute (tree *node, tree, tree args, int,
8313                               bool *no_add_attrs)
8314 {
8315   unsigned arg_count = type_num_arguments (*node);
8316   tree position = TREE_VALUE (args);
8317   if (position && TREE_CODE (position) != IDENTIFIER_NODE)
8318     position = default_conversion (position);
8319
8320   if (!tree_fits_uhwi_p (position)
8321       || !arg_count
8322       || !IN_RANGE (tree_to_uhwi (position), 1, arg_count))
8323     {
8324       warning (OPT_Wattributes,
8325                "alloc_align parameter outside range");
8326       *no_add_attrs = true;
8327       return NULL_TREE;
8328     }
8329   return NULL_TREE;
8330 }
8331
8332 /* Handle a "assume_aligned" attribute; arguments as in
8333    struct attribute_spec.handler.  */
8334
8335 static tree
8336 handle_assume_aligned_attribute (tree *, tree, tree args, int,
8337                                  bool *no_add_attrs)
8338 {
8339   for (; args; args = TREE_CHAIN (args))
8340     {
8341       tree position = TREE_VALUE (args);
8342       if (position && TREE_CODE (position) != IDENTIFIER_NODE
8343           && TREE_CODE (position) != FUNCTION_DECL)
8344         position = default_conversion (position);
8345
8346       if (TREE_CODE (position) != INTEGER_CST)
8347         {
8348           warning (OPT_Wattributes,
8349                    "assume_aligned parameter not integer constant");
8350           *no_add_attrs = true;
8351           return NULL_TREE;
8352         }
8353     }
8354   return NULL_TREE;
8355 }
8356
8357 /* Handle a "fn spec" attribute; arguments as in
8358    struct attribute_spec.handler.  */
8359
8360 static tree
8361 handle_fnspec_attribute (tree *node ATTRIBUTE_UNUSED, tree ARG_UNUSED (name),
8362                          tree args, int ARG_UNUSED (flags),
8363                          bool *no_add_attrs ATTRIBUTE_UNUSED)
8364 {
8365   gcc_assert (args
8366               && TREE_CODE (TREE_VALUE (args)) == STRING_CST
8367               && !TREE_CHAIN (args));
8368   return NULL_TREE;
8369 }
8370
8371 /* Handle a "bnd_variable_size" attribute; arguments as in
8372    struct attribute_spec.handler.  */
8373
8374 static tree
8375 handle_bnd_variable_size_attribute (tree *node, tree name, tree ARG_UNUSED (args),
8376                                     int ARG_UNUSED (flags), bool *no_add_attrs)
8377 {
8378   if (TREE_CODE (*node) != FIELD_DECL)
8379     {
8380       warning (OPT_Wattributes, "%qE attribute ignored", name);
8381       *no_add_attrs = true;
8382     }
8383
8384   return NULL_TREE;
8385 }
8386
8387 /* Handle a "bnd_legacy" attribute; arguments as in
8388    struct attribute_spec.handler.  */
8389
8390 static tree
8391 handle_bnd_legacy (tree *node, tree name, tree ARG_UNUSED (args),
8392                    int ARG_UNUSED (flags), bool *no_add_attrs)
8393 {
8394   if (TREE_CODE (*node) != FUNCTION_DECL)
8395     {
8396       warning (OPT_Wattributes, "%qE attribute ignored", name);
8397       *no_add_attrs = true;
8398     }
8399
8400   return NULL_TREE;
8401 }
8402
8403 /* Handle a "bnd_instrument" attribute; arguments as in
8404    struct attribute_spec.handler.  */
8405
8406 static tree
8407 handle_bnd_instrument (tree *node, tree name, tree ARG_UNUSED (args),
8408                        int ARG_UNUSED (flags), bool *no_add_attrs)
8409 {
8410   if (TREE_CODE (*node) != FUNCTION_DECL)
8411     {
8412       warning (OPT_Wattributes, "%qE attribute ignored", name);
8413       *no_add_attrs = true;
8414     }
8415
8416   return NULL_TREE;
8417 }
8418
8419 /* Handle a "warn_unused" attribute; arguments as in
8420    struct attribute_spec.handler.  */
8421
8422 static tree
8423 handle_warn_unused_attribute (tree *node, tree name,
8424                               tree args ATTRIBUTE_UNUSED,
8425                               int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
8426 {
8427   if (TYPE_P (*node))
8428     /* Do nothing else, just set the attribute.  We'll get at
8429        it later with lookup_attribute.  */
8430     ;
8431   else
8432     {
8433       warning (OPT_Wattributes, "%qE attribute ignored", name);
8434       *no_add_attrs = true;
8435     }
8436
8437   return NULL_TREE;
8438 }
8439
8440 /* Handle an "omp declare simd" attribute; arguments as in
8441    struct attribute_spec.handler.  */
8442
8443 static tree
8444 handle_omp_declare_simd_attribute (tree *, tree, tree, int, bool *)
8445 {
8446   return NULL_TREE;
8447 }
8448
8449 /* Handle an "omp declare target" attribute; arguments as in
8450    struct attribute_spec.handler.  */
8451
8452 static tree
8453 handle_omp_declare_target_attribute (tree *, tree, tree, int, bool *)
8454 {
8455   return NULL_TREE;
8456 }
8457
8458 /* Handle a "returns_twice" attribute; arguments as in
8459    struct attribute_spec.handler.  */
8460
8461 static tree
8462 handle_returns_twice_attribute (tree *node, tree name, tree ARG_UNUSED (args),
8463                          int ARG_UNUSED (flags), bool *no_add_attrs)
8464 {
8465   if (TREE_CODE (*node) == FUNCTION_DECL)
8466     DECL_IS_RETURNS_TWICE (*node) = 1;
8467   else
8468     {
8469       warning (OPT_Wattributes, "%qE attribute ignored", name);
8470       *no_add_attrs = true;
8471     }
8472
8473   return NULL_TREE;
8474 }
8475
8476 /* Handle a "no_limit_stack" attribute; arguments as in
8477    struct attribute_spec.handler.  */
8478
8479 static tree
8480 handle_no_limit_stack_attribute (tree *node, tree name,
8481                                  tree ARG_UNUSED (args),
8482                                  int ARG_UNUSED (flags),
8483                                  bool *no_add_attrs)
8484 {
8485   tree decl = *node;
8486
8487   if (TREE_CODE (decl) != FUNCTION_DECL)
8488     {
8489       error_at (DECL_SOURCE_LOCATION (decl),
8490              "%qE attribute applies only to functions", name);
8491       *no_add_attrs = true;
8492     }
8493   else if (DECL_INITIAL (decl))
8494     {
8495       error_at (DECL_SOURCE_LOCATION (decl),
8496                 "can%'t set %qE attribute after definition", name);
8497       *no_add_attrs = true;
8498     }
8499   else
8500     DECL_NO_LIMIT_STACK (decl) = 1;
8501
8502   return NULL_TREE;
8503 }
8504
8505 /* Handle a "pure" attribute; arguments as in
8506    struct attribute_spec.handler.  */
8507
8508 static tree
8509 handle_pure_attribute (tree *node, tree name, tree ARG_UNUSED (args),
8510                        int ARG_UNUSED (flags), bool *no_add_attrs)
8511 {
8512   if (TREE_CODE (*node) == FUNCTION_DECL)
8513     DECL_PURE_P (*node) = 1;
8514   /* ??? TODO: Support types.  */
8515   else
8516     {
8517       warning (OPT_Wattributes, "%qE attribute ignored", name);
8518       *no_add_attrs = true;
8519     }
8520
8521   return NULL_TREE;
8522 }
8523
8524 /* Digest an attribute list destined for a transactional memory statement.
8525    ALLOWED is the set of attributes that are allowed for this statement;
8526    return the attribute we parsed.  Multiple attributes are never allowed.  */
8527
8528 int
8529 parse_tm_stmt_attr (tree attrs, int allowed)
8530 {
8531   tree a_seen = NULL;
8532   int m_seen = 0;
8533
8534   for ( ; attrs ; attrs = TREE_CHAIN (attrs))
8535     {
8536       tree a = TREE_PURPOSE (attrs);
8537       int m = 0;
8538
8539       if (is_attribute_p ("outer", a))
8540         m = TM_STMT_ATTR_OUTER;
8541
8542       if ((m & allowed) == 0)
8543         {
8544           warning (OPT_Wattributes, "%qE attribute directive ignored", a);
8545           continue;
8546         }
8547
8548       if (m_seen == 0)
8549         {
8550           a_seen = a;
8551           m_seen = m;
8552         }
8553       else if (m_seen == m)
8554         warning (OPT_Wattributes, "%qE attribute duplicated", a);
8555       else
8556         warning (OPT_Wattributes, "%qE attribute follows %qE", a, a_seen);
8557     }
8558
8559   return m_seen;
8560 }
8561
8562 /* Transform a TM attribute name into a maskable integer and back.
8563    Note that NULL (i.e. no attribute) is mapped to UNKNOWN, corresponding
8564    to how the lack of an attribute is treated.  */
8565
8566 int
8567 tm_attr_to_mask (tree attr)
8568 {
8569   if (attr == NULL)
8570     return 0;
8571   if (is_attribute_p ("transaction_safe", attr))
8572     return TM_ATTR_SAFE;
8573   if (is_attribute_p ("transaction_callable", attr))
8574     return TM_ATTR_CALLABLE;
8575   if (is_attribute_p ("transaction_pure", attr))
8576     return TM_ATTR_PURE;
8577   if (is_attribute_p ("transaction_unsafe", attr))
8578     return TM_ATTR_IRREVOCABLE;
8579   if (is_attribute_p ("transaction_may_cancel_outer", attr))
8580     return TM_ATTR_MAY_CANCEL_OUTER;
8581   return 0;
8582 }
8583
8584 tree
8585 tm_mask_to_attr (int mask)
8586 {
8587   const char *str;
8588   switch (mask)
8589     {
8590     case TM_ATTR_SAFE:
8591       str = "transaction_safe";
8592       break;
8593     case TM_ATTR_CALLABLE:
8594       str = "transaction_callable";
8595       break;
8596     case TM_ATTR_PURE:
8597       str = "transaction_pure";
8598       break;
8599     case TM_ATTR_IRREVOCABLE:
8600       str = "transaction_unsafe";
8601       break;
8602     case TM_ATTR_MAY_CANCEL_OUTER:
8603       str = "transaction_may_cancel_outer";
8604       break;
8605     default:
8606       gcc_unreachable ();
8607     }
8608   return get_identifier (str);
8609 }
8610
8611 /* Return the first TM attribute seen in LIST.  */
8612
8613 tree
8614 find_tm_attribute (tree list)
8615 {
8616   for (; list ; list = TREE_CHAIN (list))
8617     {
8618       tree name = TREE_PURPOSE (list);
8619       if (tm_attr_to_mask (name) != 0)
8620         return name;
8621     }
8622   return NULL_TREE;
8623 }
8624
8625 /* Handle the TM attributes; arguments as in struct attribute_spec.handler.
8626    Here we accept only function types, and verify that none of the other
8627    function TM attributes are also applied.  */
8628 /* ??? We need to accept class types for C++, but not C.  This greatly
8629    complicates this function, since we can no longer rely on the extra
8630    processing given by function_type_required.  */
8631
8632 static tree
8633 handle_tm_attribute (tree *node, tree name, tree args,
8634                      int flags, bool *no_add_attrs)
8635 {
8636   /* Only one path adds the attribute; others don't.  */
8637   *no_add_attrs = true;
8638
8639   switch (TREE_CODE (*node))
8640     {
8641     case RECORD_TYPE:
8642     case UNION_TYPE:
8643       /* Only tm_callable and tm_safe apply to classes.  */
8644       if (tm_attr_to_mask (name) & ~(TM_ATTR_SAFE | TM_ATTR_CALLABLE))
8645         goto ignored;
8646       /* FALLTHRU */
8647
8648     case FUNCTION_TYPE:
8649     case METHOD_TYPE:
8650       {
8651         tree old_name = find_tm_attribute (TYPE_ATTRIBUTES (*node));
8652         if (old_name == name)
8653           ;
8654         else if (old_name != NULL_TREE)
8655           error ("type was previously declared %qE", old_name);
8656         else
8657           *no_add_attrs = false;
8658       }
8659       break;
8660
8661     case POINTER_TYPE:
8662       {
8663         enum tree_code subcode = TREE_CODE (TREE_TYPE (*node));
8664         if (subcode == FUNCTION_TYPE || subcode == METHOD_TYPE)
8665           {
8666             tree fn_tmp = TREE_TYPE (*node);
8667             decl_attributes (&fn_tmp, tree_cons (name, args, NULL), 0);
8668             *node = build_pointer_type (fn_tmp);
8669             break;
8670           }
8671       }
8672       /* FALLTHRU */
8673
8674     default:
8675       /* If a function is next, pass it on to be tried next.  */
8676       if (flags & (int) ATTR_FLAG_FUNCTION_NEXT)
8677         return tree_cons (name, args, NULL);
8678
8679     ignored:
8680       warning (OPT_Wattributes, "%qE attribute ignored", name);
8681       break;
8682     }
8683
8684   return NULL_TREE;
8685 }
8686
8687 /* Handle the TM_WRAP attribute; arguments as in
8688    struct attribute_spec.handler.  */
8689
8690 static tree
8691 handle_tm_wrap_attribute (tree *node, tree name, tree args,
8692                           int ARG_UNUSED (flags), bool *no_add_attrs)
8693 {
8694   tree decl = *node;
8695
8696   /* We don't need the attribute even on success, since we
8697      record the entry in an external table.  */
8698   *no_add_attrs = true;
8699
8700   if (TREE_CODE (decl) != FUNCTION_DECL)
8701     warning (OPT_Wattributes, "%qE attribute ignored", name);
8702   else
8703     {
8704       tree wrap_decl = TREE_VALUE (args);
8705       if (error_operand_p (wrap_decl))
8706         ;
8707       else if (TREE_CODE (wrap_decl) != IDENTIFIER_NODE
8708                && TREE_CODE (wrap_decl) != VAR_DECL
8709                && TREE_CODE (wrap_decl) != FUNCTION_DECL)
8710         error ("%qE argument not an identifier", name);
8711       else
8712         {
8713           if (TREE_CODE (wrap_decl) == IDENTIFIER_NODE)
8714             wrap_decl = lookup_name (wrap_decl);
8715           if (wrap_decl && TREE_CODE (wrap_decl) == FUNCTION_DECL)
8716             {
8717               if (lang_hooks.types_compatible_p (TREE_TYPE (decl),
8718                                                  TREE_TYPE (wrap_decl)))
8719                 record_tm_replacement (wrap_decl, decl);
8720               else
8721                 error ("%qD is not compatible with %qD", wrap_decl, decl);
8722             }
8723           else
8724             error ("%qE argument is not a function", name);
8725         }
8726     }
8727
8728   return NULL_TREE;
8729 }
8730
8731 /* Ignore the given attribute.  Used when this attribute may be usefully
8732    overridden by the target, but is not used generically.  */
8733
8734 static tree
8735 ignore_attribute (tree * ARG_UNUSED (node), tree ARG_UNUSED (name),
8736                   tree ARG_UNUSED (args), int ARG_UNUSED (flags),
8737                   bool *no_add_attrs)
8738 {
8739   *no_add_attrs = true;
8740   return NULL_TREE;
8741 }
8742
8743 /* Handle a "no vops" attribute; arguments as in
8744    struct attribute_spec.handler.  */
8745
8746 static tree
8747 handle_novops_attribute (tree *node, tree ARG_UNUSED (name),
8748                          tree ARG_UNUSED (args), int ARG_UNUSED (flags),
8749                          bool *ARG_UNUSED (no_add_attrs))
8750 {
8751   gcc_assert (TREE_CODE (*node) == FUNCTION_DECL);
8752   DECL_IS_NOVOPS (*node) = 1;
8753   return NULL_TREE;
8754 }
8755
8756 /* Handle a "deprecated" attribute; arguments as in
8757    struct attribute_spec.handler.  */
8758
8759 static tree
8760 handle_deprecated_attribute (tree *node, tree name,
8761                              tree args, int flags,
8762                              bool *no_add_attrs)
8763 {
8764   tree type = NULL_TREE;
8765   int warn = 0;
8766   tree what = NULL_TREE;
8767
8768   if (!args)
8769     *no_add_attrs = true;
8770   else if (TREE_CODE (TREE_VALUE (args)) != STRING_CST)
8771     {
8772       error ("deprecated message is not a string");
8773       *no_add_attrs = true;
8774     }
8775
8776   if (DECL_P (*node))
8777     {
8778       tree decl = *node;
8779       type = TREE_TYPE (decl);
8780
8781       if (TREE_CODE (decl) == TYPE_DECL
8782           || TREE_CODE (decl) == PARM_DECL
8783           || TREE_CODE (decl) == VAR_DECL
8784           || TREE_CODE (decl) == FUNCTION_DECL
8785           || TREE_CODE (decl) == FIELD_DECL
8786           || objc_method_decl (TREE_CODE (decl)))
8787         TREE_DEPRECATED (decl) = 1;
8788       else
8789         warn = 1;
8790     }
8791   else if (TYPE_P (*node))
8792     {
8793       if (!(flags & (int) ATTR_FLAG_TYPE_IN_PLACE))
8794         *node = build_variant_type_copy (*node);
8795       TREE_DEPRECATED (*node) = 1;
8796       type = *node;
8797     }
8798   else
8799     warn = 1;
8800
8801   if (warn)
8802     {
8803       *no_add_attrs = true;
8804       if (type && TYPE_NAME (type))
8805         {
8806           if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE)
8807             what = TYPE_NAME (*node);
8808           else if (TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
8809                    && DECL_NAME (TYPE_NAME (type)))
8810             what = DECL_NAME (TYPE_NAME (type));
8811         }
8812       if (what)
8813         warning (OPT_Wattributes, "%qE attribute ignored for %qE", name, what);
8814       else
8815         warning (OPT_Wattributes, "%qE attribute ignored", name);
8816     }
8817
8818   return NULL_TREE;
8819 }
8820
8821 /* Handle a "vector_size" attribute; arguments as in
8822    struct attribute_spec.handler.  */
8823
8824 static tree
8825 handle_vector_size_attribute (tree *node, tree name, tree args,
8826                               int ARG_UNUSED (flags),
8827                               bool *no_add_attrs)
8828 {
8829   unsigned HOST_WIDE_INT vecsize, nunits;
8830   machine_mode orig_mode;
8831   tree type = *node, new_type, size;
8832
8833   *no_add_attrs = true;
8834
8835   size = TREE_VALUE (args);
8836   if (size && TREE_CODE (size) != IDENTIFIER_NODE
8837       && TREE_CODE (size) != FUNCTION_DECL)
8838     size = default_conversion (size);
8839
8840   if (!tree_fits_uhwi_p (size))
8841     {
8842       warning (OPT_Wattributes, "%qE attribute ignored", name);
8843       return NULL_TREE;
8844     }
8845
8846   /* Get the vector size (in bytes).  */
8847   vecsize = tree_to_uhwi (size);
8848
8849   /* We need to provide for vector pointers, vector arrays, and
8850      functions returning vectors.  For example:
8851
8852        __attribute__((vector_size(16))) short *foo;
8853
8854      In this case, the mode is SI, but the type being modified is
8855      HI, so we need to look further.  */
8856
8857   while (POINTER_TYPE_P (type)
8858          || TREE_CODE (type) == FUNCTION_TYPE
8859          || TREE_CODE (type) == METHOD_TYPE
8860          || TREE_CODE (type) == ARRAY_TYPE
8861          || TREE_CODE (type) == OFFSET_TYPE)
8862     type = TREE_TYPE (type);
8863
8864   /* Get the mode of the type being modified.  */
8865   orig_mode = TYPE_MODE (type);
8866
8867   if ((!INTEGRAL_TYPE_P (type)
8868        && !SCALAR_FLOAT_TYPE_P (type)
8869        && !FIXED_POINT_TYPE_P (type))
8870       || (!SCALAR_FLOAT_MODE_P (orig_mode)
8871           && GET_MODE_CLASS (orig_mode) != MODE_INT
8872           && !ALL_SCALAR_FIXED_POINT_MODE_P (orig_mode))
8873       || !tree_fits_uhwi_p (TYPE_SIZE_UNIT (type))
8874       || TREE_CODE (type) == BOOLEAN_TYPE)
8875     {
8876       error ("invalid vector type for attribute %qE", name);
8877       return NULL_TREE;
8878     }
8879
8880   if (vecsize % tree_to_uhwi (TYPE_SIZE_UNIT (type)))
8881     {
8882       error ("vector size not an integral multiple of component size");
8883       return NULL;
8884     }
8885
8886   if (vecsize == 0)
8887     {
8888       error ("zero vector size");
8889       return NULL;
8890     }
8891
8892   /* Calculate how many units fit in the vector.  */
8893   nunits = vecsize / tree_to_uhwi (TYPE_SIZE_UNIT (type));
8894   if (nunits & (nunits - 1))
8895     {
8896       error ("number of components of the vector not a power of two");
8897       return NULL_TREE;
8898     }
8899
8900   new_type = build_vector_type (type, nunits);
8901
8902   /* Build back pointers if needed.  */
8903   *node = lang_hooks.types.reconstruct_complex_type (*node, new_type);
8904
8905   return NULL_TREE;
8906 }
8907
8908 /* Handle the "nonnull" attribute.  */
8909 static tree
8910 handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name),
8911                           tree args, int ARG_UNUSED (flags),
8912                           bool *no_add_attrs)
8913 {
8914   tree type = *node;
8915   unsigned HOST_WIDE_INT attr_arg_num;
8916
8917   /* If no arguments are specified, all pointer arguments should be
8918      non-null.  Verify a full prototype is given so that the arguments
8919      will have the correct types when we actually check them later.  */
8920   if (!args)
8921     {
8922       if (!prototype_p (type))
8923         {
8924           error ("nonnull attribute without arguments on a non-prototype");
8925           *no_add_attrs = true;
8926         }
8927       return NULL_TREE;
8928     }
8929
8930   /* Argument list specified.  Verify that each argument number references
8931      a pointer argument.  */
8932   for (attr_arg_num = 1; args; attr_arg_num++, args = TREE_CHAIN (args))
8933     {
8934       unsigned HOST_WIDE_INT arg_num = 0, ck_num;
8935
8936       tree arg = TREE_VALUE (args);
8937       if (arg && TREE_CODE (arg) != IDENTIFIER_NODE
8938           && TREE_CODE (arg) != FUNCTION_DECL)
8939         arg = default_conversion (arg);
8940
8941       if (!get_nonnull_operand (arg, &arg_num))
8942         {
8943           error ("nonnull argument has invalid operand number (argument %lu)",
8944                  (unsigned long) attr_arg_num);
8945           *no_add_attrs = true;
8946           return NULL_TREE;
8947         }
8948
8949       if (prototype_p (type))
8950         {
8951           function_args_iterator iter;
8952           tree argument;
8953
8954           function_args_iter_init (&iter, type);
8955           for (ck_num = 1; ; ck_num++, function_args_iter_next (&iter))
8956             {
8957               argument = function_args_iter_cond (&iter);
8958               if (argument == NULL_TREE || ck_num == arg_num)
8959                 break;
8960             }
8961
8962           if (!argument
8963               || TREE_CODE (argument) == VOID_TYPE)
8964             {
8965               error ("nonnull argument with out-of-range operand number (argument %lu, operand %lu)",
8966                      (unsigned long) attr_arg_num, (unsigned long) arg_num);
8967               *no_add_attrs = true;
8968               return NULL_TREE;
8969             }
8970
8971           if (TREE_CODE (argument) != POINTER_TYPE)
8972             {
8973               error ("nonnull argument references non-pointer operand (argument %lu, operand %lu)",
8974                    (unsigned long) attr_arg_num, (unsigned long) arg_num);
8975               *no_add_attrs = true;
8976               return NULL_TREE;
8977             }
8978         }
8979     }
8980
8981   return NULL_TREE;
8982 }
8983
8984 /* Check the argument list of a function call for null in argument slots
8985    that are marked as requiring a non-null pointer argument.  The NARGS
8986    arguments are passed in the array ARGARRAY.
8987 */
8988
8989 static void
8990 check_function_nonnull (tree attrs, int nargs, tree *argarray)
8991 {
8992   tree a;
8993   int i;
8994
8995   attrs = lookup_attribute ("nonnull", attrs);
8996   if (attrs == NULL_TREE)
8997     return;
8998
8999   a = attrs;
9000   /* See if any of the nonnull attributes has no arguments.  If so,
9001      then every pointer argument is checked (in which case the check
9002      for pointer type is done in check_nonnull_arg).  */
9003   if (TREE_VALUE (a) != NULL_TREE)
9004     do
9005       a = lookup_attribute ("nonnull", TREE_CHAIN (a));
9006     while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
9007
9008   if (a != NULL_TREE)
9009     for (i = 0; i < nargs; i++)
9010       check_function_arguments_recurse (check_nonnull_arg, NULL, argarray[i],
9011                                         i + 1);
9012   else
9013     {
9014       /* Walk the argument list.  If we encounter an argument number we
9015          should check for non-null, do it.  */
9016       for (i = 0; i < nargs; i++)
9017         {
9018           for (a = attrs; ; a = TREE_CHAIN (a))
9019             {
9020               a = lookup_attribute ("nonnull", a);
9021               if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
9022                 break;
9023             }
9024
9025           if (a != NULL_TREE)
9026             check_function_arguments_recurse (check_nonnull_arg, NULL,
9027                                               argarray[i], i + 1);
9028         }
9029     }
9030 }
9031
9032 /* Check that the Nth argument of a function call (counting backwards
9033    from the end) is a (pointer)0.  The NARGS arguments are passed in the
9034    array ARGARRAY.  */
9035
9036 static void
9037 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
9038 {
9039   tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
9040
9041   if (attr)
9042     {
9043       int len = 0;
9044       int pos = 0;
9045       tree sentinel;
9046       function_args_iterator iter;
9047       tree t;
9048
9049       /* Skip over the named arguments.  */
9050       FOREACH_FUNCTION_ARGS (fntype, t, iter)
9051         {
9052           if (len == nargs)
9053             break;
9054           len++;
9055         }
9056
9057       if (TREE_VALUE (attr))
9058         {
9059           tree p = TREE_VALUE (TREE_VALUE (attr));
9060           pos = TREE_INT_CST_LOW (p);
9061         }
9062
9063       /* The sentinel must be one of the varargs, i.e.
9064          in position >= the number of fixed arguments.  */
9065       if ((nargs - 1 - pos) < len)
9066         {
9067           warning (OPT_Wformat_,
9068                    "not enough variable arguments to fit a sentinel");
9069           return;
9070         }
9071
9072       /* Validate the sentinel.  */
9073       sentinel = argarray[nargs - 1 - pos];
9074       if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
9075            || !integer_zerop (sentinel))
9076           /* Although __null (in C++) is only an integer we allow it
9077              nevertheless, as we are guaranteed that it's exactly
9078              as wide as a pointer, and we don't want to force
9079              users to cast the NULL they have written there.
9080              We warn with -Wstrict-null-sentinel, though.  */
9081           && (warn_strict_null_sentinel || null_node != sentinel))
9082         warning (OPT_Wformat_, "missing sentinel in function call");
9083     }
9084 }
9085
9086 /* Helper for check_function_nonnull; given a list of operands which
9087    must be non-null in ARGS, determine if operand PARAM_NUM should be
9088    checked.  */
9089
9090 static bool
9091 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
9092 {
9093   unsigned HOST_WIDE_INT arg_num = 0;
9094
9095   for (; args; args = TREE_CHAIN (args))
9096     {
9097       bool found = get_nonnull_operand (TREE_VALUE (args), &arg_num);
9098
9099       gcc_assert (found);
9100
9101       if (arg_num == param_num)
9102         return true;
9103     }
9104   return false;
9105 }
9106
9107 /* Check that the function argument PARAM (which is operand number
9108    PARAM_NUM) is non-null.  This is called by check_function_nonnull
9109    via check_function_arguments_recurse.  */
9110
9111 static void
9112 check_nonnull_arg (void * ARG_UNUSED (ctx), tree param,
9113                    unsigned HOST_WIDE_INT param_num)
9114 {
9115   /* Just skip checking the argument if it's not a pointer.  This can
9116      happen if the "nonnull" attribute was given without an operand
9117      list (which means to check every pointer argument).  */
9118
9119   if (TREE_CODE (TREE_TYPE (param)) != POINTER_TYPE)
9120     return;
9121
9122   if (integer_zerop (param))
9123     warning (OPT_Wnonnull, "null argument where non-null required "
9124              "(argument %lu)", (unsigned long) param_num);
9125 }
9126
9127 /* Helper for nonnull attribute handling; fetch the operand number
9128    from the attribute argument list.  */
9129
9130 static bool
9131 get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
9132 {
9133   /* Verify the arg number is a small constant.  */
9134   if (tree_fits_uhwi_p (arg_num_expr))
9135     {
9136       *valp = TREE_INT_CST_LOW (arg_num_expr);
9137       return true;
9138     }
9139   else
9140     return false;
9141 }
9142
9143 /* Handle a "nothrow" attribute; arguments as in
9144    struct attribute_spec.handler.  */
9145
9146 static tree
9147 handle_nothrow_attribute (tree *node, tree name, tree ARG_UNUSED (args),
9148                           int ARG_UNUSED (flags), bool *no_add_attrs)
9149 {
9150   if (TREE_CODE (*node) == FUNCTION_DECL)
9151     TREE_NOTHROW (*node) = 1;
9152   /* ??? TODO: Support types.  */
9153   else
9154     {
9155       warning (OPT_Wattributes, "%qE attribute ignored", name);
9156       *no_add_attrs = true;
9157     }
9158
9159   return NULL_TREE;
9160 }
9161
9162 /* Handle a "cleanup" attribute; arguments as in
9163    struct attribute_spec.handler.  */
9164
9165 static tree
9166 handle_cleanup_attribute (tree *node, tree name, tree args,
9167                           int ARG_UNUSED (flags), bool *no_add_attrs)
9168 {
9169   tree decl = *node;
9170   tree cleanup_id, cleanup_decl;
9171
9172   /* ??? Could perhaps support cleanups on TREE_STATIC, much like we do
9173      for global destructors in C++.  This requires infrastructure that
9174      we don't have generically at the moment.  It's also not a feature
9175      we'd be missing too much, since we do have attribute constructor.  */
9176   if (TREE_CODE (decl) != VAR_DECL || TREE_STATIC (decl))
9177     {
9178       warning (OPT_Wattributes, "%qE attribute ignored", name);
9179       *no_add_attrs = true;
9180       return NULL_TREE;
9181     }
9182
9183   /* Verify that the argument is a function in scope.  */
9184   /* ??? We could support pointers to functions here as well, if
9185      that was considered desirable.  */
9186   cleanup_id = TREE_VALUE (args);
9187   if (TREE_CODE (cleanup_id) != IDENTIFIER_NODE)
9188     {
9189       error ("cleanup argument not an identifier");
9190       *no_add_attrs = true;
9191       return NULL_TREE;
9192     }
9193   cleanup_decl = lookup_name (cleanup_id);
9194   if (!cleanup_decl || TREE_CODE (cleanup_decl) != FUNCTION_DECL)
9195     {
9196       error ("cleanup argument not a function");
9197       *no_add_attrs = true;
9198       return NULL_TREE;
9199     }
9200
9201   /* That the function has proper type is checked with the
9202      eventual call to build_function_call.  */
9203
9204   return NULL_TREE;
9205 }
9206
9207 /* Handle a "warn_unused_result" attribute.  No special handling.  */
9208
9209 static tree
9210 handle_warn_unused_result_attribute (tree *node, tree name,
9211                                tree ARG_UNUSED (args),
9212                                int ARG_UNUSED (flags), bool *no_add_attrs)
9213 {
9214   /* Ignore the attribute for functions not returning any value.  */
9215   if (VOID_TYPE_P (TREE_TYPE (*node)))
9216     {
9217       warning (OPT_Wattributes, "%qE attribute ignored", name);
9218       *no_add_attrs = true;
9219     }
9220
9221   return NULL_TREE;
9222 }
9223
9224 /* Handle a "sentinel" attribute.  */
9225
9226 static tree
9227 handle_sentinel_attribute (tree *node, tree name, tree args,
9228                            int ARG_UNUSED (flags), bool *no_add_attrs)
9229 {
9230   if (!prototype_p (*node))
9231     {
9232       warning (OPT_Wattributes,
9233                "%qE attribute requires prototypes with named arguments", name);
9234       *no_add_attrs = true;
9235     }
9236   else
9237     {
9238       if (!stdarg_p (*node))
9239         {
9240           warning (OPT_Wattributes,
9241                    "%qE attribute only applies to variadic functions", name);
9242           *no_add_attrs = true;
9243         }
9244     }
9245
9246   if (args)
9247     {
9248       tree position = TREE_VALUE (args);
9249       if (position && TREE_CODE (position) != IDENTIFIER_NODE
9250           && TREE_CODE (position) != FUNCTION_DECL)
9251         position = default_conversion (position);
9252
9253       if (TREE_CODE (position) != INTEGER_CST
9254           || !INTEGRAL_TYPE_P (TREE_TYPE (position)))
9255         {
9256           warning (OPT_Wattributes,
9257                    "requested position is not an integer constant");
9258           *no_add_attrs = true;
9259         }
9260       else
9261         {
9262           if (tree_int_cst_lt (position, integer_zero_node))
9263             {
9264               warning (OPT_Wattributes,
9265                        "requested position is less than zero");
9266               *no_add_attrs = true;
9267             }
9268         }
9269     }
9270
9271   return NULL_TREE;
9272 }
9273
9274 /* Handle a "type_generic" attribute.  */
9275
9276 static tree
9277 handle_type_generic_attribute (tree *node, tree ARG_UNUSED (name),
9278                                tree ARG_UNUSED (args), int ARG_UNUSED (flags),
9279                                bool * ARG_UNUSED (no_add_attrs))
9280 {
9281   /* Ensure we have a function type.  */
9282   gcc_assert (TREE_CODE (*node) == FUNCTION_TYPE);
9283
9284   /* Ensure we have a variadic function.  */
9285   gcc_assert (!prototype_p (*node) || stdarg_p (*node));
9286
9287   return NULL_TREE;
9288 }
9289
9290 /* Handle a "target" attribute.  */
9291
9292 static tree
9293 handle_target_attribute (tree *node, tree name, tree args, int flags,
9294                          bool *no_add_attrs)
9295 {
9296   /* Ensure we have a function type.  */
9297   if (TREE_CODE (*node) != FUNCTION_DECL)
9298     {
9299       warning (OPT_Wattributes, "%qE attribute ignored", name);
9300       *no_add_attrs = true;
9301     }
9302   else if (! targetm.target_option.valid_attribute_p (*node, name, args,
9303                                                       flags))
9304     *no_add_attrs = true;
9305
9306   return NULL_TREE;
9307 }
9308
9309 /* Arguments being collected for optimization.  */
9310 typedef const char *const_char_p;               /* For DEF_VEC_P.  */
9311 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
9312
9313
9314 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
9315    options in ARGS.  ATTR_P is true if this is for attribute(optimize), and
9316    false for #pragma GCC optimize.  */
9317
9318 bool
9319 parse_optimize_options (tree args, bool attr_p)
9320 {
9321   bool ret = true;
9322   unsigned opt_argc;
9323   unsigned i;
9324   int saved_flag_strict_aliasing;
9325   const char **opt_argv;
9326   struct cl_decoded_option *decoded_options;
9327   unsigned int decoded_options_count;
9328   tree ap;
9329
9330   /* Build up argv vector.  Just in case the string is stored away, use garbage
9331      collected strings.  */
9332   vec_safe_truncate (optimize_args, 0);
9333   vec_safe_push (optimize_args, (const char *) NULL);
9334
9335   for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
9336     {
9337       tree value = TREE_VALUE (ap);
9338
9339       if (TREE_CODE (value) == INTEGER_CST)
9340         {
9341           char buffer[20];
9342           sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
9343           vec_safe_push (optimize_args, ggc_strdup (buffer));
9344         }
9345
9346       else if (TREE_CODE (value) == STRING_CST)
9347         {
9348           /* Split string into multiple substrings.  */
9349           size_t len = TREE_STRING_LENGTH (value);
9350           char *p = ASTRDUP (TREE_STRING_POINTER (value));
9351           char *end = p + len;
9352           char *comma;
9353           char *next_p = p;
9354
9355           while (next_p != NULL)
9356             {
9357               size_t len2;
9358               char *q, *r;
9359
9360               p = next_p;
9361               comma = strchr (p, ',');
9362               if (comma)
9363                 {
9364                   len2 = comma - p;
9365                   *comma = '\0';
9366                   next_p = comma+1;
9367                 }
9368               else
9369                 {
9370                   len2 = end - p;
9371                   next_p = NULL;
9372                 }
9373
9374               r = q = (char *) ggc_alloc_atomic (len2 + 3);
9375
9376               /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
9377                  options.  */
9378               if (*p == '-' && p[1] != 'O' && p[1] != 'f')
9379                 {
9380                   ret = false;
9381                   if (attr_p)
9382                     warning (OPT_Wattributes,
9383                              "bad option %s to optimize attribute", p);
9384                   else
9385                     warning (OPT_Wpragmas,
9386                              "bad option %s to pragma attribute", p);
9387                   continue;
9388                 }
9389
9390               if (*p != '-')
9391                 {
9392                   *r++ = '-';
9393
9394                   /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
9395                      itself is -Os, and any other switch begins with a -f.  */
9396                   if ((*p >= '0' && *p <= '9')
9397                       || (p[0] == 's' && p[1] == '\0'))
9398                     *r++ = 'O';
9399                   else if (*p != 'O')
9400                     *r++ = 'f';
9401                 }
9402
9403               memcpy (r, p, len2);
9404               r[len2] = '\0';
9405               vec_safe_push (optimize_args, (const char *) q);
9406             }
9407
9408         }
9409     }
9410
9411   opt_argc = optimize_args->length ();
9412   opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
9413
9414   for (i = 1; i < opt_argc; i++)
9415     opt_argv[i] = (*optimize_args)[i];
9416
9417   saved_flag_strict_aliasing = flag_strict_aliasing;
9418
9419   /* Now parse the options.  */
9420   decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
9421                                                 &decoded_options,
9422                                                 &decoded_options_count);
9423   decode_options (&global_options, &global_options_set,
9424                   decoded_options, decoded_options_count,
9425                   input_location, global_dc);
9426
9427   targetm.override_options_after_change();
9428
9429   /* Don't allow changing -fstrict-aliasing.  */
9430   flag_strict_aliasing = saved_flag_strict_aliasing;
9431
9432   optimize_args->truncate (0);
9433   return ret;
9434 }
9435
9436 /* For handling "optimize" attribute. arguments as in
9437    struct attribute_spec.handler.  */
9438
9439 static tree
9440 handle_optimize_attribute (tree *node, tree name, tree args,
9441                            int ARG_UNUSED (flags), bool *no_add_attrs)
9442 {
9443   /* Ensure we have a function type.  */
9444   if (TREE_CODE (*node) != FUNCTION_DECL)
9445     {
9446       warning (OPT_Wattributes, "%qE attribute ignored", name);
9447       *no_add_attrs = true;
9448     }
9449   else
9450     {
9451       struct cl_optimization cur_opts;
9452       tree old_opts = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (*node);
9453
9454       /* Save current options.  */
9455       cl_optimization_save (&cur_opts, &global_options);
9456
9457       /* If we previously had some optimization options, use them as the
9458          default.  */
9459       if (old_opts)
9460         cl_optimization_restore (&global_options,
9461                                  TREE_OPTIMIZATION (old_opts));
9462
9463       /* Parse options, and update the vector.  */
9464       parse_optimize_options (args, true);
9465       DECL_FUNCTION_SPECIFIC_OPTIMIZATION (*node)
9466         = build_optimization_node (&global_options);
9467
9468       /* Restore current options.  */
9469       cl_optimization_restore (&global_options, &cur_opts);
9470     }
9471
9472   return NULL_TREE;
9473 }
9474
9475 /* Handle a "no_split_stack" attribute.  */
9476
9477 static tree
9478 handle_no_split_stack_attribute (tree *node, tree name,
9479                                  tree ARG_UNUSED (args),
9480                                  int ARG_UNUSED (flags),
9481                                  bool *no_add_attrs)
9482 {
9483   tree decl = *node;
9484
9485   if (TREE_CODE (decl) != FUNCTION_DECL)
9486     {
9487       error_at (DECL_SOURCE_LOCATION (decl),
9488                 "%qE attribute applies only to functions", name);
9489       *no_add_attrs = true;
9490     }
9491   else if (DECL_INITIAL (decl))
9492     {
9493       error_at (DECL_SOURCE_LOCATION (decl),
9494                 "can%'t set %qE attribute after definition", name);
9495       *no_add_attrs = true;
9496     }
9497
9498   return NULL_TREE;
9499 }
9500
9501 /* Handle a "returns_nonnull" attribute; arguments as in
9502    struct attribute_spec.handler.  */
9503
9504 static tree
9505 handle_returns_nonnull_attribute (tree *node, tree, tree, int,
9506                                   bool *no_add_attrs)
9507 {
9508   // Even without a prototype we still have a return type we can check.
9509   if (TREE_CODE (TREE_TYPE (*node)) != POINTER_TYPE)
9510     {
9511       error ("returns_nonnull attribute on a function not returning a pointer");
9512       *no_add_attrs = true;
9513     }
9514   return NULL_TREE;
9515 }
9516
9517 /* Handle a "designated_init" attribute; arguments as in
9518    struct attribute_spec.handler.  */
9519
9520 static tree
9521 handle_designated_init_attribute (tree *node, tree name, tree, int,
9522                                   bool *no_add_attrs)
9523 {
9524   if (TREE_CODE (*node) != RECORD_TYPE)
9525     {
9526       error ("%qE attribute is only valid on %<struct%> type", name);
9527       *no_add_attrs = true;
9528     }
9529   return NULL_TREE;
9530 }
9531
9532 \f
9533 /* Check for valid arguments being passed to a function with FNTYPE.
9534    There are NARGS arguments in the array ARGARRAY.  */
9535 void
9536 check_function_arguments (const_tree fntype, int nargs, tree *argarray)
9537 {
9538   /* Check for null being passed in a pointer argument that must be
9539      non-null.  We also need to do this if format checking is enabled.  */
9540
9541   if (warn_nonnull)
9542     check_function_nonnull (TYPE_ATTRIBUTES (fntype), nargs, argarray);
9543
9544   /* Check for errors in format strings.  */
9545
9546   if (warn_format || warn_suggest_attribute_format)
9547     check_function_format (TYPE_ATTRIBUTES (fntype), nargs, argarray);
9548
9549   if (warn_format)
9550     check_function_sentinel (fntype, nargs, argarray);
9551 }
9552
9553 /* Generic argument checking recursion routine.  PARAM is the argument to
9554    be checked.  PARAM_NUM is the number of the argument.  CALLBACK is invoked
9555    once the argument is resolved.  CTX is context for the callback.  */
9556 void
9557 check_function_arguments_recurse (void (*callback)
9558                                   (void *, tree, unsigned HOST_WIDE_INT),
9559                                   void *ctx, tree param,
9560                                   unsigned HOST_WIDE_INT param_num)
9561 {
9562   if (CONVERT_EXPR_P (param)
9563       && (TYPE_PRECISION (TREE_TYPE (param))
9564           == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
9565     {
9566       /* Strip coercion.  */
9567       check_function_arguments_recurse (callback, ctx,
9568                                         TREE_OPERAND (param, 0), param_num);
9569       return;
9570     }
9571
9572   if (TREE_CODE (param) == CALL_EXPR)
9573     {
9574       tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
9575       tree attrs;
9576       bool found_format_arg = false;
9577
9578       /* See if this is a call to a known internationalization function
9579          that modifies a format arg.  Such a function may have multiple
9580          format_arg attributes (for example, ngettext).  */
9581
9582       for (attrs = TYPE_ATTRIBUTES (type);
9583            attrs;
9584            attrs = TREE_CHAIN (attrs))
9585         if (is_attribute_p ("format_arg", TREE_PURPOSE (attrs)))
9586           {
9587             tree inner_arg;
9588             tree format_num_expr;
9589             int format_num;
9590             int i;
9591             call_expr_arg_iterator iter;
9592
9593             /* Extract the argument number, which was previously checked
9594                to be valid.  */
9595             format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
9596
9597             format_num = tree_to_uhwi (format_num_expr);
9598
9599             for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
9600                  inner_arg != 0;
9601                  inner_arg = next_call_expr_arg (&iter), i++)
9602               if (i == format_num)
9603                 {
9604                   check_function_arguments_recurse (callback, ctx,
9605                                                     inner_arg, param_num);
9606                   found_format_arg = true;
9607                   break;
9608                 }
9609           }
9610
9611       /* If we found a format_arg attribute and did a recursive check,
9612          we are done with checking this argument.  Otherwise, we continue
9613          and this will be considered a non-literal.  */
9614       if (found_format_arg)
9615         return;
9616     }
9617
9618   if (TREE_CODE (param) == COND_EXPR)
9619     {
9620       /* Check both halves of the conditional expression.  */
9621       check_function_arguments_recurse (callback, ctx,
9622                                         TREE_OPERAND (param, 1), param_num);
9623       check_function_arguments_recurse (callback, ctx,
9624                                         TREE_OPERAND (param, 2), param_num);
9625       return;
9626     }
9627
9628   (*callback) (ctx, param, param_num);
9629 }
9630
9631 /* Checks for a builtin function FNDECL that the number of arguments
9632    NARGS against the required number REQUIRED and issues an error if
9633    there is a mismatch.  Returns true if the number of arguments is
9634    correct, otherwise false.  */
9635
9636 static bool
9637 builtin_function_validate_nargs (tree fndecl, int nargs, int required)
9638 {
9639   if (nargs < required)
9640     {
9641       error_at (input_location,
9642                 "not enough arguments to function %qE", fndecl);
9643       return false;
9644     }
9645   else if (nargs > required)
9646     {
9647       error_at (input_location,
9648                 "too many arguments to function %qE", fndecl);
9649       return false;
9650     }
9651   return true;
9652 }
9653
9654 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
9655    Returns false if there was an error, otherwise true.  */
9656
9657 bool
9658 check_builtin_function_arguments (tree fndecl, int nargs, tree *args)
9659 {
9660   if (!DECL_BUILT_IN (fndecl)
9661       || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
9662     return true;
9663
9664   switch (DECL_FUNCTION_CODE (fndecl))
9665     {
9666     case BUILT_IN_CONSTANT_P:
9667       return builtin_function_validate_nargs (fndecl, nargs, 1);
9668
9669     case BUILT_IN_ISFINITE:
9670     case BUILT_IN_ISINF:
9671     case BUILT_IN_ISINF_SIGN:
9672     case BUILT_IN_ISNAN:
9673     case BUILT_IN_ISNORMAL:
9674       if (builtin_function_validate_nargs (fndecl, nargs, 1))
9675         {
9676           if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
9677             {
9678               error ("non-floating-point argument in call to "
9679                      "function %qE", fndecl);
9680               return false;
9681             }
9682           return true;
9683         }
9684       return false;
9685
9686     case BUILT_IN_ISGREATER:
9687     case BUILT_IN_ISGREATEREQUAL:
9688     case BUILT_IN_ISLESS:
9689     case BUILT_IN_ISLESSEQUAL:
9690     case BUILT_IN_ISLESSGREATER:
9691     case BUILT_IN_ISUNORDERED:
9692       if (builtin_function_validate_nargs (fndecl, nargs, 2))
9693         {
9694           enum tree_code code0, code1;
9695           code0 = TREE_CODE (TREE_TYPE (args[0]));
9696           code1 = TREE_CODE (TREE_TYPE (args[1]));
9697           if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
9698                 || (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9699                 || (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
9700             {
9701               error ("non-floating-point arguments in call to "
9702                      "function %qE", fndecl);
9703               return false;
9704             }
9705           return true;
9706         }
9707       return false;
9708
9709     case BUILT_IN_FPCLASSIFY:
9710       if (builtin_function_validate_nargs (fndecl, nargs, 6))
9711         {
9712           unsigned i;
9713
9714           for (i=0; i<5; i++)
9715             if (TREE_CODE (args[i]) != INTEGER_CST)
9716               {
9717                 error ("non-const integer argument %u in call to function %qE",
9718                        i+1, fndecl);
9719                 return false;
9720               }
9721
9722           if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
9723             {
9724               error ("non-floating-point argument in call to function %qE",
9725                      fndecl);
9726               return false;
9727             }
9728           return true;
9729         }
9730       return false;
9731
9732     case BUILT_IN_ASSUME_ALIGNED:
9733       if (builtin_function_validate_nargs (fndecl, nargs, 2 + (nargs > 2)))
9734         {
9735           if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
9736             {
9737               error ("non-integer argument 3 in call to function %qE", fndecl);
9738               return false;
9739             }
9740           return true;
9741         }
9742       return false;
9743
9744     case BUILT_IN_ADD_OVERFLOW:
9745     case BUILT_IN_SUB_OVERFLOW:
9746     case BUILT_IN_MUL_OVERFLOW:
9747       if (builtin_function_validate_nargs (fndecl, nargs, 3))
9748         {
9749           unsigned i;
9750           for (i = 0; i < 2; i++)
9751             if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
9752               {
9753                 error ("argument %u in call to function %qE does not have "
9754                        "integral type", i + 1, fndecl);
9755                 return false;
9756               }
9757           if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
9758               || TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) != INTEGER_TYPE)
9759             {
9760               error ("argument 3 in call to function %qE does not have "
9761                      "pointer to integer type", fndecl);
9762               return false;
9763             }
9764           return true;
9765         }
9766       return false;
9767
9768     default:
9769       return true;
9770     }
9771 }
9772
9773 /* Function to help qsort sort FIELD_DECLs by name order.  */
9774
9775 int
9776 field_decl_cmp (const void *x_p, const void *y_p)
9777 {
9778   const tree *const x = (const tree *const) x_p;
9779   const tree *const y = (const tree *const) y_p;
9780
9781   if (DECL_NAME (*x) == DECL_NAME (*y))
9782     /* A nontype is "greater" than a type.  */
9783     return (TREE_CODE (*y) == TYPE_DECL) - (TREE_CODE (*x) == TYPE_DECL);
9784   if (DECL_NAME (*x) == NULL_TREE)
9785     return -1;
9786   if (DECL_NAME (*y) == NULL_TREE)
9787     return 1;
9788   if (DECL_NAME (*x) < DECL_NAME (*y))
9789     return -1;
9790   return 1;
9791 }
9792
9793 static struct {
9794   gt_pointer_operator new_value;
9795   void *cookie;
9796 } resort_data;
9797
9798 /* This routine compares two fields like field_decl_cmp but using the
9799 pointer operator in resort_data.  */
9800
9801 static int
9802 resort_field_decl_cmp (const void *x_p, const void *y_p)
9803 {
9804   const tree *const x = (const tree *const) x_p;
9805   const tree *const y = (const tree *const) y_p;
9806
9807   if (DECL_NAME (*x) == DECL_NAME (*y))
9808     /* A nontype is "greater" than a type.  */
9809     return (TREE_CODE (*y) == TYPE_DECL) - (TREE_CODE (*x) == TYPE_DECL);
9810   if (DECL_NAME (*x) == NULL_TREE)
9811     return -1;
9812   if (DECL_NAME (*y) == NULL_TREE)
9813     return 1;
9814   {
9815     tree d1 = DECL_NAME (*x);
9816     tree d2 = DECL_NAME (*y);
9817     resort_data.new_value (&d1, resort_data.cookie);
9818     resort_data.new_value (&d2, resort_data.cookie);
9819     if (d1 < d2)
9820       return -1;
9821   }
9822   return 1;
9823 }
9824
9825 /* Resort DECL_SORTED_FIELDS because pointers have been reordered.  */
9826
9827 void
9828 resort_sorted_fields (void *obj,
9829                       void * ARG_UNUSED (orig_obj),
9830                       gt_pointer_operator new_value,
9831                       void *cookie)
9832 {
9833   struct sorted_fields_type *sf = (struct sorted_fields_type *) obj;
9834   resort_data.new_value = new_value;
9835   resort_data.cookie = cookie;
9836   qsort (&sf->elts[0], sf->len, sizeof (tree),
9837          resort_field_decl_cmp);
9838 }
9839
9840 /* Subroutine of c_parse_error.
9841    Return the result of concatenating LHS and RHS. RHS is really
9842    a string literal, its first character is indicated by RHS_START and
9843    RHS_SIZE is its length (including the terminating NUL character).
9844
9845    The caller is responsible for deleting the returned pointer.  */
9846
9847 static char *
9848 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
9849 {
9850   const int lhs_size = strlen (lhs);
9851   char *result = XNEWVEC (char, lhs_size + rhs_size);
9852   strncpy (result, lhs, lhs_size);
9853   strncpy (result + lhs_size, rhs_start, rhs_size);
9854   return result;
9855 }
9856
9857 /* Issue the error given by GMSGID, indicating that it occurred before
9858    TOKEN, which had the associated VALUE.  */
9859
9860 void
9861 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
9862                tree value, unsigned char token_flags)
9863 {
9864 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
9865
9866   char *message = NULL;
9867
9868   if (token_type == CPP_EOF)
9869     message = catenate_messages (gmsgid, " at end of input");
9870   else if (token_type == CPP_CHAR
9871            || token_type == CPP_WCHAR
9872            || token_type == CPP_CHAR16
9873            || token_type == CPP_CHAR32)
9874     {
9875       unsigned int val = TREE_INT_CST_LOW (value);
9876       const char *prefix;
9877
9878       switch (token_type)
9879         {
9880         default:
9881           prefix = "";
9882           break;
9883         case CPP_WCHAR:
9884           prefix = "L";
9885           break;
9886         case CPP_CHAR16:
9887           prefix = "u";
9888           break;
9889         case CPP_CHAR32:
9890           prefix = "U";
9891           break;
9892         }
9893
9894       if (val <= UCHAR_MAX && ISGRAPH (val))
9895         message = catenate_messages (gmsgid, " before %s'%c'");
9896       else
9897         message = catenate_messages (gmsgid, " before %s'\\x%x'");
9898
9899       error (message, prefix, val);
9900       free (message);
9901       message = NULL;
9902     }
9903   else if (token_type == CPP_CHAR_USERDEF
9904            || token_type == CPP_WCHAR_USERDEF
9905            || token_type == CPP_CHAR16_USERDEF
9906            || token_type == CPP_CHAR32_USERDEF)
9907     message = catenate_messages (gmsgid,
9908                                  " before user-defined character literal");
9909   else if (token_type == CPP_STRING_USERDEF
9910            || token_type == CPP_WSTRING_USERDEF
9911            || token_type == CPP_STRING16_USERDEF
9912            || token_type == CPP_STRING32_USERDEF
9913            || token_type == CPP_UTF8STRING_USERDEF)
9914     message = catenate_messages (gmsgid, " before user-defined string literal");
9915   else if (token_type == CPP_STRING
9916            || token_type == CPP_WSTRING
9917            || token_type == CPP_STRING16
9918            || token_type == CPP_STRING32
9919            || token_type == CPP_UTF8STRING)
9920     message = catenate_messages (gmsgid, " before string constant");
9921   else if (token_type == CPP_NUMBER)
9922     message = catenate_messages (gmsgid, " before numeric constant");
9923   else if (token_type == CPP_NAME)
9924     {
9925       message = catenate_messages (gmsgid, " before %qE");
9926       error (message, value);
9927       free (message);
9928       message = NULL;
9929     }
9930   else if (token_type == CPP_PRAGMA)
9931     message = catenate_messages (gmsgid, " before %<#pragma%>");
9932   else if (token_type == CPP_PRAGMA_EOL)
9933     message = catenate_messages (gmsgid, " before end of line");
9934   else if (token_type == CPP_DECLTYPE)
9935     message = catenate_messages (gmsgid, " before %<decltype%>");
9936   else if (token_type < N_TTYPES)
9937     {
9938       message = catenate_messages (gmsgid, " before %qs token");
9939       error (message, cpp_type2name (token_type, token_flags));
9940       free (message);
9941       message = NULL;
9942     }
9943   else
9944     error (gmsgid);
9945
9946   if (message)
9947     {
9948       error (message);
9949       free (message);
9950     }
9951 #undef catenate_messages
9952 }
9953
9954 /* Return the gcc option code associated with the reason for a cpp
9955    message, or 0 if none.  */
9956
9957 static int
9958 c_option_controlling_cpp_error (int reason)
9959 {
9960   const struct cpp_reason_option_codes_t *entry;
9961
9962   for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
9963     {
9964       if (entry->reason == reason)
9965         return entry->option_code;
9966     }
9967   return 0;
9968 }
9969
9970 /* Callback from cpp_error for PFILE to print diagnostics from the
9971    preprocessor.  The diagnostic is of type LEVEL, with REASON set
9972    to the reason code if LEVEL is represents a warning, at location
9973    LOCATION unless this is after lexing and the compiler's location
9974    should be used instead, with column number possibly overridden by
9975    COLUMN_OVERRIDE if not zero; MSG is the translated message and AP
9976    the arguments.  Returns true if a diagnostic was emitted, false
9977    otherwise.  */
9978
9979 bool
9980 c_cpp_error (cpp_reader *pfile ATTRIBUTE_UNUSED, int level, int reason,
9981              location_t location, unsigned int column_override,
9982              const char *msg, va_list *ap)
9983 {
9984   diagnostic_info diagnostic;
9985   diagnostic_t dlevel;
9986   bool save_warn_system_headers = global_dc->dc_warn_system_headers;
9987   bool ret;
9988
9989   switch (level)
9990     {
9991     case CPP_DL_WARNING_SYSHDR:
9992       if (flag_no_output)
9993         return false;
9994       global_dc->dc_warn_system_headers = 1;
9995       /* Fall through.  */
9996     case CPP_DL_WARNING:
9997       if (flag_no_output)
9998         return false;
9999       dlevel = DK_WARNING;
10000       break;
10001     case CPP_DL_PEDWARN:
10002       if (flag_no_output && !flag_pedantic_errors)
10003         return false;
10004       dlevel = DK_PEDWARN;
10005       break;
10006     case CPP_DL_ERROR:
10007       dlevel = DK_ERROR;
10008       break;
10009     case CPP_DL_ICE:
10010       dlevel = DK_ICE;
10011       break;
10012     case CPP_DL_NOTE:
10013       dlevel = DK_NOTE;
10014       break;
10015     case CPP_DL_FATAL:
10016       dlevel = DK_FATAL;
10017       break;
10018     default:
10019       gcc_unreachable ();
10020     }
10021   if (done_lexing)
10022     location = input_location;
10023   diagnostic_set_info_translated (&diagnostic, msg, ap,
10024                                   location, dlevel);
10025   if (column_override)
10026     diagnostic_override_column (&diagnostic, column_override);
10027   diagnostic_override_option_index (&diagnostic,
10028                                     c_option_controlling_cpp_error (reason));
10029   ret = report_diagnostic (&diagnostic);
10030   if (level == CPP_DL_WARNING_SYSHDR)
10031     global_dc->dc_warn_system_headers = save_warn_system_headers;
10032   return ret;
10033 }
10034
10035 /* Convert a character from the host to the target execution character
10036    set.  cpplib handles this, mostly.  */
10037
10038 HOST_WIDE_INT
10039 c_common_to_target_charset (HOST_WIDE_INT c)
10040 {
10041   /* Character constants in GCC proper are sign-extended under -fsigned-char,
10042      zero-extended under -fno-signed-char.  cpplib insists that characters
10043      and character constants are always unsigned.  Hence we must convert
10044      back and forth.  */
10045   cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
10046
10047   uc = cpp_host_to_exec_charset (parse_in, uc);
10048
10049   if (flag_signed_char)
10050     return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
10051                                >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
10052   else
10053     return uc;
10054 }
10055
10056 /* Fold an offsetof-like expression.  EXPR is a nested sequence of component
10057    references with an INDIRECT_REF of a constant at the bottom; much like the
10058    traditional rendering of offsetof as a macro.  Return the folded result.  */
10059
10060 tree
10061 fold_offsetof_1 (tree expr)
10062 {
10063   tree base, off, t;
10064
10065   switch (TREE_CODE (expr))
10066     {
10067     case ERROR_MARK:
10068       return expr;
10069
10070     case VAR_DECL:
10071       error ("cannot apply %<offsetof%> to static data member %qD", expr);
10072       return error_mark_node;
10073
10074     case CALL_EXPR:
10075     case TARGET_EXPR:
10076       error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
10077       return error_mark_node;
10078
10079     case NOP_EXPR:
10080     case INDIRECT_REF:
10081       if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
10082         {
10083           error ("cannot apply %<offsetof%> to a non constant address");
10084           return error_mark_node;
10085         }
10086       return TREE_OPERAND (expr, 0);
10087
10088     case COMPONENT_REF:
10089       base = fold_offsetof_1 (TREE_OPERAND (expr, 0));
10090       if (base == error_mark_node)
10091         return base;
10092
10093       t = TREE_OPERAND (expr, 1);
10094       if (DECL_C_BIT_FIELD (t))
10095         {
10096           error ("attempt to take address of bit-field structure "
10097                  "member %qD", t);
10098           return error_mark_node;
10099         }
10100       off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
10101                             size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
10102                                       / BITS_PER_UNIT));
10103       break;
10104
10105     case ARRAY_REF:
10106       base = fold_offsetof_1 (TREE_OPERAND (expr, 0));
10107       if (base == error_mark_node)
10108         return base;
10109
10110       t = TREE_OPERAND (expr, 1);
10111
10112       /* Check if the offset goes beyond the upper bound of the array.  */
10113       if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
10114         {
10115           tree upbound = array_ref_up_bound (expr);
10116           if (upbound != NULL_TREE
10117               && TREE_CODE (upbound) == INTEGER_CST
10118               && !tree_int_cst_equal (upbound,
10119                                       TYPE_MAX_VALUE (TREE_TYPE (upbound))))
10120             {
10121               upbound = size_binop (PLUS_EXPR, upbound,
10122                                     build_int_cst (TREE_TYPE (upbound), 1));
10123               if (tree_int_cst_lt (upbound, t))
10124                 {
10125                   tree v;
10126
10127                   for (v = TREE_OPERAND (expr, 0);
10128                        TREE_CODE (v) == COMPONENT_REF;
10129                        v = TREE_OPERAND (v, 0))
10130                     if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
10131                         == RECORD_TYPE)
10132                       {
10133                         tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
10134                         for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
10135                           if (TREE_CODE (fld_chain) == FIELD_DECL)
10136                             break;
10137
10138                         if (fld_chain)
10139                           break;
10140                       }
10141                   /* Don't warn if the array might be considered a poor
10142                      man's flexible array member with a very permissive
10143                      definition thereof.  */
10144                   if (TREE_CODE (v) == ARRAY_REF
10145                       || TREE_CODE (v) == COMPONENT_REF)
10146                     warning (OPT_Warray_bounds,
10147                              "index %E denotes an offset "
10148                              "greater than size of %qT",
10149                              t, TREE_TYPE (TREE_OPERAND (expr, 0)));
10150                 }
10151             }
10152         }
10153
10154       t = convert (sizetype, t);
10155       off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
10156       break;
10157
10158     case COMPOUND_EXPR:
10159       /* Handle static members of volatile structs.  */
10160       t = TREE_OPERAND (expr, 1);
10161       gcc_assert (TREE_CODE (t) == VAR_DECL);
10162       return fold_offsetof_1 (t);
10163
10164     default:
10165       gcc_unreachable ();
10166     }
10167
10168   return fold_build_pointer_plus (base, off);
10169 }
10170
10171 /* Likewise, but convert it to the return type of offsetof.  */
10172
10173 tree
10174 fold_offsetof (tree expr)
10175 {
10176   return convert (size_type_node, fold_offsetof_1 (expr));
10177 }
10178
10179 /* Warn for A ?: C expressions (with B omitted) where A is a boolean 
10180    expression, because B will always be true. */
10181
10182 void
10183 warn_for_omitted_condop (location_t location, tree cond) 
10184
10185   if (truth_value_p (TREE_CODE (cond))) 
10186       warning_at (location, OPT_Wparentheses, 
10187                 "the omitted middle operand in ?: will always be %<true%>, "
10188                 "suggest explicit middle operand");
10189
10190
10191 /* Give an error for storing into ARG, which is 'const'.  USE indicates
10192    how ARG was being used.  */
10193
10194 void
10195 readonly_error (location_t loc, tree arg, enum lvalue_use use)
10196 {
10197   gcc_assert (use == lv_assign || use == lv_increment || use == lv_decrement
10198               || use == lv_asm);
10199   /* Using this macro rather than (for example) arrays of messages
10200      ensures that all the format strings are checked at compile
10201      time.  */
10202 #define READONLY_MSG(A, I, D, AS) (use == lv_assign ? (A)               \
10203                                    : (use == lv_increment ? (I)         \
10204                                    : (use == lv_decrement ? (D) : (AS))))
10205   if (TREE_CODE (arg) == COMPONENT_REF)
10206     {
10207       if (TYPE_READONLY (TREE_TYPE (TREE_OPERAND (arg, 0))))
10208         error_at (loc, READONLY_MSG (G_("assignment of member "
10209                                         "%qD in read-only object"),
10210                                      G_("increment of member "
10211                                         "%qD in read-only object"),
10212                                      G_("decrement of member "
10213                                         "%qD in read-only object"),
10214                                      G_("member %qD in read-only object "
10215                                         "used as %<asm%> output")),
10216                   TREE_OPERAND (arg, 1));
10217       else
10218         error_at (loc, READONLY_MSG (G_("assignment of read-only member %qD"),
10219                                      G_("increment of read-only member %qD"),
10220                                      G_("decrement of read-only member %qD"),
10221                                      G_("read-only member %qD used as %<asm%> output")),
10222                   TREE_OPERAND (arg, 1));
10223     }
10224   else if (TREE_CODE (arg) == VAR_DECL)
10225     error_at (loc, READONLY_MSG (G_("assignment of read-only variable %qD"),
10226                                  G_("increment of read-only variable %qD"),
10227                                  G_("decrement of read-only variable %qD"),
10228                                  G_("read-only variable %qD used as %<asm%> output")),
10229               arg);
10230   else if (TREE_CODE (arg) == PARM_DECL)
10231     error_at (loc, READONLY_MSG (G_("assignment of read-only parameter %qD"),
10232                                  G_("increment of read-only parameter %qD"),
10233                                  G_("decrement of read-only parameter %qD"),
10234                                  G_("read-only parameter %qD use as %<asm%> output")),
10235               arg);
10236   else if (TREE_CODE (arg) == RESULT_DECL)
10237     {
10238       gcc_assert (c_dialect_cxx ());
10239       error_at (loc, READONLY_MSG (G_("assignment of "
10240                                       "read-only named return value %qD"),
10241                                    G_("increment of "
10242                                       "read-only named return value %qD"),
10243                                    G_("decrement of "
10244                                       "read-only named return value %qD"),
10245                                    G_("read-only named return value %qD "
10246                                       "used as %<asm%>output")),
10247                 arg);
10248     }
10249   else if (TREE_CODE (arg) == FUNCTION_DECL)
10250     error_at (loc, READONLY_MSG (G_("assignment of function %qD"),
10251                                  G_("increment of function %qD"),
10252                                  G_("decrement of function %qD"),
10253                                  G_("function %qD used as %<asm%> output")),
10254               arg);
10255   else
10256     error_at (loc, READONLY_MSG (G_("assignment of read-only location %qE"),
10257                                  G_("increment of read-only location %qE"),
10258                                  G_("decrement of read-only location %qE"),
10259                                  G_("read-only location %qE used as %<asm%> output")),
10260               arg);
10261 }
10262
10263 /* Print an error message for an invalid lvalue.  USE says
10264    how the lvalue is being used and so selects the error message.  LOC
10265    is the location for the error.  */
10266
10267 void
10268 lvalue_error (location_t loc, enum lvalue_use use)
10269 {
10270   switch (use)
10271     {
10272     case lv_assign:
10273       error_at (loc, "lvalue required as left operand of assignment");
10274       break;
10275     case lv_increment:
10276       error_at (loc, "lvalue required as increment operand");
10277       break;
10278     case lv_decrement:
10279       error_at (loc, "lvalue required as decrement operand");
10280       break;
10281     case lv_addressof:
10282       error_at (loc, "lvalue required as unary %<&%> operand");
10283       break;
10284     case lv_asm:
10285       error_at (loc, "lvalue required in asm statement");
10286       break;
10287     default:
10288       gcc_unreachable ();
10289     }
10290 }
10291
10292 /* Print an error message for an invalid indirection of type TYPE.
10293    ERRSTRING is the name of the operator for the indirection.  */
10294
10295 void
10296 invalid_indirection_error (location_t loc, tree type, ref_operator errstring)
10297 {
10298   switch (errstring)
10299     {
10300     case RO_NULL:
10301       gcc_assert (c_dialect_cxx ());
10302       error_at (loc, "invalid type argument (have %qT)", type);
10303       break;
10304     case RO_ARRAY_INDEXING:
10305       error_at (loc,
10306                 "invalid type argument of array indexing (have %qT)",
10307                 type);
10308       break;
10309     case RO_UNARY_STAR:
10310       error_at (loc,
10311                 "invalid type argument of unary %<*%> (have %qT)",
10312                 type);
10313       break;
10314     case RO_ARROW:
10315       error_at (loc,
10316                 "invalid type argument of %<->%> (have %qT)",
10317                 type);
10318       break;
10319     case RO_ARROW_STAR:
10320       error_at (loc,
10321                 "invalid type argument of %<->*%> (have %qT)",
10322                 type);
10323       break;
10324     case RO_IMPLICIT_CONVERSION:
10325       error_at (loc,
10326                 "invalid type argument of implicit conversion (have %qT)",
10327                 type);
10328       break;
10329     default:
10330       gcc_unreachable ();
10331     }
10332 }
10333 \f
10334 /* *PTYPE is an incomplete array.  Complete it with a domain based on
10335    INITIAL_VALUE.  If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
10336    is true.  Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
10337    2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty.  */
10338
10339 int
10340 complete_array_type (tree *ptype, tree initial_value, bool do_default)
10341 {
10342   tree maxindex, type, main_type, elt, unqual_elt;
10343   int failure = 0, quals;
10344   hashval_t hashcode = 0;
10345   bool overflow_p = false;
10346
10347   maxindex = size_zero_node;
10348   if (initial_value)
10349     {
10350       if (TREE_CODE (initial_value) == STRING_CST)
10351         {
10352           int eltsize
10353             = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
10354           maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
10355         }
10356       else if (TREE_CODE (initial_value) == CONSTRUCTOR)
10357         {
10358           vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
10359
10360           if (vec_safe_is_empty (v))
10361             {
10362               if (pedantic)
10363                 failure = 3;
10364               maxindex = ssize_int (-1);
10365             }
10366           else
10367             {
10368               tree curindex;
10369               unsigned HOST_WIDE_INT cnt;
10370               constructor_elt *ce;
10371               bool fold_p = false;
10372
10373               if ((*v)[0].index)
10374                 maxindex = (*v)[0].index, fold_p = true;
10375
10376               curindex = maxindex;
10377
10378               for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
10379                 {
10380                   bool curfold_p = false;
10381                   if (ce->index)
10382                     curindex = ce->index, curfold_p = true;
10383                   else
10384                     {
10385                       if (fold_p)
10386                         {
10387                           /* Since we treat size types now as ordinary
10388                              unsigned types, we need an explicit overflow
10389                              check.  */
10390                           tree orig = curindex;
10391                           curindex = fold_convert (sizetype, curindex);
10392                           overflow_p |= tree_int_cst_lt (curindex, orig);
10393                         }
10394                       curindex = size_binop (PLUS_EXPR, curindex,
10395                                              size_one_node);
10396                     }
10397                   if (tree_int_cst_lt (maxindex, curindex))
10398                     maxindex = curindex, fold_p = curfold_p;
10399                 }
10400               if (fold_p)
10401                 {
10402                   tree orig = maxindex;
10403                   maxindex = fold_convert (sizetype, maxindex);
10404                   overflow_p |= tree_int_cst_lt (maxindex, orig);
10405                 }
10406             }
10407         }
10408       else
10409         {
10410           /* Make an error message unless that happened already.  */
10411           if (initial_value != error_mark_node)
10412             failure = 1;
10413         }
10414     }
10415   else
10416     {
10417       failure = 2;
10418       if (!do_default)
10419         return failure;
10420     }
10421
10422   type = *ptype;
10423   elt = TREE_TYPE (type);
10424   quals = TYPE_QUALS (strip_array_types (elt));
10425   if (quals == 0)
10426     unqual_elt = elt;
10427   else
10428     unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
10429
10430   /* Using build_distinct_type_copy and modifying things afterward instead
10431      of using build_array_type to create a new type preserves all of the
10432      TYPE_LANG_FLAG_? bits that the front end may have set.  */
10433   main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
10434   TREE_TYPE (main_type) = unqual_elt;
10435   TYPE_DOMAIN (main_type)
10436     = build_range_type (TREE_TYPE (maxindex),
10437                         build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
10438   layout_type (main_type);
10439
10440   /* Make sure we have the canonical MAIN_TYPE. */
10441   hashcode = iterative_hash_object (TYPE_HASH (unqual_elt), hashcode);
10442   hashcode = iterative_hash_object (TYPE_HASH (TYPE_DOMAIN (main_type)),
10443                                     hashcode);
10444   main_type = type_hash_canon (hashcode, main_type);
10445
10446   /* Fix the canonical type.  */
10447   if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
10448       || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
10449     SET_TYPE_STRUCTURAL_EQUALITY (main_type);
10450   else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
10451            || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
10452                != TYPE_DOMAIN (main_type)))
10453     TYPE_CANONICAL (main_type)
10454       = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
10455                           TYPE_CANONICAL (TYPE_DOMAIN (main_type)));
10456   else
10457     TYPE_CANONICAL (main_type) = main_type;
10458
10459   if (quals == 0)
10460     type = main_type;
10461   else
10462     type = c_build_qualified_type (main_type, quals);
10463
10464   if (COMPLETE_TYPE_P (type)
10465       && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
10466       && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
10467     {
10468       error ("size of array is too large");
10469       /* If we proceed with the array type as it is, we'll eventually
10470          crash in tree_to_[su]hwi().  */
10471       type = error_mark_node;
10472     }
10473
10474   *ptype = type;
10475   return failure;
10476 }
10477
10478 /* Like c_mark_addressable but don't check register qualifier.  */
10479 void 
10480 c_common_mark_addressable_vec (tree t)
10481 {   
10482   while (handled_component_p (t))
10483     t = TREE_OPERAND (t, 0);
10484   if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
10485     return;
10486   TREE_ADDRESSABLE (t) = 1;
10487 }
10488
10489
10490 \f
10491 /* Used to help initialize the builtin-types.def table.  When a type of
10492    the correct size doesn't exist, use error_mark_node instead of NULL.
10493    The later results in segfaults even when a decl using the type doesn't
10494    get invoked.  */
10495
10496 tree
10497 builtin_type_for_size (int size, bool unsignedp)
10498 {
10499   tree type = c_common_type_for_size (size, unsignedp);
10500   return type ? type : error_mark_node;
10501 }
10502
10503 /* A helper function for resolve_overloaded_builtin in resolving the
10504    overloaded __sync_ builtins.  Returns a positive power of 2 if the
10505    first operand of PARAMS is a pointer to a supported data type.
10506    Returns 0 if an error is encountered.  */
10507
10508 static int
10509 sync_resolve_size (tree function, vec<tree, va_gc> *params)
10510 {
10511   tree type;
10512   int size;
10513
10514   if (vec_safe_is_empty (params))
10515     {
10516       error ("too few arguments to function %qE", function);
10517       return 0;
10518     }
10519
10520   type = TREE_TYPE ((*params)[0]);
10521   if (TREE_CODE (type) == ARRAY_TYPE)
10522     {
10523       /* Force array-to-pointer decay for C++.  */
10524       gcc_assert (c_dialect_cxx());
10525       (*params)[0] = default_conversion ((*params)[0]);
10526       type = TREE_TYPE ((*params)[0]);
10527     }
10528   if (TREE_CODE (type) != POINTER_TYPE)
10529     goto incompatible;
10530
10531   type = TREE_TYPE (type);
10532   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
10533     goto incompatible;
10534
10535   size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
10536   if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
10537     return size;
10538
10539  incompatible:
10540   error ("incompatible type for argument %d of %qE", 1, function);
10541   return 0;
10542 }
10543
10544 /* A helper function for resolve_overloaded_builtin.  Adds casts to
10545    PARAMS to make arguments match up with those of FUNCTION.  Drops
10546    the variadic arguments at the end.  Returns false if some error
10547    was encountered; true on success.  */
10548
10549 static bool
10550 sync_resolve_params (location_t loc, tree orig_function, tree function,
10551                      vec<tree, va_gc> *params, bool orig_format)
10552 {
10553   function_args_iterator iter;
10554   tree ptype;
10555   unsigned int parmnum;
10556
10557   function_args_iter_init (&iter, TREE_TYPE (function));
10558   /* We've declared the implementation functions to use "volatile void *"
10559      as the pointer parameter, so we shouldn't get any complaints from the
10560      call to check_function_arguments what ever type the user used.  */
10561   function_args_iter_next (&iter);
10562   ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
10563   ptype = TYPE_MAIN_VARIANT (ptype);
10564
10565   /* For the rest of the values, we need to cast these to FTYPE, so that we
10566      don't get warnings for passing pointer types, etc.  */
10567   parmnum = 0;
10568   while (1)
10569     {
10570       tree val, arg_type;
10571
10572       arg_type = function_args_iter_cond (&iter);
10573       /* XXX void_type_node belies the abstraction.  */
10574       if (arg_type == void_type_node)
10575         break;
10576
10577       ++parmnum;
10578       if (params->length () <= parmnum)
10579         {
10580           error_at (loc, "too few arguments to function %qE", orig_function);
10581           return false;
10582         }
10583
10584       /* Only convert parameters if arg_type is unsigned integer type with
10585          new format sync routines, i.e. don't attempt to convert pointer
10586          arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
10587          bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
10588          kinds).  */
10589       if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
10590         {
10591           /* Ideally for the first conversion we'd use convert_for_assignment
10592              so that we get warnings for anything that doesn't match the pointer
10593              type.  This isn't portable across the C and C++ front ends atm.  */
10594           val = (*params)[parmnum];
10595           val = convert (ptype, val);
10596           val = convert (arg_type, val);
10597           (*params)[parmnum] = val;
10598         }
10599
10600       function_args_iter_next (&iter);
10601     }
10602
10603   /* __atomic routines are not variadic.  */
10604   if (!orig_format && params->length () != parmnum + 1)
10605     {
10606       error_at (loc, "too many arguments to function %qE", orig_function);
10607       return false;
10608     }
10609
10610   /* The definition of these primitives is variadic, with the remaining
10611      being "an optional list of variables protected by the memory barrier".
10612      No clue what that's supposed to mean, precisely, but we consider all
10613      call-clobbered variables to be protected so we're safe.  */
10614   params->truncate (parmnum + 1);
10615
10616   return true;
10617 }
10618
10619 /* A helper function for resolve_overloaded_builtin.  Adds a cast to
10620    RESULT to make it match the type of the first pointer argument in
10621    PARAMS.  */
10622
10623 static tree
10624 sync_resolve_return (tree first_param, tree result, bool orig_format)
10625 {
10626   tree ptype = TREE_TYPE (TREE_TYPE (first_param));
10627   tree rtype = TREE_TYPE (result);
10628   ptype = TYPE_MAIN_VARIANT (ptype);
10629
10630   /* New format doesn't require casting unless the types are the same size.  */
10631   if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
10632     return convert (ptype, result);
10633   else
10634     return result;
10635 }
10636
10637 /* This function verifies the PARAMS to generic atomic FUNCTION.
10638    It returns the size if all the parameters are the same size, otherwise
10639    0 is returned if the parameters are invalid.  */
10640
10641 static int
10642 get_atomic_generic_size (location_t loc, tree function,
10643                          vec<tree, va_gc> *params)
10644 {
10645   unsigned int n_param;
10646   unsigned int n_model;
10647   unsigned int x;
10648   int size_0;
10649   tree type_0;
10650
10651   /* Determine the parameter makeup.  */
10652   switch (DECL_FUNCTION_CODE (function))
10653     {
10654     case BUILT_IN_ATOMIC_EXCHANGE:
10655       n_param = 4;
10656       n_model = 1;
10657       break;
10658     case BUILT_IN_ATOMIC_LOAD:
10659     case BUILT_IN_ATOMIC_STORE:
10660       n_param = 3;
10661       n_model = 1;
10662       break;
10663     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
10664       n_param = 6;
10665       n_model = 2;
10666       break;
10667     default:
10668       gcc_unreachable ();
10669     }
10670
10671   if (vec_safe_length (params) != n_param)
10672     {
10673       error_at (loc, "incorrect number of arguments to function %qE", function);
10674       return 0;
10675     }
10676
10677   /* Get type of first parameter, and determine its size.  */
10678   type_0 = TREE_TYPE ((*params)[0]);
10679   if (TREE_CODE (type_0) == ARRAY_TYPE)
10680     {
10681       /* Force array-to-pointer decay for C++.  */
10682       gcc_assert (c_dialect_cxx());
10683       (*params)[0] = default_conversion ((*params)[0]);
10684       type_0 = TREE_TYPE ((*params)[0]);
10685     }
10686   if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
10687     {
10688       error_at (loc, "argument 1 of %qE must be a non-void pointer type",
10689                 function);
10690       return 0;
10691     }
10692
10693   /* Types must be compile time constant sizes. */
10694   if (TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))) != INTEGER_CST)
10695     {
10696       error_at (loc, 
10697                 "argument 1 of %qE must be a pointer to a constant size type",
10698                 function);
10699       return 0;
10700     }
10701
10702   size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
10703
10704   /* Zero size objects are not allowed.  */
10705   if (size_0 == 0)
10706     {
10707       error_at (loc, 
10708                 "argument 1 of %qE must be a pointer to a nonzero size object",
10709                 function);
10710       return 0;
10711     }
10712
10713   /* Check each other parameter is a pointer and the same size.  */
10714   for (x = 0; x < n_param - n_model; x++)
10715     {
10716       int size;
10717       tree type = TREE_TYPE ((*params)[x]);
10718       /* __atomic_compare_exchange has a bool in the 4th position, skip it.  */
10719       if (n_param == 6 && x == 3)
10720         continue;
10721       if (!POINTER_TYPE_P (type))
10722         {
10723           error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
10724                     function);
10725           return 0;
10726         }
10727       tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
10728       size = type_size ? tree_to_uhwi (type_size) : 0;
10729       if (size != size_0)
10730         {
10731           error_at (loc, "size mismatch in argument %d of %qE", x + 1,
10732                     function);
10733           return 0;
10734         }
10735     }
10736
10737   /* Check memory model parameters for validity.  */
10738   for (x = n_param - n_model ; x < n_param; x++)
10739     {
10740       tree p = (*params)[x];
10741       if (TREE_CODE (p) == INTEGER_CST)
10742         {
10743           int i = tree_to_uhwi (p);
10744           if (i < 0 || (memmodel_base (i) >= MEMMODEL_LAST))
10745             {
10746               warning_at (loc, OPT_Winvalid_memory_model,
10747                           "invalid memory model argument %d of %qE", x + 1,
10748                           function);
10749             }
10750         }
10751       else
10752         if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
10753           {
10754             error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
10755                    function);
10756             return 0;
10757           }
10758       }
10759
10760   return size_0;
10761 }
10762
10763
10764 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
10765    at the beginning of the parameter list PARAMS representing the size of the
10766    objects.  This is to match the library ABI requirement.  LOC is the location
10767    of the function call.  
10768    The new function is returned if it needed rebuilding, otherwise NULL_TREE is
10769    returned to allow the external call to be constructed.  */
10770
10771 static tree
10772 add_atomic_size_parameter (unsigned n, location_t loc, tree function, 
10773                            vec<tree, va_gc> *params)
10774 {
10775   tree size_node;
10776
10777   /* Insert a SIZE_T parameter as the first param.  If there isn't
10778      enough space, allocate a new vector and recursively re-build with that.  */
10779   if (!params->space (1))
10780     {
10781       unsigned int z, len;
10782       vec<tree, va_gc> *v;
10783       tree f;
10784
10785       len = params->length ();
10786       vec_alloc (v, len + 1);
10787       v->quick_push (build_int_cst (size_type_node, n));
10788       for (z = 0; z < len; z++)
10789         v->quick_push ((*params)[z]);
10790       f = build_function_call_vec (loc, vNULL, function, v, NULL);
10791       vec_free (v);
10792       return f;
10793     }
10794
10795   /* Add the size parameter and leave as a function call for processing.  */
10796   size_node = build_int_cst (size_type_node, n);
10797   params->quick_insert (0, size_node);
10798   return NULL_TREE;
10799 }
10800
10801
10802 /* Return whether atomic operations for naturally aligned N-byte
10803    arguments are supported, whether inline or through libatomic.  */
10804 static bool
10805 atomic_size_supported_p (int n)
10806 {
10807   switch (n)
10808     {
10809     case 1:
10810     case 2:
10811     case 4:
10812     case 8:
10813       return true;
10814
10815     case 16:
10816       return targetm.scalar_mode_supported_p (TImode);
10817
10818     default:
10819       return false;
10820     }
10821 }
10822
10823 /* This will process an __atomic_exchange function call, determine whether it
10824    needs to be mapped to the _N variation, or turned into a library call.
10825    LOC is the location of the builtin call.
10826    FUNCTION is the DECL that has been invoked;
10827    PARAMS is the argument list for the call.  The return value is non-null
10828    TRUE is returned if it is translated into the proper format for a call to the
10829    external library, and NEW_RETURN is set the tree for that function.
10830    FALSE is returned if processing for the _N variation is required, and 
10831    NEW_RETURN is set to the the return value the result is copied into.  */
10832 static bool
10833 resolve_overloaded_atomic_exchange (location_t loc, tree function, 
10834                                     vec<tree, va_gc> *params, tree *new_return)
10835 {       
10836   tree p0, p1, p2, p3;
10837   tree I_type, I_type_ptr;
10838   int n = get_atomic_generic_size (loc, function, params);
10839
10840   /* Size of 0 is an error condition.  */
10841   if (n == 0)
10842     {
10843       *new_return = error_mark_node;
10844       return true;
10845     }
10846
10847   /* If not a lock-free size, change to the library generic format.  */
10848   if (!atomic_size_supported_p (n))
10849     {
10850       *new_return = add_atomic_size_parameter (n, loc, function, params);
10851       return true;
10852     }
10853
10854   /* Otherwise there is a lockfree match, transform the call from:
10855        void fn(T* mem, T* desired, T* return, model)
10856      into
10857        *return = (T) (fn (In* mem, (In) *desired, model))  */
10858
10859   p0 = (*params)[0];
10860   p1 = (*params)[1];
10861   p2 = (*params)[2];
10862   p3 = (*params)[3];
10863   
10864   /* Create pointer to appropriate size.  */
10865   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
10866   I_type_ptr = build_pointer_type (I_type);
10867
10868   /* Convert object pointer to required type.  */
10869   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
10870   (*params)[0] = p0; 
10871   /* Convert new value to required type, and dereference it.  */
10872   p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
10873   p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
10874   (*params)[1] = p1;
10875
10876   /* Move memory model to the 3rd position, and end param list.  */
10877   (*params)[2] = p3;
10878   params->truncate (3);
10879
10880   /* Convert return pointer and dereference it for later assignment.  */
10881   *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
10882
10883   return false;
10884 }
10885
10886
10887 /* This will process an __atomic_compare_exchange function call, determine 
10888    whether it needs to be mapped to the _N variation, or turned into a lib call.
10889    LOC is the location of the builtin call.
10890    FUNCTION is the DECL that has been invoked;
10891    PARAMS is the argument list for the call.  The return value is non-null
10892    TRUE is returned if it is translated into the proper format for a call to the
10893    external library, and NEW_RETURN is set the tree for that function.
10894    FALSE is returned if processing for the _N variation is required.  */
10895
10896 static bool
10897 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function, 
10898                                             vec<tree, va_gc> *params, 
10899                                             tree *new_return)
10900 {       
10901   tree p0, p1, p2;
10902   tree I_type, I_type_ptr;
10903   int n = get_atomic_generic_size (loc, function, params);
10904
10905   /* Size of 0 is an error condition.  */
10906   if (n == 0)
10907     {
10908       *new_return = error_mark_node;
10909       return true;
10910     }
10911
10912   /* If not a lock-free size, change to the library generic format.  */
10913   if (!atomic_size_supported_p (n))
10914     {
10915       /* The library generic format does not have the weak parameter, so 
10916          remove it from the param list.  Since a parameter has been removed,
10917          we can be sure that there is room for the SIZE_T parameter, meaning
10918          there will not be a recursive rebuilding of the parameter list, so
10919          there is no danger this will be done twice.  */
10920       if (n > 0)
10921         {
10922           (*params)[3] = (*params)[4];
10923           (*params)[4] = (*params)[5];
10924           params->truncate (5);
10925         }
10926       *new_return = add_atomic_size_parameter (n, loc, function, params);
10927       return true;
10928     }
10929
10930   /* Otherwise, there is a match, so the call needs to be transformed from:
10931        bool fn(T* mem, T* desired, T* return, weak, success, failure)
10932      into
10933        bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail)  */
10934
10935   p0 = (*params)[0];
10936   p1 = (*params)[1];
10937   p2 = (*params)[2];
10938   
10939   /* Create pointer to appropriate size.  */
10940   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
10941   I_type_ptr = build_pointer_type (I_type);
10942
10943   /* Convert object pointer to required type.  */
10944   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
10945   (*params)[0] = p0;
10946
10947   /* Convert expected pointer to required type.  */
10948   p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
10949   (*params)[1] = p1;
10950
10951   /* Convert desired value to required type, and dereference it.  */
10952   p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
10953   p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
10954   (*params)[2] = p2;
10955
10956   /* The rest of the parameters are fine. NULL means no special return value
10957      processing.*/
10958   *new_return = NULL;
10959   return false;
10960 }
10961
10962
10963 /* This will process an __atomic_load function call, determine whether it
10964    needs to be mapped to the _N variation, or turned into a library call.
10965    LOC is the location of the builtin call.
10966    FUNCTION is the DECL that has been invoked;
10967    PARAMS is the argument list for the call.  The return value is non-null
10968    TRUE is returned if it is translated into the proper format for a call to the
10969    external library, and NEW_RETURN is set the tree for that function.
10970    FALSE is returned if processing for the _N variation is required, and 
10971    NEW_RETURN is set to the the return value the result is copied into.  */
10972
10973 static bool
10974 resolve_overloaded_atomic_load (location_t loc, tree function, 
10975                                 vec<tree, va_gc> *params, tree *new_return)
10976 {       
10977   tree p0, p1, p2;
10978   tree I_type, I_type_ptr;
10979   int n = get_atomic_generic_size (loc, function, params);
10980
10981   /* Size of 0 is an error condition.  */
10982   if (n == 0)
10983     {
10984       *new_return = error_mark_node;
10985       return true;
10986     }
10987
10988   /* If not a lock-free size, change to the library generic format.  */
10989   if (!atomic_size_supported_p (n))
10990     {
10991       *new_return = add_atomic_size_parameter (n, loc, function, params);
10992       return true;
10993     }
10994
10995   /* Otherwise, there is a match, so the call needs to be transformed from:
10996        void fn(T* mem, T* return, model)
10997      into
10998        *return = (T) (fn ((In *) mem, model))  */
10999
11000   p0 = (*params)[0];
11001   p1 = (*params)[1];
11002   p2 = (*params)[2];
11003   
11004   /* Create pointer to appropriate size.  */
11005   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
11006   I_type_ptr = build_pointer_type (I_type);
11007
11008   /* Convert object pointer to required type.  */
11009   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
11010   (*params)[0] = p0;
11011
11012   /* Move memory model to the 2nd position, and end param list.  */
11013   (*params)[1] = p2;
11014   params->truncate (2);
11015
11016   /* Convert return pointer and dereference it for later assignment.  */
11017   *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
11018
11019   return false;
11020 }
11021
11022
11023 /* This will process an __atomic_store function call, determine whether it
11024    needs to be mapped to the _N variation, or turned into a library call.
11025    LOC is the location of the builtin call.
11026    FUNCTION is the DECL that has been invoked;
11027    PARAMS is the argument list for the call.  The return value is non-null
11028    TRUE is returned if it is translated into the proper format for a call to the
11029    external library, and NEW_RETURN is set the tree for that function.
11030    FALSE is returned if processing for the _N variation is required, and 
11031    NEW_RETURN is set to the the return value the result is copied into.  */
11032
11033 static bool
11034 resolve_overloaded_atomic_store (location_t loc, tree function, 
11035                                  vec<tree, va_gc> *params, tree *new_return)
11036 {       
11037   tree p0, p1;
11038   tree I_type, I_type_ptr;
11039   int n = get_atomic_generic_size (loc, function, params);
11040
11041   /* Size of 0 is an error condition.  */
11042   if (n == 0)
11043     {
11044       *new_return = error_mark_node;
11045       return true;
11046     }
11047
11048   /* If not a lock-free size, change to the library generic format.  */
11049   if (!atomic_size_supported_p (n))
11050     {
11051       *new_return = add_atomic_size_parameter (n, loc, function, params);
11052       return true;
11053     }
11054
11055   /* Otherwise, there is a match, so the call needs to be transformed from:
11056        void fn(T* mem, T* value, model)
11057      into
11058        fn ((In *) mem, (In) *value, model)  */
11059
11060   p0 = (*params)[0];
11061   p1 = (*params)[1];
11062   
11063   /* Create pointer to appropriate size.  */
11064   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
11065   I_type_ptr = build_pointer_type (I_type);
11066
11067   /* Convert object pointer to required type.  */
11068   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
11069   (*params)[0] = p0;
11070
11071   /* Convert new value to required type, and dereference it.  */
11072   p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
11073   p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
11074   (*params)[1] = p1;
11075   
11076   /* The memory model is in the right spot already. Return is void.  */
11077   *new_return = NULL_TREE;
11078
11079   return false;
11080 }
11081
11082
11083 /* Some builtin functions are placeholders for other expressions.  This
11084    function should be called immediately after parsing the call expression
11085    before surrounding code has committed to the type of the expression.
11086
11087    LOC is the location of the builtin call.
11088
11089    FUNCTION is the DECL that has been invoked; it is known to be a builtin.
11090    PARAMS is the argument list for the call.  The return value is non-null
11091    when expansion is complete, and null if normal processing should
11092    continue.  */
11093
11094 tree
11095 resolve_overloaded_builtin (location_t loc, tree function,
11096                             vec<tree, va_gc> *params)
11097 {
11098   enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
11099   bool orig_format = true;
11100   tree new_return = NULL_TREE;
11101
11102   switch (DECL_BUILT_IN_CLASS (function))
11103     {
11104     case BUILT_IN_NORMAL:
11105       break;
11106     case BUILT_IN_MD:
11107       if (targetm.resolve_overloaded_builtin)
11108         return targetm.resolve_overloaded_builtin (loc, function, params);
11109       else
11110         return NULL_TREE;
11111     default:
11112       return NULL_TREE;
11113     }
11114
11115   /* Handle BUILT_IN_NORMAL here.  */
11116   switch (orig_code)
11117     {
11118     case BUILT_IN_ATOMIC_EXCHANGE:
11119     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
11120     case BUILT_IN_ATOMIC_LOAD:
11121     case BUILT_IN_ATOMIC_STORE:
11122       {
11123         /* Handle these 4 together so that they can fall through to the next
11124            case if the call is transformed to an _N variant.  */
11125         switch (orig_code)
11126         {
11127           case BUILT_IN_ATOMIC_EXCHANGE:
11128             {
11129               if (resolve_overloaded_atomic_exchange (loc, function, params,
11130                                                       &new_return))
11131                 return new_return;
11132               /* Change to the _N variant.  */
11133               orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
11134               break;
11135             }
11136
11137           case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
11138             {
11139               if (resolve_overloaded_atomic_compare_exchange (loc, function,
11140                                                               params,
11141                                                               &new_return))
11142                 return new_return;
11143               /* Change to the _N variant.  */
11144               orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
11145               break;
11146             }
11147           case BUILT_IN_ATOMIC_LOAD:
11148             {
11149               if (resolve_overloaded_atomic_load (loc, function, params,
11150                                                   &new_return))
11151                 return new_return;
11152               /* Change to the _N variant.  */
11153               orig_code = BUILT_IN_ATOMIC_LOAD_N;
11154               break;
11155             }
11156           case BUILT_IN_ATOMIC_STORE:
11157             {
11158               if (resolve_overloaded_atomic_store (loc, function, params,
11159                                                    &new_return))
11160                 return new_return;
11161               /* Change to the _N variant.  */
11162               orig_code = BUILT_IN_ATOMIC_STORE_N;
11163               break;
11164             }
11165           default:
11166             gcc_unreachable ();
11167         }
11168         /* Fallthrough to the normal processing.  */
11169       }
11170     case BUILT_IN_ATOMIC_EXCHANGE_N:
11171     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
11172     case BUILT_IN_ATOMIC_LOAD_N:
11173     case BUILT_IN_ATOMIC_STORE_N:
11174     case BUILT_IN_ATOMIC_ADD_FETCH_N:
11175     case BUILT_IN_ATOMIC_SUB_FETCH_N:
11176     case BUILT_IN_ATOMIC_AND_FETCH_N:
11177     case BUILT_IN_ATOMIC_NAND_FETCH_N:
11178     case BUILT_IN_ATOMIC_XOR_FETCH_N:
11179     case BUILT_IN_ATOMIC_OR_FETCH_N:
11180     case BUILT_IN_ATOMIC_FETCH_ADD_N:
11181     case BUILT_IN_ATOMIC_FETCH_SUB_N:
11182     case BUILT_IN_ATOMIC_FETCH_AND_N:
11183     case BUILT_IN_ATOMIC_FETCH_NAND_N:
11184     case BUILT_IN_ATOMIC_FETCH_XOR_N:
11185     case BUILT_IN_ATOMIC_FETCH_OR_N:
11186       {
11187         orig_format = false;
11188         /* Fallthru for parameter processing.  */
11189       }
11190     case BUILT_IN_SYNC_FETCH_AND_ADD_N:
11191     case BUILT_IN_SYNC_FETCH_AND_SUB_N:
11192     case BUILT_IN_SYNC_FETCH_AND_OR_N:
11193     case BUILT_IN_SYNC_FETCH_AND_AND_N:
11194     case BUILT_IN_SYNC_FETCH_AND_XOR_N:
11195     case BUILT_IN_SYNC_FETCH_AND_NAND_N:
11196     case BUILT_IN_SYNC_ADD_AND_FETCH_N:
11197     case BUILT_IN_SYNC_SUB_AND_FETCH_N:
11198     case BUILT_IN_SYNC_OR_AND_FETCH_N:
11199     case BUILT_IN_SYNC_AND_AND_FETCH_N:
11200     case BUILT_IN_SYNC_XOR_AND_FETCH_N:
11201     case BUILT_IN_SYNC_NAND_AND_FETCH_N:
11202     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
11203     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
11204     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
11205     case BUILT_IN_SYNC_LOCK_RELEASE_N:
11206       {
11207         int n = sync_resolve_size (function, params);
11208         tree new_function, first_param, result;
11209         enum built_in_function fncode;
11210
11211         if (n == 0)
11212           return error_mark_node;
11213
11214         fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
11215         new_function = builtin_decl_explicit (fncode);
11216         if (!sync_resolve_params (loc, function, new_function, params,
11217                                   orig_format))
11218           return error_mark_node;
11219
11220         first_param = (*params)[0];
11221         result = build_function_call_vec (loc, vNULL, new_function, params,
11222                                           NULL);
11223         if (result == error_mark_node)
11224           return result;
11225         if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
11226             && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
11227             && orig_code != BUILT_IN_ATOMIC_STORE_N)
11228           result = sync_resolve_return (first_param, result, orig_format);
11229
11230         /* If new_return is set, assign function to that expr and cast the
11231            result to void since the generic interface returned void.  */
11232         if (new_return)
11233           {
11234             /* Cast function result from I{1,2,4,8,16} to the required type.  */
11235             result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
11236             result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
11237                              result);
11238             TREE_SIDE_EFFECTS (result) = 1;
11239             protected_set_expr_location (result, loc);
11240             result = convert (void_type_node, result);
11241           }
11242         return result;
11243       }
11244
11245     default:
11246       return NULL_TREE;
11247     }
11248 }
11249
11250 /* vector_types_compatible_elements_p is used in type checks of vectors
11251    values used as operands of binary operators.  Where it returns true, and
11252    the other checks of the caller succeed (being vector types in he first
11253    place, and matching number of elements), we can just treat the types
11254    as essentially the same.
11255    Contrast with vector_targets_convertible_p, which is used for vector
11256    pointer types,  and vector_types_convertible_p, which will allow
11257    language-specific matches under the control of flag_lax_vector_conversions,
11258    and might still require a conversion.  */
11259 /* True if vector types T1 and T2 can be inputs to the same binary
11260    operator without conversion.
11261    We don't check the overall vector size here because some of our callers
11262    want to give different error messages when the vectors are compatible
11263    except for the element count.  */
11264
11265 bool
11266 vector_types_compatible_elements_p (tree t1, tree t2)
11267 {
11268   bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
11269   t1 = TREE_TYPE (t1);
11270   t2 = TREE_TYPE (t2);
11271
11272   enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
11273
11274   gcc_assert ((c1 == INTEGER_TYPE || c1 == REAL_TYPE || c1 == FIXED_POINT_TYPE)
11275               && (c2 == INTEGER_TYPE || c2 == REAL_TYPE
11276                   || c2 == FIXED_POINT_TYPE));
11277
11278   t1 = c_common_signed_type (t1);
11279   t2 = c_common_signed_type (t2);
11280   /* Equality works here because c_common_signed_type uses
11281      TYPE_MAIN_VARIANT.  */
11282   if (t1 == t2)
11283     return true;
11284   if (opaque && c1 == c2
11285       && (c1 == INTEGER_TYPE || c1 == REAL_TYPE)
11286       && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
11287     return true;
11288   return false;
11289 }
11290
11291 /* Check for missing format attributes on function pointers.  LTYPE is
11292    the new type or left-hand side type.  RTYPE is the old type or
11293    right-hand side type.  Returns TRUE if LTYPE is missing the desired
11294    attribute.  */
11295
11296 bool
11297 check_missing_format_attribute (tree ltype, tree rtype)
11298 {
11299   tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
11300   tree ra;
11301
11302   for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
11303     if (is_attribute_p ("format", TREE_PURPOSE (ra)))
11304       break;
11305   if (ra)
11306     {
11307       tree la;
11308       for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
11309         if (is_attribute_p ("format", TREE_PURPOSE (la)))
11310           break;
11311       return !la;
11312     }
11313   else
11314     return false;
11315 }
11316
11317 /* Subscripting with type char is likely to lose on a machine where
11318    chars are signed.  So warn on any machine, but optionally.  Don't
11319    warn for unsigned char since that type is safe.  Don't warn for
11320    signed char because anyone who uses that must have done so
11321    deliberately. Furthermore, we reduce the false positive load by
11322    warning only for non-constant value of type char.  */
11323
11324 void
11325 warn_array_subscript_with_type_char (location_t loc, tree index)
11326 {
11327   if (TYPE_MAIN_VARIANT (TREE_TYPE (index)) == char_type_node
11328       && TREE_CODE (index) != INTEGER_CST)
11329     warning_at (loc, OPT_Wchar_subscripts,
11330                 "array subscript has type %<char%>");
11331 }
11332
11333 /* Implement -Wparentheses for the unexpected C precedence rules, to
11334    cover cases like x + y << z which readers are likely to
11335    misinterpret.  We have seen an expression in which CODE is a binary
11336    operator used to combine expressions ARG_LEFT and ARG_RIGHT, which
11337    before folding had CODE_LEFT and CODE_RIGHT.  CODE_LEFT and
11338    CODE_RIGHT may be ERROR_MARK, which means that that side of the
11339    expression was not formed using a binary or unary operator, or it
11340    was enclosed in parentheses.  */
11341
11342 void
11343 warn_about_parentheses (location_t loc, enum tree_code code,
11344                         enum tree_code code_left, tree arg_left,
11345                         enum tree_code code_right, tree arg_right)
11346 {
11347   if (!warn_parentheses)
11348     return;
11349
11350   /* This macro tests that the expression ARG with original tree code
11351      CODE appears to be a boolean expression. or the result of folding a
11352      boolean expression.  */
11353 #define APPEARS_TO_BE_BOOLEAN_EXPR_P(CODE, ARG)                             \
11354         (truth_value_p (TREE_CODE (ARG))                                    \
11355          || TREE_CODE (TREE_TYPE (ARG)) == BOOLEAN_TYPE                     \
11356          /* Folding may create 0 or 1 integers from other expressions.  */  \
11357          || ((CODE) != INTEGER_CST                                          \
11358              && (integer_onep (ARG) || integer_zerop (ARG))))
11359
11360   switch (code)
11361     {
11362     case LSHIFT_EXPR:
11363       if (code_left == PLUS_EXPR)
11364         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11365                     "suggest parentheses around %<+%> inside %<<<%>");
11366       else if (code_right == PLUS_EXPR)
11367         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11368                     "suggest parentheses around %<+%> inside %<<<%>");
11369       else if (code_left == MINUS_EXPR)
11370         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11371                     "suggest parentheses around %<-%> inside %<<<%>");
11372       else if (code_right == MINUS_EXPR)
11373         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11374                     "suggest parentheses around %<-%> inside %<<<%>");
11375       return;
11376
11377     case RSHIFT_EXPR:
11378       if (code_left == PLUS_EXPR)
11379         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11380                     "suggest parentheses around %<+%> inside %<>>%>");
11381       else if (code_right == PLUS_EXPR)
11382         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11383                     "suggest parentheses around %<+%> inside %<>>%>");
11384       else if (code_left == MINUS_EXPR)
11385         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11386                     "suggest parentheses around %<-%> inside %<>>%>");
11387       else if (code_right == MINUS_EXPR)
11388         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11389                     "suggest parentheses around %<-%> inside %<>>%>");
11390       return;
11391
11392     case TRUTH_ORIF_EXPR:
11393       if (code_left == TRUTH_ANDIF_EXPR)
11394         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11395                     "suggest parentheses around %<&&%> within %<||%>");
11396       else if (code_right == TRUTH_ANDIF_EXPR)
11397         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11398                     "suggest parentheses around %<&&%> within %<||%>");
11399       return;
11400
11401     case BIT_IOR_EXPR:
11402       if (code_left == BIT_AND_EXPR || code_left == BIT_XOR_EXPR
11403           || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
11404         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11405                  "suggest parentheses around arithmetic in operand of %<|%>");
11406       else if (code_right == BIT_AND_EXPR || code_right == BIT_XOR_EXPR
11407                || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
11408         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11409                  "suggest parentheses around arithmetic in operand of %<|%>");
11410       /* Check cases like x|y==z */
11411       else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
11412         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11413                  "suggest parentheses around comparison in operand of %<|%>");
11414       else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
11415         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11416                  "suggest parentheses around comparison in operand of %<|%>");
11417       /* Check cases like !x | y */
11418       else if (code_left == TRUTH_NOT_EXPR
11419                && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
11420         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11421                     "suggest parentheses around operand of "
11422                     "%<!%> or change %<|%> to %<||%> or %<!%> to %<~%>");
11423       return;
11424
11425     case BIT_XOR_EXPR:
11426       if (code_left == BIT_AND_EXPR
11427           || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
11428         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11429                  "suggest parentheses around arithmetic in operand of %<^%>");
11430       else if (code_right == BIT_AND_EXPR
11431                || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
11432         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11433                  "suggest parentheses around arithmetic in operand of %<^%>");
11434       /* Check cases like x^y==z */
11435       else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
11436         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11437                  "suggest parentheses around comparison in operand of %<^%>");
11438       else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
11439         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11440                  "suggest parentheses around comparison in operand of %<^%>");
11441       return;
11442
11443     case BIT_AND_EXPR:
11444       if (code_left == PLUS_EXPR)
11445         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11446                  "suggest parentheses around %<+%> in operand of %<&%>");
11447       else if (code_right == PLUS_EXPR)
11448         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11449                  "suggest parentheses around %<+%> in operand of %<&%>");
11450       else if (code_left == MINUS_EXPR)
11451         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11452                  "suggest parentheses around %<-%> in operand of %<&%>");
11453       else if (code_right == MINUS_EXPR)
11454         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11455                  "suggest parentheses around %<-%> in operand of %<&%>");
11456       /* Check cases like x&y==z */
11457       else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
11458         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11459                  "suggest parentheses around comparison in operand of %<&%>");
11460       else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
11461         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11462                  "suggest parentheses around comparison in operand of %<&%>");
11463       /* Check cases like !x & y */
11464       else if (code_left == TRUTH_NOT_EXPR
11465                && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
11466         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11467                     "suggest parentheses around operand of "
11468                     "%<!%> or change %<&%> to %<&&%> or %<!%> to %<~%>");
11469       return;
11470
11471     case EQ_EXPR:
11472       if (TREE_CODE_CLASS (code_left) == tcc_comparison)
11473         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11474                  "suggest parentheses around comparison in operand of %<==%>");
11475       else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
11476         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11477                  "suggest parentheses around comparison in operand of %<==%>");
11478       return;
11479     case NE_EXPR:
11480       if (TREE_CODE_CLASS (code_left) == tcc_comparison)
11481         warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11482                  "suggest parentheses around comparison in operand of %<!=%>");
11483       else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
11484         warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11485                  "suggest parentheses around comparison in operand of %<!=%>");
11486       return;
11487
11488     default:
11489       if (TREE_CODE_CLASS (code) == tcc_comparison)
11490         {
11491           if (TREE_CODE_CLASS (code_left) == tcc_comparison
11492                 && code_left != NE_EXPR && code_left != EQ_EXPR
11493                 && INTEGRAL_TYPE_P (TREE_TYPE (arg_left)))
11494             warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
11495                         "comparisons like %<X<=Y<=Z%> do not "
11496                         "have their mathematical meaning");
11497           else if (TREE_CODE_CLASS (code_right) == tcc_comparison
11498                    && code_right != NE_EXPR && code_right != EQ_EXPR
11499                    && INTEGRAL_TYPE_P (TREE_TYPE (arg_right)))
11500             warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
11501                         "comparisons like %<X<=Y<=Z%> do not "
11502                         "have their mathematical meaning");
11503         }
11504       return;
11505     }
11506 #undef NOT_A_BOOLEAN_EXPR_P
11507 }
11508
11509 /* If LABEL (a LABEL_DECL) has not been used, issue a warning.  */
11510
11511 void
11512 warn_for_unused_label (tree label)
11513 {
11514   if (!TREE_USED (label))
11515     {
11516       if (DECL_INITIAL (label))
11517         warning (OPT_Wunused_label, "label %q+D defined but not used", label);
11518       else
11519         warning (OPT_Wunused_label, "label %q+D declared but not defined", label);
11520     }
11521 }
11522
11523 /* Warn for division by zero according to the value of DIVISOR.  LOC
11524    is the location of the division operator.  */
11525
11526 void
11527 warn_for_div_by_zero (location_t loc, tree divisor)
11528 {
11529   /* If DIVISOR is zero, and has integral or fixed-point type, issue a warning
11530      about division by zero.  Do not issue a warning if DIVISOR has a
11531      floating-point type, since we consider 0.0/0.0 a valid way of
11532      generating a NaN.  */
11533   if (c_inhibit_evaluation_warnings == 0
11534       && (integer_zerop (divisor) || fixed_zerop (divisor)))
11535     warning_at (loc, OPT_Wdiv_by_zero, "division by zero");
11536 }
11537
11538 /* Subroutine of build_binary_op. Give warnings for comparisons
11539    between signed and unsigned quantities that may fail. Do the
11540    checking based on the original operand trees ORIG_OP0 and ORIG_OP1,
11541    so that casts will be considered, but default promotions won't
11542    be.
11543
11544    LOCATION is the location of the comparison operator.
11545
11546    The arguments of this function map directly to local variables
11547    of build_binary_op.  */
11548
11549 void
11550 warn_for_sign_compare (location_t location,
11551                        tree orig_op0, tree orig_op1,
11552                        tree op0, tree op1,
11553                        tree result_type, enum tree_code resultcode)
11554 {
11555   int op0_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op0));
11556   int op1_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op1));
11557   int unsignedp0, unsignedp1;
11558
11559   /* In C++, check for comparison of different enum types.  */
11560   if (c_dialect_cxx()
11561       && TREE_CODE (TREE_TYPE (orig_op0)) == ENUMERAL_TYPE
11562       && TREE_CODE (TREE_TYPE (orig_op1)) == ENUMERAL_TYPE
11563       && TYPE_MAIN_VARIANT (TREE_TYPE (orig_op0))
11564          != TYPE_MAIN_VARIANT (TREE_TYPE (orig_op1)))
11565     {
11566       warning_at (location,
11567                   OPT_Wsign_compare, "comparison between types %qT and %qT",
11568                   TREE_TYPE (orig_op0), TREE_TYPE (orig_op1));
11569     }
11570
11571   /* Do not warn if the comparison is being done in a signed type,
11572      since the signed type will only be chosen if it can represent
11573      all the values of the unsigned type.  */
11574   if (!TYPE_UNSIGNED (result_type))
11575     /* OK */;
11576   /* Do not warn if both operands are unsigned.  */
11577   else if (op0_signed == op1_signed)
11578     /* OK */;
11579   else
11580     {
11581       tree sop, uop, base_type;
11582       bool ovf;
11583
11584       if (op0_signed)
11585         sop = orig_op0, uop = orig_op1;
11586       else
11587         sop = orig_op1, uop = orig_op0;
11588
11589       STRIP_TYPE_NOPS (sop);
11590       STRIP_TYPE_NOPS (uop);
11591       base_type = (TREE_CODE (result_type) == COMPLEX_TYPE
11592                    ? TREE_TYPE (result_type) : result_type);
11593
11594       /* Do not warn if the signed quantity is an unsuffixed integer
11595          literal (or some static constant expression involving such
11596          literals or a conditional expression involving such literals)
11597          and it is non-negative.  */
11598       if (tree_expr_nonnegative_warnv_p (sop, &ovf))
11599         /* OK */;
11600       /* Do not warn if the comparison is an equality operation, the
11601          unsigned quantity is an integral constant, and it would fit
11602          in the result if the result were signed.  */
11603       else if (TREE_CODE (uop) == INTEGER_CST
11604                && (resultcode == EQ_EXPR || resultcode == NE_EXPR)
11605                && int_fits_type_p (uop, c_common_signed_type (base_type)))
11606         /* OK */;
11607       /* In C, do not warn if the unsigned quantity is an enumeration
11608          constant and its maximum value would fit in the result if the
11609          result were signed.  */
11610       else if (!c_dialect_cxx() && TREE_CODE (uop) == INTEGER_CST
11611                && TREE_CODE (TREE_TYPE (uop)) == ENUMERAL_TYPE
11612                && int_fits_type_p (TYPE_MAX_VALUE (TREE_TYPE (uop)),
11613                                    c_common_signed_type (base_type)))
11614         /* OK */;
11615       else
11616         warning_at (location,
11617                     OPT_Wsign_compare,
11618                     "comparison between signed and unsigned integer expressions");
11619     }
11620
11621   /* Warn if two unsigned values are being compared in a size larger
11622      than their original size, and one (and only one) is the result of
11623      a `~' operator.  This comparison will always fail.
11624
11625      Also warn if one operand is a constant, and the constant does not
11626      have all bits set that are set in the ~ operand when it is
11627      extended.  */
11628
11629   op0 = c_common_get_narrower (op0, &unsignedp0);
11630   op1 = c_common_get_narrower (op1, &unsignedp1);
11631
11632   if ((TREE_CODE (op0) == BIT_NOT_EXPR)
11633       ^ (TREE_CODE (op1) == BIT_NOT_EXPR))
11634     {
11635       if (TREE_CODE (op0) == BIT_NOT_EXPR)
11636         op0 = c_common_get_narrower (TREE_OPERAND (op0, 0), &unsignedp0);
11637       if (TREE_CODE (op1) == BIT_NOT_EXPR)
11638         op1 = c_common_get_narrower (TREE_OPERAND (op1, 0), &unsignedp1);
11639
11640       if (tree_fits_shwi_p (op0) || tree_fits_shwi_p (op1))
11641         {
11642           tree primop;
11643           HOST_WIDE_INT constant, mask;
11644           int unsignedp;
11645           unsigned int bits;
11646
11647           if (tree_fits_shwi_p (op0))
11648             {
11649               primop = op1;
11650               unsignedp = unsignedp1;
11651               constant = tree_to_shwi (op0);
11652             }
11653           else
11654             {
11655               primop = op0;
11656               unsignedp = unsignedp0;
11657               constant = tree_to_shwi (op1);
11658             }
11659
11660           bits = TYPE_PRECISION (TREE_TYPE (primop));
11661           if (bits < TYPE_PRECISION (result_type)
11662               && bits < HOST_BITS_PER_LONG && unsignedp)
11663             {
11664               mask = (~ (HOST_WIDE_INT) 0) << bits;
11665               if ((mask & constant) != mask)
11666                 {
11667                   if (constant == 0)
11668                     warning_at (location, OPT_Wsign_compare,
11669                                 "promoted ~unsigned is always non-zero");
11670                   else
11671                     warning_at (location, OPT_Wsign_compare,
11672                                 "comparison of promoted ~unsigned with constant");
11673                 }
11674             }
11675         }
11676       else if (unsignedp0 && unsignedp1
11677                && (TYPE_PRECISION (TREE_TYPE (op0))
11678                    < TYPE_PRECISION (result_type))
11679                && (TYPE_PRECISION (TREE_TYPE (op1))
11680                    < TYPE_PRECISION (result_type)))
11681         warning_at (location, OPT_Wsign_compare,
11682                  "comparison of promoted ~unsigned with unsigned");
11683     }
11684 }
11685
11686 /* RESULT_TYPE is the result of converting TYPE1 and TYPE2 to a common
11687    type via c_common_type.  If -Wdouble-promotion is in use, and the
11688    conditions for warning have been met, issue a warning.  GMSGID is
11689    the warning message.  It must have two %T specifiers for the type
11690    that was converted (generally "float") and the type to which it was
11691    converted (generally "double), respectively.  LOC is the location
11692    to which the awrning should refer.  */
11693
11694 void
11695 do_warn_double_promotion (tree result_type, tree type1, tree type2,
11696                          const char *gmsgid, location_t loc)
11697 {
11698   tree source_type;
11699
11700   if (!warn_double_promotion)
11701     return;
11702   /* If the conversion will not occur at run-time, there is no need to
11703      warn about it.  */
11704   if (c_inhibit_evaluation_warnings)
11705     return;
11706   if (TYPE_MAIN_VARIANT (result_type) != double_type_node
11707       && TYPE_MAIN_VARIANT (result_type) != complex_double_type_node)
11708     return;
11709   if (TYPE_MAIN_VARIANT (type1) == float_type_node
11710       || TYPE_MAIN_VARIANT (type1) == complex_float_type_node)
11711     source_type = type1;
11712   else if (TYPE_MAIN_VARIANT (type2) == float_type_node
11713            || TYPE_MAIN_VARIANT (type2) == complex_float_type_node)
11714     source_type = type2;
11715   else
11716     return;
11717   warning_at (loc, OPT_Wdouble_promotion, gmsgid, source_type, result_type);
11718 }
11719
11720 /* Setup a TYPE_DECL node as a typedef representation.
11721
11722    X is a TYPE_DECL for a typedef statement.  Create a brand new
11723    ..._TYPE node (which will be just a variant of the existing
11724    ..._TYPE node with identical properties) and then install X
11725    as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
11726
11727    The whole point here is to end up with a situation where each
11728    and every ..._TYPE node the compiler creates will be uniquely
11729    associated with AT MOST one node representing a typedef name.
11730    This way, even though the compiler substitutes corresponding
11731    ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
11732    early on, later parts of the compiler can always do the reverse
11733    translation and get back the corresponding typedef name.  For
11734    example, given:
11735
11736         typedef struct S MY_TYPE;
11737         MY_TYPE object;
11738
11739    Later parts of the compiler might only know that `object' was of
11740    type `struct S' if it were not for code just below.  With this
11741    code however, later parts of the compiler see something like:
11742
11743         struct S' == struct S
11744         typedef struct S' MY_TYPE;
11745         struct S' object;
11746
11747     And they can then deduce (from the node for type struct S') that
11748     the original object declaration was:
11749
11750                 MY_TYPE object;
11751
11752     Being able to do this is important for proper support of protoize,
11753     and also for generating precise symbolic debugging information
11754     which takes full account of the programmer's (typedef) vocabulary.
11755
11756     Obviously, we don't want to generate a duplicate ..._TYPE node if
11757     the TYPE_DECL node that we are now processing really represents a
11758     standard built-in type.  */
11759
11760 void
11761 set_underlying_type (tree x)
11762 {
11763   if (x == error_mark_node)
11764     return;
11765   if (DECL_IS_BUILTIN (x))
11766     {
11767       if (TYPE_NAME (TREE_TYPE (x)) == 0)
11768         TYPE_NAME (TREE_TYPE (x)) = x;
11769     }
11770   else if (TREE_TYPE (x) != error_mark_node
11771            && DECL_ORIGINAL_TYPE (x) == NULL_TREE)
11772     {
11773       tree tt = TREE_TYPE (x);
11774       DECL_ORIGINAL_TYPE (x) = tt;
11775       tt = build_variant_type_copy (tt);
11776       TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
11777       TYPE_NAME (tt) = x;
11778       TREE_USED (tt) = TREE_USED (x);
11779       TREE_TYPE (x) = tt;
11780     }
11781 }
11782
11783 /* Record the types used by the current global variable declaration
11784    being parsed, so that we can decide later to emit their debug info.
11785    Those types are in types_used_by_cur_var_decl, and we are going to
11786    store them in the types_used_by_vars_hash hash table.
11787    DECL is the declaration of the global variable that has been parsed.  */
11788
11789 void
11790 record_types_used_by_current_var_decl (tree decl)
11791 {
11792   gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
11793
11794   while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
11795     {
11796       tree type = types_used_by_cur_var_decl->pop ();
11797       types_used_by_var_decl_insert (type, decl);
11798     }
11799 }
11800
11801 /* If DECL is a typedef that is declared in the current function,
11802    record it for the purpose of -Wunused-local-typedefs.  */
11803
11804 void
11805 record_locally_defined_typedef (tree decl)
11806 {
11807   struct c_language_function *l;
11808
11809   if (!warn_unused_local_typedefs
11810       || cfun == NULL
11811       /* if this is not a locally defined typedef then we are not
11812          interested.  */
11813       || !is_typedef_decl (decl)
11814       || !decl_function_context (decl))
11815     return;
11816
11817   l = (struct c_language_function *) cfun->language;
11818   vec_safe_push (l->local_typedefs, decl);
11819 }
11820
11821 /* If T is a TYPE_DECL declared locally, mark it as used.  */
11822
11823 void
11824 maybe_record_typedef_use (tree t)
11825 {
11826   if (!is_typedef_decl (t))
11827     return;
11828
11829   TREE_USED (t) = true;
11830 }
11831
11832 /* Warn if there are some unused locally defined typedefs in the
11833    current function. */
11834
11835 void
11836 maybe_warn_unused_local_typedefs (void)
11837 {
11838   int i;
11839   tree decl;
11840   /* The number of times we have emitted -Wunused-local-typedefs
11841      warnings.  If this is different from errorcount, that means some
11842      unrelated errors have been issued.  In which case, we'll avoid
11843      emitting "unused-local-typedefs" warnings.  */
11844   static int unused_local_typedefs_warn_count;
11845   struct c_language_function *l;
11846
11847   if (cfun == NULL)
11848     return;
11849
11850   if ((l = (struct c_language_function *) cfun->language) == NULL)
11851     return;
11852
11853   if (warn_unused_local_typedefs
11854       && errorcount == unused_local_typedefs_warn_count)
11855     {
11856       FOR_EACH_VEC_SAFE_ELT (l->local_typedefs, i, decl)
11857         if (!TREE_USED (decl))
11858           warning_at (DECL_SOURCE_LOCATION (decl),
11859                       OPT_Wunused_local_typedefs,
11860                       "typedef %qD locally defined but not used", decl);
11861       unused_local_typedefs_warn_count = errorcount;
11862     }
11863
11864   vec_free (l->local_typedefs);
11865 }
11866
11867 /* Warn about boolean expression compared with an integer value different
11868    from true/false.  Warns also e.g. about "(i1 == i2) == 2".
11869    LOC is the location of the comparison, CODE is its code, OP0 and OP1
11870    are the operands of the comparison.  The caller must ensure that
11871    either operand is a boolean expression.  */
11872
11873 void
11874 maybe_warn_bool_compare (location_t loc, enum tree_code code, tree op0,
11875                          tree op1)
11876 {
11877   if (TREE_CODE_CLASS (code) != tcc_comparison)
11878     return;
11879
11880   tree cst = (TREE_CODE (op0) == INTEGER_CST)
11881              ? op0 : (TREE_CODE (op1) == INTEGER_CST) ? op1 : NULL_TREE;
11882   if (!cst)
11883     return;
11884
11885   if (!integer_zerop (cst) && !integer_onep (cst))
11886     {
11887       int sign = (TREE_CODE (op0) == INTEGER_CST)
11888                  ? tree_int_cst_sgn (cst) : -tree_int_cst_sgn (cst);
11889       if (code == EQ_EXPR
11890           || ((code == GT_EXPR || code == GE_EXPR) && sign < 0)
11891           || ((code == LT_EXPR || code == LE_EXPR) && sign > 0))
11892         warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
11893                     "with boolean expression is always false", cst);
11894       else
11895         warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
11896                     "with boolean expression is always true", cst);
11897     }
11898 }
11899
11900 /* The C and C++ parsers both use vectors to hold function arguments.
11901    For efficiency, we keep a cache of unused vectors.  This is the
11902    cache.  */
11903
11904 typedef vec<tree, va_gc> *tree_gc_vec;
11905 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
11906
11907 /* Return a new vector from the cache.  If the cache is empty,
11908    allocate a new vector.  These vectors are GC'ed, so it is OK if the
11909    pointer is not released..  */
11910
11911 vec<tree, va_gc> *
11912 make_tree_vector (void)
11913 {
11914   if (tree_vector_cache && !tree_vector_cache->is_empty ())
11915     return tree_vector_cache->pop ();
11916   else
11917     {
11918       /* Passing 0 to vec::alloc returns NULL, and our callers require
11919          that we always return a non-NULL value.  The vector code uses
11920          4 when growing a NULL vector, so we do too.  */
11921       vec<tree, va_gc> *v;
11922       vec_alloc (v, 4);
11923       return v;
11924     }
11925 }
11926
11927 /* Release a vector of trees back to the cache.  */
11928
11929 void
11930 release_tree_vector (vec<tree, va_gc> *vec)
11931 {
11932   if (vec != NULL)
11933     {
11934       vec->truncate (0);
11935       vec_safe_push (tree_vector_cache, vec);
11936     }
11937 }
11938
11939 /* Get a new tree vector holding a single tree.  */
11940
11941 vec<tree, va_gc> *
11942 make_tree_vector_single (tree t)
11943 {
11944   vec<tree, va_gc> *ret = make_tree_vector ();
11945   ret->quick_push (t);
11946   return ret;
11947 }
11948
11949 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain.  */
11950
11951 vec<tree, va_gc> *
11952 make_tree_vector_from_list (tree list)
11953 {
11954   vec<tree, va_gc> *ret = make_tree_vector ();
11955   for (; list; list = TREE_CHAIN (list))
11956     vec_safe_push (ret, TREE_VALUE (list));
11957   return ret;
11958 }
11959
11960 /* Get a new tree vector which is a copy of an existing one.  */
11961
11962 vec<tree, va_gc> *
11963 make_tree_vector_copy (const vec<tree, va_gc> *orig)
11964 {
11965   vec<tree, va_gc> *ret;
11966   unsigned int ix;
11967   tree t;
11968
11969   ret = make_tree_vector ();
11970   vec_safe_reserve (ret, vec_safe_length (orig));
11971   FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
11972     ret->quick_push (t);
11973   return ret;
11974 }
11975
11976 /* Return true if KEYWORD starts a type specifier.  */
11977
11978 bool
11979 keyword_begins_type_specifier (enum rid keyword)
11980 {
11981   switch (keyword)
11982     {
11983     case RID_AUTO_TYPE:
11984     case RID_INT:
11985     case RID_CHAR:
11986     case RID_FLOAT:
11987     case RID_DOUBLE:
11988     case RID_VOID:
11989     case RID_UNSIGNED:
11990     case RID_LONG:
11991     case RID_SHORT:
11992     case RID_SIGNED:
11993     case RID_DFLOAT32:
11994     case RID_DFLOAT64:
11995     case RID_DFLOAT128:
11996     case RID_FRACT:
11997     case RID_ACCUM:
11998     case RID_BOOL:
11999     case RID_WCHAR:
12000     case RID_CHAR16:
12001     case RID_CHAR32:
12002     case RID_SAT:
12003     case RID_COMPLEX:
12004     case RID_TYPEOF:
12005     case RID_STRUCT:
12006     case RID_CLASS:
12007     case RID_UNION:
12008     case RID_ENUM:
12009       return true;
12010     default:
12011       if (keyword >= RID_FIRST_INT_N
12012           && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
12013           && int_n_enabled_p[keyword-RID_FIRST_INT_N])
12014         return true;
12015       return false;
12016     }
12017 }
12018
12019 /* Return true if KEYWORD names a type qualifier.  */
12020
12021 bool
12022 keyword_is_type_qualifier (enum rid keyword)
12023 {
12024   switch (keyword)
12025     {
12026     case RID_CONST:
12027     case RID_VOLATILE:
12028     case RID_RESTRICT:
12029     case RID_ATOMIC:
12030       return true;
12031     default:
12032       return false;
12033     }
12034 }
12035
12036 /* Return true if KEYWORD names a storage class specifier.
12037
12038    RID_TYPEDEF is not included in this list despite `typedef' being
12039    listed in C99 6.7.1.1.  6.7.1.3 indicates that `typedef' is listed as
12040    such for syntactic convenience only.  */
12041
12042 bool
12043 keyword_is_storage_class_specifier (enum rid keyword)
12044 {
12045   switch (keyword)
12046     {
12047     case RID_STATIC:
12048     case RID_EXTERN:
12049     case RID_REGISTER:
12050     case RID_AUTO:
12051     case RID_MUTABLE:
12052     case RID_THREAD:
12053       return true;
12054     default:
12055       return false;
12056     }
12057 }
12058
12059 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec].  */
12060
12061 static bool
12062 keyword_is_function_specifier (enum rid keyword)
12063 {
12064   switch (keyword)
12065     {
12066     case RID_INLINE:
12067     case RID_NORETURN:
12068     case RID_VIRTUAL:
12069     case RID_EXPLICIT:
12070       return true;
12071     default:
12072       return false;
12073     }
12074 }
12075
12076 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
12077    declaration-specifier (C99 6.7).  */
12078
12079 bool
12080 keyword_is_decl_specifier (enum rid keyword)
12081 {
12082   if (keyword_is_storage_class_specifier (keyword)
12083       || keyword_is_type_qualifier (keyword)
12084       || keyword_is_function_specifier (keyword))
12085     return true;
12086
12087   switch (keyword)
12088     {
12089     case RID_TYPEDEF:
12090     case RID_FRIEND:
12091     case RID_CONSTEXPR:
12092       return true;
12093     default:
12094       return false;
12095     }
12096 }
12097
12098 /* Initialize language-specific-bits of tree_contains_struct.  */
12099
12100 void
12101 c_common_init_ts (void)
12102 {
12103   MARK_TS_TYPED (C_MAYBE_CONST_EXPR);
12104   MARK_TS_TYPED (EXCESS_PRECISION_EXPR);
12105   MARK_TS_TYPED (ARRAY_NOTATION_REF);
12106 }
12107
12108 /* Build a user-defined numeric literal out of an integer constant type VALUE
12109    with identifier SUFFIX.  */
12110
12111 tree
12112 build_userdef_literal (tree suffix_id, tree value,
12113                        enum overflow_type overflow, tree num_string)
12114 {
12115   tree literal = make_node (USERDEF_LITERAL);
12116   USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
12117   USERDEF_LITERAL_VALUE (literal) = value;
12118   USERDEF_LITERAL_OVERFLOW (literal) = overflow;
12119   USERDEF_LITERAL_NUM_STRING (literal) = num_string;
12120   return literal;
12121 }
12122
12123 /* For vector[index], convert the vector to a
12124    pointer of the underlying type.  Return true if the resulting
12125    ARRAY_REF should not be an lvalue.  */
12126
12127 bool
12128 convert_vector_to_pointer_for_subscript (location_t loc,
12129                                          tree *vecp, tree index)
12130 {
12131   bool ret = false;
12132   if (TREE_CODE (TREE_TYPE (*vecp)) == VECTOR_TYPE)
12133     {
12134       tree type = TREE_TYPE (*vecp);
12135       tree type1;
12136
12137       ret = !lvalue_p (*vecp);
12138       if (TREE_CODE (index) == INTEGER_CST)
12139         if (!tree_fits_uhwi_p (index)
12140             || tree_to_uhwi (index) >= TYPE_VECTOR_SUBPARTS (type))
12141           warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
12142
12143       if (ret)
12144         {
12145           tree tmp = create_tmp_var_raw (type);
12146           DECL_SOURCE_LOCATION (tmp) = loc;
12147           *vecp = c_save_expr (*vecp);
12148           if (TREE_CODE (*vecp) == C_MAYBE_CONST_EXPR)
12149             {
12150               bool non_const = C_MAYBE_CONST_EXPR_NON_CONST (*vecp);
12151               *vecp = C_MAYBE_CONST_EXPR_EXPR (*vecp);
12152               *vecp
12153                 = c_wrap_maybe_const (build4 (TARGET_EXPR, type, tmp,
12154                                               *vecp, NULL_TREE, NULL_TREE),
12155                                       non_const);
12156             }
12157           else
12158             *vecp = build4 (TARGET_EXPR, type, tmp, *vecp,
12159                             NULL_TREE, NULL_TREE);
12160           SET_EXPR_LOCATION (*vecp, loc);
12161           c_common_mark_addressable_vec (tmp);
12162         }
12163       else
12164         c_common_mark_addressable_vec (*vecp);
12165       type = build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
12166       type1 = build_pointer_type (TREE_TYPE (*vecp));
12167       bool ref_all = TYPE_REF_CAN_ALIAS_ALL (type1);
12168       if (!ref_all
12169           && !DECL_P (*vecp))
12170         {
12171           /* If the original vector isn't declared may_alias and it
12172              isn't a bare vector look if the subscripting would
12173              alias the vector we subscript, and if not, force ref-all.  */
12174           alias_set_type vecset = get_alias_set (*vecp);
12175           alias_set_type sset = get_alias_set (type);
12176           if (!alias_sets_must_conflict_p (sset, vecset)
12177               && !alias_set_subset_of (sset, vecset))
12178             ref_all = true;
12179         }
12180       type = build_pointer_type_for_mode (type, ptr_mode, ref_all);
12181       *vecp = build1 (ADDR_EXPR, type1, *vecp);
12182       *vecp = convert (type, *vecp);
12183     }
12184   return ret;
12185 }
12186
12187 /* Determine which of the operands, if any, is a scalar that needs to be
12188    converted to a vector, for the range of operations.  */
12189 enum stv_conv
12190 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
12191                   bool complain)
12192 {
12193   tree type0 = TREE_TYPE (op0);
12194   tree type1 = TREE_TYPE (op1);
12195   bool integer_only_op = false;
12196   enum stv_conv ret = stv_firstarg;
12197
12198   gcc_assert (TREE_CODE (type0) == VECTOR_TYPE
12199               || TREE_CODE (type1) == VECTOR_TYPE);
12200   switch (code)
12201     {
12202       /* Most GENERIC binary expressions require homogeneous arguments.
12203          LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
12204          argument that is a vector and a second one that is a scalar, so
12205          we never return stv_secondarg for them.  */
12206       case RSHIFT_EXPR:
12207       case LSHIFT_EXPR:
12208         if (TREE_CODE (type0) == INTEGER_TYPE
12209             && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
12210           {
12211             if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0, false))
12212               {
12213                 if (complain)
12214                   error_at (loc, "conversion of scalar %qT to vector %qT "
12215                             "involves truncation", type0, type1);
12216                 return stv_error;
12217               }
12218             else
12219               return stv_firstarg;
12220           }
12221         break;
12222
12223       case BIT_IOR_EXPR:
12224       case BIT_XOR_EXPR:
12225       case BIT_AND_EXPR:
12226         integer_only_op = true;
12227         /* ... fall through ...  */
12228
12229       case VEC_COND_EXPR:
12230
12231       case PLUS_EXPR:
12232       case MINUS_EXPR:
12233       case MULT_EXPR:
12234       case TRUNC_DIV_EXPR:
12235       case CEIL_DIV_EXPR:
12236       case FLOOR_DIV_EXPR:
12237       case ROUND_DIV_EXPR:
12238       case EXACT_DIV_EXPR:
12239       case TRUNC_MOD_EXPR:
12240       case FLOOR_MOD_EXPR:
12241       case RDIV_EXPR:
12242       case EQ_EXPR:
12243       case NE_EXPR:
12244       case LE_EXPR:
12245       case GE_EXPR:
12246       case LT_EXPR:
12247       case GT_EXPR:
12248       /* What about UNLT_EXPR?  */
12249         if (TREE_CODE (type0) == VECTOR_TYPE)
12250           {
12251             tree tmp;
12252             ret = stv_secondarg;
12253             /* Swap TYPE0 with TYPE1 and OP0 with OP1  */
12254             tmp = type0; type0 = type1; type1 = tmp;
12255             tmp = op0; op0 = op1; op1 = tmp;
12256           }
12257
12258         if (TREE_CODE (type0) == INTEGER_TYPE
12259             && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
12260           {
12261             if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0, false))
12262               {
12263                 if (complain)
12264                   error_at (loc, "conversion of scalar %qT to vector %qT "
12265                             "involves truncation", type0, type1);
12266                 return stv_error;
12267               }
12268             return ret;
12269           }
12270         else if (!integer_only_op
12271                     /* Allow integer --> real conversion if safe.  */
12272                  && (TREE_CODE (type0) == REAL_TYPE
12273                      || TREE_CODE (type0) == INTEGER_TYPE)
12274                  && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
12275           {
12276             if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0, false))
12277               {
12278                 if (complain)
12279                   error_at (loc, "conversion of scalar %qT to vector %qT "
12280                             "involves truncation", type0, type1);
12281                 return stv_error;
12282               }
12283             return ret;
12284           }
12285       default:
12286         break;
12287     }
12288
12289   return stv_nothing;
12290 }
12291
12292 /* Return true iff ALIGN is an integral constant that is a fundamental
12293    alignment, as defined by [basic.align] in the c++-11
12294    specifications.
12295
12296    That is:
12297
12298        [A fundamental alignment is represented by an alignment less than or
12299         equal to the greatest alignment supported by the implementation
12300         in all contexts, which is equal to
12301         alignof(max_align_t)].  */
12302
12303 bool
12304 cxx_fundamental_alignment_p  (unsigned align)
12305 {
12306   return (align <=  MAX (TYPE_ALIGN (long_long_integer_type_node),
12307                          TYPE_ALIGN (long_double_type_node)));
12308 }
12309
12310 /* Return true if T is a pointer to a zero-sized aggregate.  */
12311
12312 bool
12313 pointer_to_zero_sized_aggr_p (tree t)
12314 {
12315   if (!POINTER_TYPE_P (t))
12316     return false;
12317   t = TREE_TYPE (t);
12318   return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
12319 }
12320
12321 #include "gt-c-family-c-common.h"