9746504195b26512160db11e4f87b8110b828919
[platform/upstream/gcc.git] / gcc / c-family / c-common.cc
1 /* Subroutines shared by all languages that are variants of C.
2    Copyright (C) 1992-2022 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 "target.h"
26 #include "function.h"
27 #include "tree.h"
28 #include "memmodel.h"
29 #include "c-common.h"
30 #include "gimple-expr.h"
31 #include "tm_p.h"
32 #include "stringpool.h"
33 #include "cgraph.h"
34 #include "diagnostic.h"
35 #include "intl.h"
36 #include "stor-layout.h"
37 #include "calls.h"
38 #include "attribs.h"
39 #include "varasm.h"
40 #include "trans-mem.h"
41 #include "c-objc.h"
42 #include "common/common-target.h"
43 #include "langhooks.h"
44 #include "tree-inline.h"
45 #include "toplev.h"
46 #include "tree-iterator.h"
47 #include "opts.h"
48 #include "gimplify.h"
49 #include "substring-locations.h"
50 #include "spellcheck.h"
51 #include "c-spellcheck.h"
52 #include "selftest.h"
53 #include "debug.h"
54 #include "tree-vector-builder.h"
55 #include "vec-perm-indices.h"
56
57 cpp_reader *parse_in;           /* Declared in c-pragma.h.  */
58
59 /* Mode used to build pointers (VOIDmode means ptr_mode).  */
60
61 machine_mode c_default_pointer_mode = VOIDmode;
62
63 /* The following symbols are subsumed in the c_global_trees array, and
64    listed here individually for documentation purposes.
65
66    INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
67
68         tree short_integer_type_node;
69         tree long_integer_type_node;
70         tree long_long_integer_type_node;
71
72         tree short_unsigned_type_node;
73         tree long_unsigned_type_node;
74         tree long_long_unsigned_type_node;
75
76         tree truthvalue_type_node;
77         tree truthvalue_false_node;
78         tree truthvalue_true_node;
79
80         tree ptrdiff_type_node;
81
82         tree unsigned_char_type_node;
83         tree signed_char_type_node;
84         tree wchar_type_node;
85
86         tree char8_type_node;
87         tree char16_type_node;
88         tree char32_type_node;
89
90         tree float_type_node;
91         tree double_type_node;
92         tree long_double_type_node;
93
94         tree complex_integer_type_node;
95         tree complex_float_type_node;
96         tree complex_double_type_node;
97         tree complex_long_double_type_node;
98
99         tree dfloat32_type_node;
100         tree dfloat64_type_node;
101         tree_dfloat128_type_node;
102
103         tree intQI_type_node;
104         tree intHI_type_node;
105         tree intSI_type_node;
106         tree intDI_type_node;
107         tree intTI_type_node;
108
109         tree unsigned_intQI_type_node;
110         tree unsigned_intHI_type_node;
111         tree unsigned_intSI_type_node;
112         tree unsigned_intDI_type_node;
113         tree unsigned_intTI_type_node;
114
115         tree widest_integer_literal_type_node;
116         tree widest_unsigned_literal_type_node;
117
118    Nodes for types `void *' and `const void *'.
119
120         tree ptr_type_node, const_ptr_type_node;
121
122    Nodes for types `char *' and `const char *'.
123
124         tree string_type_node, const_string_type_node;
125
126    Type `char[SOMENUMBER]'.
127    Used when an array of char is needed and the size is irrelevant.
128
129         tree char_array_type_node;
130
131    Type `wchar_t[SOMENUMBER]' or something like it.
132    Used when a wide string literal is created.
133
134         tree wchar_array_type_node;
135
136    Type `char8_t[SOMENUMBER]' or something like it.
137    Used when a UTF-8 string literal is created.
138
139         tree char8_array_type_node;
140
141    Type `char16_t[SOMENUMBER]' or something like it.
142    Used when a UTF-16 string literal is created.
143
144         tree char16_array_type_node;
145
146    Type `char32_t[SOMENUMBER]' or something like it.
147    Used when a UTF-32 string literal is created.
148
149         tree char32_array_type_node;
150
151    Type `int ()' -- used for implicit declaration of functions.
152
153         tree default_function_type;
154
155    A VOID_TYPE node, packaged in a TREE_LIST.
156
157         tree void_list_node;
158
159   The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
160   and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
161   VAR_DECLS, but C++ does.)
162
163         tree function_name_decl_node;
164         tree pretty_function_name_decl_node;
165         tree c99_function_name_decl_node;
166
167   Stack of nested function name VAR_DECLs.
168
169         tree saved_function_name_decls;
170
171 */
172
173 tree c_global_trees[CTI_MAX];
174 \f
175 /* Switches common to the C front ends.  */
176
177 /* Nonzero means don't output line number information.  */
178
179 char flag_no_line_commands;
180
181 /* Nonzero causes -E output not to be done, but directives such as
182    #define that have side effects are still obeyed.  */
183
184 char flag_no_output;
185
186 /* Nonzero means dump macros in some fashion.  */
187
188 char flag_dump_macros;
189
190 /* Nonzero means pass #include lines through to the output.  */
191
192 char flag_dump_includes;
193
194 /* Nonzero means process PCH files while preprocessing.  */
195
196 bool flag_pch_preprocess;
197
198 /* The file name to which we should write a precompiled header, or
199    NULL if no header will be written in this compile.  */
200
201 const char *pch_file;
202
203 /* Nonzero if an ISO standard was selected.  It rejects macros in the
204    user's namespace.  */
205 int flag_iso;
206
207 /* C/ObjC language option variables.  */
208
209
210 /* Nonzero means allow type mismatches in conditional expressions;
211    just make their values `void'.  */
212
213 int flag_cond_mismatch;
214
215 /* Nonzero means enable C89 Amendment 1 features.  */
216
217 int flag_isoc94;
218
219 /* Nonzero means use the ISO C99 (or C11) dialect of C.  */
220
221 int flag_isoc99;
222
223 /* Nonzero means use the ISO C11 dialect of C.  */
224
225 int flag_isoc11;
226
227 /* Nonzero means use the ISO C2X dialect of C.  */
228
229 int flag_isoc2x;
230
231 /* Nonzero means that we have builtin functions, and main is an int.  */
232
233 int flag_hosted = 1;
234
235
236 /* ObjC language option variables.  */
237
238
239 /* Tells the compiler that this is a special run.  Do not perform any
240    compiling, instead we are to test some platform dependent features
241    and output a C header file with appropriate definitions.  */
242
243 int print_struct_values;
244
245 /* Tells the compiler what is the constant string class for ObjC.  */
246
247 const char *constant_string_class_name;
248
249
250 /* C++ language option variables.  */
251
252 /* The reference version of the ABI for -Wabi.  */
253
254 int warn_abi_version = -1;
255
256 /* The C++ dialect being used.  Default set in c_common_post_options.  */
257
258 enum cxx_dialect cxx_dialect = cxx_unset;
259
260 /* Maximum template instantiation depth.  This limit exists to limit the
261    time it takes to notice excessively recursive template instantiations.
262
263    The default is lower than the 1024 recommended by the C++0x standard
264    because G++ runs out of stack before 1024 with highly recursive template
265    argument deduction substitution (g++.dg/cpp0x/enum11.C).  */
266
267 int max_tinst_depth = 900;
268
269 /* The elements of `ridpointers' are identifier nodes for the reserved
270    type names and storage classes.  It is indexed by a RID_... value.  */
271 tree *ridpointers;
272
273 tree (*make_fname_decl) (location_t, tree, int);
274
275 /* Nonzero means don't warn about problems that occur when the code is
276    executed.  */
277 int c_inhibit_evaluation_warnings;
278
279 /* Whether we are building a boolean conversion inside
280    convert_for_assignment, or some other late binary operation.  If
281    build_binary_op is called for C (from code shared by C and C++) in
282    this case, then the operands have already been folded and the
283    result will not be folded again, so C_MAYBE_CONST_EXPR should not
284    be generated.  */
285 bool in_late_binary_op;
286
287 /* Depending on which phase of processing we are in, we may need
288    to prefer input_location to libcpp's locations.  (Specifically,
289    after the C++ lexer is done lexing tokens, but prior to calling
290    cpp_finish (), we need to do so.  */
291 bool override_libcpp_locations;
292
293 /* Information about how a function name is generated.  */
294 struct fname_var_t
295 {
296   tree *const decl;     /* pointer to the VAR_DECL.  */
297   const unsigned rid;   /* RID number for the identifier.  */
298   const int pretty;     /* How pretty is it? */
299 };
300
301 /* The three ways of getting then name of the current function.  */
302
303 const struct fname_var_t fname_vars[] =
304 {
305   /* C99 compliant __func__, must be first.  */
306   {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
307   /* GCC __FUNCTION__ compliant.  */
308   {&function_name_decl_node, RID_FUNCTION_NAME, 0},
309   /* GCC __PRETTY_FUNCTION__ compliant.  */
310   {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
311   {NULL, 0, 0},
312 };
313
314 /* Global visibility options.  */
315 struct visibility_flags visibility_options;
316
317 static tree check_case_value (location_t, tree);
318
319
320 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
321 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
322
323 /* Reserved words.  The third field is a mask: keywords are disabled
324    if they match the mask.
325
326    Masks for languages:
327    C --std=c89: D_C99 | D_C2X | D_CXXONLY | D_OBJC | D_CXX_OBJC
328    C --std=c99: D_C2X | D_CXXONLY | D_OBJC
329    C --std=c17: D_C2X | D_CXXONLY | D_OBJC
330    C --std=c2x: D_CXXONLY | D_OBJC
331    ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
332    C++ --std=c++98: D_CONLY | D_CXX11 | D_CXX20 | D_OBJC
333    C++ --std=c++11: D_CONLY | D_CXX20 | D_OBJC
334    C++ --std=c++20: D_CONLY | D_OBJC
335    ObjC++ is like C++ except that D_OBJC is not set
336
337    If -fno-asm is used, D_ASM is added to the mask.  If
338    -fno-gnu-keywords is used, D_EXT is added.  If -fno-asm and C in
339    C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
340    In C with -Wc++-compat, we warn if D_CXXWARN is set.
341
342    Note the complication of the D_CXX_OBJC keywords.  These are
343    reserved words such as 'class'.  In C++, 'class' is a reserved
344    word.  In Objective-C++ it is too.  In Objective-C, it is a
345    reserved word too, but only if it follows an '@' sign.
346 */
347 const struct c_common_resword c_common_reswords[] =
348 {
349   { "_Alignas",         RID_ALIGNAS,   D_CONLY },
350   { "_Alignof",         RID_ALIGNOF,   D_CONLY },
351   { "_Atomic",          RID_ATOMIC,    D_CONLY },
352   { "_Bool",            RID_BOOL,      D_CONLY },
353   { "_Complex",         RID_COMPLEX,    0 },
354   { "_Imaginary",       RID_IMAGINARY, D_CONLY },
355   { "_Float16",         RID_FLOAT16,   D_CONLY },
356   { "_Float32",         RID_FLOAT32,   D_CONLY },
357   { "_Float64",         RID_FLOAT64,   D_CONLY },
358   { "_Float128",        RID_FLOAT128,  D_CONLY },
359   { "_Float32x",        RID_FLOAT32X,  D_CONLY },
360   { "_Float64x",        RID_FLOAT64X,  D_CONLY },
361   { "_Float128x",       RID_FLOAT128X, D_CONLY },
362   { "_Decimal32",       RID_DFLOAT32,  D_CONLY },
363   { "_Decimal64",       RID_DFLOAT64,  D_CONLY },
364   { "_Decimal128",      RID_DFLOAT128, D_CONLY },
365   { "_Fract",           RID_FRACT,     D_CONLY | D_EXT },
366   { "_Accum",           RID_ACCUM,     D_CONLY | D_EXT },
367   { "_Sat",             RID_SAT,       D_CONLY | D_EXT },
368   { "_Static_assert",   RID_STATIC_ASSERT, D_CONLY },
369   { "_Noreturn",        RID_NORETURN,  D_CONLY },
370   { "_Generic",         RID_GENERIC,   D_CONLY },
371   { "_Thread_local",    RID_THREAD,    D_CONLY },
372   { "__FUNCTION__",     RID_FUNCTION_NAME, 0 },
373   { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
374   { "__alignof",        RID_ALIGNOF,    0 },
375   { "__alignof__",      RID_ALIGNOF,    0 },
376   { "__asm",            RID_ASM,        0 },
377   { "__asm__",          RID_ASM,        0 },
378   { "__attribute",      RID_ATTRIBUTE,  0 },
379   { "__attribute__",    RID_ATTRIBUTE,  0 },
380   { "__auto_type",      RID_AUTO_TYPE,  D_CONLY },
381   { "__bases",          RID_BASES, D_CXXONLY },
382   { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
383   { "__builtin_bit_cast", RID_BUILTIN_BIT_CAST, D_CXXONLY },
384   { "__builtin_call_with_static_chain",
385     RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
386   { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
387   { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
388   { "__builtin_convertvector", RID_BUILTIN_CONVERTVECTOR, 0 },
389   { "__builtin_has_attribute", RID_BUILTIN_HAS_ATTRIBUTE, 0 },
390   { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
391   { "__builtin_assoc_barrier", RID_BUILTIN_ASSOC_BARRIER, 0 },
392   { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
393   { "__builtin_shufflevector", RID_BUILTIN_SHUFFLEVECTOR, 0 },
394   { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
395   { "__builtin_offsetof", RID_OFFSETOF, 0 },
396   { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
397   { "__builtin_va_arg", RID_VA_ARG,     0 },
398   { "__complex",        RID_COMPLEX,    0 },
399   { "__complex__",      RID_COMPLEX,    0 },
400   { "__const",          RID_CONST,      0 },
401   { "__const__",        RID_CONST,      0 },
402   { "__constinit",      RID_CONSTINIT,  D_CXXONLY },
403   { "__decltype",       RID_DECLTYPE,   D_CXXONLY },
404   { "__direct_bases",   RID_DIRECT_BASES, D_CXXONLY },
405   { "__extension__",    RID_EXTENSION,  0 },
406   { "__func__",         RID_C99_FUNCTION_NAME, 0 },
407   { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
408   { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
409   { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
410   { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
411   { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
412   { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
413   { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
414   { "__has_unique_object_representations", RID_HAS_UNIQUE_OBJ_REPRESENTATIONS,
415                                         D_CXXONLY },
416   { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
417   { "__imag",           RID_IMAGPART,   0 },
418   { "__imag__",         RID_IMAGPART,   0 },
419   { "__inline",         RID_INLINE,     0 },
420   { "__inline__",       RID_INLINE,     0 },
421   { "__is_abstract",    RID_IS_ABSTRACT, D_CXXONLY },
422   { "__is_aggregate",   RID_IS_AGGREGATE, D_CXXONLY },
423   { "__is_base_of",     RID_IS_BASE_OF, D_CXXONLY },
424   { "__is_class",       RID_IS_CLASS,   D_CXXONLY },
425   { "__is_empty",       RID_IS_EMPTY,   D_CXXONLY },
426   { "__is_enum",        RID_IS_ENUM,    D_CXXONLY },
427   { "__is_final",       RID_IS_FINAL,   D_CXXONLY },
428   { "__is_layout_compatible", RID_IS_LAYOUT_COMPATIBLE, D_CXXONLY },
429   { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
430   { "__is_pointer_interconvertible_base_of",
431                         RID_IS_POINTER_INTERCONVERTIBLE_BASE_OF, D_CXXONLY },
432   { "__is_pod",         RID_IS_POD,     D_CXXONLY },
433   { "__is_polymorphic", RID_IS_POLYMORPHIC, D_CXXONLY },
434   { "__is_same",     RID_IS_SAME_AS, D_CXXONLY },
435   { "__is_same_as",     RID_IS_SAME_AS, D_CXXONLY },
436   { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
437   { "__is_trivial",     RID_IS_TRIVIAL, D_CXXONLY },
438   { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
439   { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
440   { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
441   { "__is_union",       RID_IS_UNION,   D_CXXONLY },
442   { "__label__",        RID_LABEL,      0 },
443   { "__null",           RID_NULL,       0 },
444   { "__real",           RID_REALPART,   0 },
445   { "__real__",         RID_REALPART,   0 },
446   { "__restrict",       RID_RESTRICT,   0 },
447   { "__restrict__",     RID_RESTRICT,   0 },
448   { "__signed",         RID_SIGNED,     0 },
449   { "__signed__",       RID_SIGNED,     0 },
450   { "__thread",         RID_THREAD,     0 },
451   { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
452   { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
453   { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
454   { "__typeof",         RID_TYPEOF,     0 },
455   { "__typeof__",       RID_TYPEOF,     0 },
456   { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
457   { "__volatile",       RID_VOLATILE,   0 },
458   { "__volatile__",     RID_VOLATILE,   0 },
459   { "__GIMPLE",         RID_GIMPLE,     D_CONLY },
460   { "__PHI",            RID_PHI,        D_CONLY },
461   { "__RTL",            RID_RTL,        D_CONLY },
462   { "alignas",          RID_ALIGNAS,    D_CXXONLY | D_CXX11 | D_CXXWARN },
463   { "alignof",          RID_ALIGNOF,    D_CXXONLY | D_CXX11 | D_CXXWARN },
464   { "asm",              RID_ASM,        D_ASM },
465   { "auto",             RID_AUTO,       0 },
466   { "bool",             RID_BOOL,       D_CXXONLY | D_CXXWARN },
467   { "break",            RID_BREAK,      0 },
468   { "case",             RID_CASE,       0 },
469   { "catch",            RID_CATCH,      D_CXX_OBJC | D_CXXWARN },
470   { "char",             RID_CHAR,       0 },
471   { "char8_t",          RID_CHAR8,      D_CXX_CHAR8_T_FLAGS | D_CXXWARN },
472   { "char16_t",         RID_CHAR16,     D_CXXONLY | D_CXX11 | D_CXXWARN },
473   { "char32_t",         RID_CHAR32,     D_CXXONLY | D_CXX11 | D_CXXWARN },
474   { "class",            RID_CLASS,      D_CXX_OBJC | D_CXXWARN },
475   { "const",            RID_CONST,      0 },
476   { "consteval",        RID_CONSTEVAL,  D_CXXONLY | D_CXX20 | D_CXXWARN },
477   { "constexpr",        RID_CONSTEXPR,  D_CXXONLY | D_CXX11 | D_CXXWARN },
478   { "constinit",        RID_CONSTINIT,  D_CXXONLY | D_CXX20 | D_CXXWARN },
479   { "const_cast",       RID_CONSTCAST,  D_CXXONLY | D_CXXWARN },
480   { "continue",         RID_CONTINUE,   0 },
481   { "decltype",         RID_DECLTYPE,   D_CXXONLY | D_CXX11 | D_CXXWARN },
482   { "default",          RID_DEFAULT,    0 },
483   { "delete",           RID_DELETE,     D_CXXONLY | D_CXXWARN },
484   { "do",               RID_DO,         0 },
485   { "double",           RID_DOUBLE,     0 },
486   { "dynamic_cast",     RID_DYNCAST,    D_CXXONLY | D_CXXWARN },
487   { "else",             RID_ELSE,       0 },
488   { "enum",             RID_ENUM,       0 },
489   { "explicit",         RID_EXPLICIT,   D_CXXONLY | D_CXXWARN },
490   { "export",           RID_EXPORT,     D_CXXONLY | D_CXXWARN },
491   { "extern",           RID_EXTERN,     0 },
492   { "false",            RID_FALSE,      D_CXXONLY | D_CXXWARN },
493   { "float",            RID_FLOAT,      0 },
494   { "for",              RID_FOR,        0 },
495   { "friend",           RID_FRIEND,     D_CXXONLY | D_CXXWARN },
496   { "goto",             RID_GOTO,       0 },
497   { "if",               RID_IF,         0 },
498   { "inline",           RID_INLINE,     D_EXT89 },
499   { "int",              RID_INT,        0 },
500   { "long",             RID_LONG,       0 },
501   { "mutable",          RID_MUTABLE,    D_CXXONLY | D_CXXWARN },
502   { "namespace",        RID_NAMESPACE,  D_CXXONLY | D_CXXWARN },
503   { "new",              RID_NEW,        D_CXXONLY | D_CXXWARN },
504   { "noexcept",         RID_NOEXCEPT,   D_CXXONLY | D_CXX11 | D_CXXWARN },
505   { "nullptr",          RID_NULLPTR,    D_C2X | D_CXX11 | D_CXXWARN },
506   { "operator",         RID_OPERATOR,   D_CXXONLY | D_CXXWARN },
507   { "private",          RID_PRIVATE,    D_CXX_OBJC | D_CXXWARN },
508   { "protected",        RID_PROTECTED,  D_CXX_OBJC | D_CXXWARN },
509   { "public",           RID_PUBLIC,     D_CXX_OBJC | D_CXXWARN },
510   { "register",         RID_REGISTER,   0 },
511   { "reinterpret_cast", RID_REINTCAST,  D_CXXONLY | D_CXXWARN },
512   { "restrict",         RID_RESTRICT,   D_CONLY | D_C99 },
513   { "return",           RID_RETURN,     0 },
514   { "short",            RID_SHORT,      0 },
515   { "signed",           RID_SIGNED,     0 },
516   { "sizeof",           RID_SIZEOF,     0 },
517   { "static",           RID_STATIC,     0 },
518   { "static_assert",    RID_STATIC_ASSERT, D_CXXONLY | D_CXX11 | D_CXXWARN },
519   { "static_cast",      RID_STATCAST,   D_CXXONLY | D_CXXWARN },
520   { "struct",           RID_STRUCT,     0 },
521   { "switch",           RID_SWITCH,     0 },
522   { "template",         RID_TEMPLATE,   D_CXXONLY | D_CXXWARN },
523   { "this",             RID_THIS,       D_CXXONLY | D_CXXWARN },
524   { "thread_local",     RID_THREAD,     D_CXXONLY | D_CXX11 | D_CXXWARN },
525   { "throw",            RID_THROW,      D_CXX_OBJC | D_CXXWARN },
526   { "true",             RID_TRUE,       D_CXXONLY | D_CXXWARN },
527   { "try",              RID_TRY,        D_CXX_OBJC | D_CXXWARN },
528   { "typedef",          RID_TYPEDEF,    0 },
529   { "typename",         RID_TYPENAME,   D_CXXONLY | D_CXXWARN },
530   { "typeid",           RID_TYPEID,     D_CXXONLY | D_CXXWARN },
531   { "typeof",           RID_TYPEOF,     D_ASM | D_EXT },
532   { "union",            RID_UNION,      0 },
533   { "unsigned",         RID_UNSIGNED,   0 },
534   { "using",            RID_USING,      D_CXXONLY | D_CXXWARN },
535   { "virtual",          RID_VIRTUAL,    D_CXXONLY | D_CXXWARN },
536   { "void",             RID_VOID,       0 },
537   { "volatile",         RID_VOLATILE,   0 },
538   { "wchar_t",          RID_WCHAR,      D_CXXONLY },
539   { "while",            RID_WHILE,      0 },
540   { "__is_assignable", RID_IS_ASSIGNABLE, D_CXXONLY },
541   { "__is_constructible", RID_IS_CONSTRUCTIBLE, D_CXXONLY },
542   { "__is_nothrow_assignable", RID_IS_NOTHROW_ASSIGNABLE, D_CXXONLY },
543   { "__is_nothrow_constructible", RID_IS_NOTHROW_CONSTRUCTIBLE, D_CXXONLY },
544   { "__reference_constructs_from_temporary", RID_REF_CONSTRUCTS_FROM_TEMPORARY,
545                                         D_CXXONLY },
546   { "__reference_converts_from_temporary", RID_REF_CONVERTS_FROM_TEMPORARY,
547                                         D_CXXONLY },
548
549   /* C++ transactional memory.  */
550   { "synchronized",     RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
551   { "atomic_noexcept",  RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
552   { "atomic_cancel",    RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
553   { "atomic_commit",    RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
554
555   /* Concepts-related keywords */
556   { "concept",          RID_CONCEPT,    D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
557   { "requires",         RID_REQUIRES,   D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
558
559   /* Modules-related keywords, these are internal unspellable tokens,
560      created by the preprocessor.  */
561   { "module ",          RID__MODULE,    D_CXX_MODULES_FLAGS | D_CXXWARN },
562   { "import ",          RID__IMPORT,    D_CXX_MODULES_FLAGS | D_CXXWARN },
563   { "export ",          RID__EXPORT,    D_CXX_MODULES_FLAGS | D_CXXWARN },
564
565   /* Coroutines-related keywords */
566   { "co_await",         RID_CO_AWAIT,   D_CXX_COROUTINES_FLAGS | D_CXXWARN },
567   { "co_yield",         RID_CO_YIELD,   D_CXX_COROUTINES_FLAGS | D_CXXWARN },
568   { "co_return",        RID_CO_RETURN,  D_CXX_COROUTINES_FLAGS | D_CXXWARN },
569
570   /* These Objective-C keywords are recognized only immediately after
571      an '@'.  */
572   { "compatibility_alias", RID_AT_ALIAS,        D_OBJC },
573   { "defs",             RID_AT_DEFS,            D_OBJC },
574   { "encode",           RID_AT_ENCODE,          D_OBJC },
575   { "end",              RID_AT_END,             D_OBJC },
576   { "implementation",   RID_AT_IMPLEMENTATION,  D_OBJC },
577   { "interface",        RID_AT_INTERFACE,       D_OBJC },
578   { "protocol",         RID_AT_PROTOCOL,        D_OBJC },
579   { "selector",         RID_AT_SELECTOR,        D_OBJC },
580   { "finally",          RID_AT_FINALLY,         D_OBJC },
581   { "optional",         RID_AT_OPTIONAL,        D_OBJC },
582   { "required",         RID_AT_REQUIRED,        D_OBJC },
583   { "property",         RID_AT_PROPERTY,        D_OBJC },
584   { "package",          RID_AT_PACKAGE,         D_OBJC },
585   { "synthesize",       RID_AT_SYNTHESIZE,      D_OBJC },
586   { "dynamic",          RID_AT_DYNAMIC,         D_OBJC },
587   /* These are recognized only in protocol-qualifier context
588      (see above) */
589   { "bycopy",           RID_BYCOPY,             D_OBJC },
590   { "byref",            RID_BYREF,              D_OBJC },
591   { "in",               RID_IN,                 D_OBJC },
592   { "inout",            RID_INOUT,              D_OBJC },
593   { "oneway",           RID_ONEWAY,             D_OBJC },
594   { "out",              RID_OUT,                D_OBJC },
595   /* These are recognized inside a property attribute list */
596   { "assign",           RID_ASSIGN,             D_OBJC },
597   { "atomic",           RID_PROPATOMIC,         D_OBJC },
598   { "copy",             RID_COPY,               D_OBJC },
599   { "getter",           RID_GETTER,             D_OBJC },
600   { "nonatomic",        RID_NONATOMIC,          D_OBJC },
601   { "readonly",         RID_READONLY,           D_OBJC },
602   { "readwrite",        RID_READWRITE,          D_OBJC },
603   { "retain",           RID_RETAIN,             D_OBJC },
604   { "setter",           RID_SETTER,             D_OBJC },
605   /* These are Objective C implementation of nullability, accepted only in
606      specific contexts.  */
607   { "null_unspecified", RID_NULL_UNSPECIFIED,   D_OBJC },
608   { "nullable",         RID_NULLABLE,           D_OBJC },
609   { "nonnull",          RID_NONNULL,            D_OBJC },
610   { "null_resettable",  RID_NULL_RESETTABLE,    D_OBJC },
611 };
612
613 const unsigned int num_c_common_reswords = ARRAY_SIZE (c_common_reswords);
614
615 /* Return identifier for address space AS.  */
616
617 const char *
618 c_addr_space_name (addr_space_t as)
619 {
620   int rid = RID_FIRST_ADDR_SPACE + as;
621   gcc_assert (ridpointers [rid]);
622   return IDENTIFIER_POINTER (ridpointers [rid]);
623 }
624
625 /* Push current bindings for the function name VAR_DECLS.  */
626
627 void
628 start_fname_decls (void)
629 {
630   unsigned ix;
631   tree saved = NULL_TREE;
632
633   for (ix = 0; fname_vars[ix].decl; ix++)
634     {
635       tree decl = *fname_vars[ix].decl;
636
637       if (decl)
638         {
639           saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
640                              saved);
641           *fname_vars[ix].decl = NULL_TREE;
642         }
643     }
644   if (saved || saved_function_name_decls)
645     /* Normally they'll have been NULL, so only push if we've got a
646        stack, or they are non-NULL.  */
647     saved_function_name_decls = tree_cons (saved, NULL_TREE,
648                                            saved_function_name_decls);
649 }
650
651 /* Finish up the current bindings, adding them into the current function's
652    statement tree.  This must be done _before_ finish_stmt_tree is called.
653    If there is no current function, we must be at file scope and no statements
654    are involved. Pop the previous bindings.  */
655
656 void
657 finish_fname_decls (void)
658 {
659   unsigned ix;
660   tree stmts = NULL_TREE;
661   tree stack = saved_function_name_decls;
662
663   for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
664     append_to_statement_list (TREE_VALUE (stack), &stmts);
665
666   if (stmts)
667     {
668       tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
669
670       if (TREE_CODE (*bodyp) == BIND_EXPR)
671         bodyp = &BIND_EXPR_BODY (*bodyp);
672
673       append_to_statement_list_force (*bodyp, &stmts);
674       *bodyp = stmts;
675     }
676
677   for (ix = 0; fname_vars[ix].decl; ix++)
678     *fname_vars[ix].decl = NULL_TREE;
679
680   if (stack)
681     {
682       /* We had saved values, restore them.  */
683       tree saved;
684
685       for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
686         {
687           tree decl = TREE_PURPOSE (saved);
688           unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
689
690           *fname_vars[ix].decl = decl;
691         }
692       stack = TREE_CHAIN (stack);
693     }
694   saved_function_name_decls = stack;
695 }
696
697 /* Return the text name of the current function, suitably prettified
698    by PRETTY_P.  Return string must be freed by caller.  */
699
700 const char *
701 fname_as_string (int pretty_p)
702 {
703   const char *name = "top level";
704   char *namep;
705   int vrb = 2, len;
706   cpp_string cstr = { 0, 0 }, strname;
707
708   if (!pretty_p)
709     {
710       name = "";
711       vrb = 0;
712     }
713
714   if (current_function_decl)
715     name = lang_hooks.decl_printable_name (current_function_decl, vrb);
716
717   len = strlen (name) + 3; /* Two for '"'s.  One for NULL.  */
718
719   namep = XNEWVEC (char, len);
720   snprintf (namep, len, "\"%s\"", name);
721   strname.text = (unsigned char *) namep;
722   strname.len = len - 1;
723
724   if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
725     {
726       XDELETEVEC (namep);
727       return (const char *) cstr.text;
728     }
729
730   return namep;
731 }
732
733 /* Return the VAR_DECL for a const char array naming the current
734    function. If the VAR_DECL has not yet been created, create it
735    now. RID indicates how it should be formatted and IDENTIFIER_NODE
736    ID is its name (unfortunately C and C++ hold the RID values of
737    keywords in different places, so we can't derive RID from ID in
738    this language independent code. LOC is the location of the
739    function.  */
740
741 tree
742 fname_decl (location_t loc, unsigned int rid, tree id)
743 {
744   unsigned ix;
745   tree decl = NULL_TREE;
746
747   for (ix = 0; fname_vars[ix].decl; ix++)
748     if (fname_vars[ix].rid == rid)
749       break;
750
751   decl = *fname_vars[ix].decl;
752   if (!decl)
753     {
754       /* If a tree is built here, it would normally have the lineno of
755          the current statement.  Later this tree will be moved to the
756          beginning of the function and this line number will be wrong.
757          To avoid this problem set the lineno to 0 here; that prevents
758          it from appearing in the RTL.  */
759       tree stmts;
760       location_t saved_location = input_location;
761       input_location = UNKNOWN_LOCATION;
762
763       stmts = push_stmt_list ();
764       decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
765       stmts = pop_stmt_list (stmts);
766       if (!IS_EMPTY_STMT (stmts))
767         saved_function_name_decls
768           = tree_cons (decl, stmts, saved_function_name_decls);
769       *fname_vars[ix].decl = decl;
770       input_location = saved_location;
771     }
772   if (!ix && !current_function_decl)
773     pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
774
775   return decl;
776 }
777
778 /* Given a STRING_CST, give it a suitable array-of-chars data type.  */
779
780 tree
781 fix_string_type (tree value)
782 {
783   int length = TREE_STRING_LENGTH (value);
784   int nchars, charsz;
785   tree e_type, i_type, a_type;
786
787   /* Compute the number of elements, for the array type.  */
788   if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
789     {
790       charsz = 1;
791       e_type = char_type_node;
792     }
793   else if (flag_char8_t && TREE_TYPE (value) == char8_array_type_node)
794     {
795       charsz = TYPE_PRECISION (char8_type_node) / BITS_PER_UNIT;
796       e_type = char8_type_node;
797     }
798   else if (TREE_TYPE (value) == char16_array_type_node)
799     {
800       charsz = TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT;
801       e_type = char16_type_node;
802     }
803   else if (TREE_TYPE (value) == char32_array_type_node)
804     {
805       charsz = TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT;
806       e_type = char32_type_node;
807     }
808   else
809     {
810       charsz = TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT;
811       e_type = wchar_type_node;
812     }
813
814   /* This matters only for targets where ssizetype has smaller precision
815      than 32 bits.  */
816   if (wi::lts_p (wi::to_wide (TYPE_MAX_VALUE (ssizetype)), length))
817     {
818       error ("size of string literal is too large");
819       length = tree_to_shwi (TYPE_MAX_VALUE (ssizetype)) / charsz * charsz;
820       char *str = CONST_CAST (char *, TREE_STRING_POINTER (value));
821       memset (str + length, '\0',
822               MIN (TREE_STRING_LENGTH (value) - length, charsz));
823       TREE_STRING_LENGTH (value) = length;
824     }
825   nchars = length / charsz;
826
827   /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits).  The analogous
828      limit in C++98 Annex B is very large (65536) and is not normative,
829      so we do not diagnose it (warn_overlength_strings is forced off
830      in c_common_post_options).  */
831   if (warn_overlength_strings)
832     {
833       const int nchars_max = flag_isoc99 ? 4095 : 509;
834       const int relevant_std = flag_isoc99 ? 99 : 90;
835       if (nchars - 1 > nchars_max)
836         /* Translators: The %d after 'ISO C' will be 90 or 99.  Do not
837            separate the %d from the 'C'.  'ISO' should not be
838            translated, but it may be moved after 'C%d' in languages
839            where modifiers follow nouns.  */
840         pedwarn (input_location, OPT_Woverlength_strings,
841                  "string length %qd is greater than the length %qd "
842                  "ISO C%d compilers are required to support",
843                  nchars - 1, nchars_max, relevant_std);
844     }
845
846   /* Create the array type for the string constant.  The ISO C++
847      standard says that a string literal has type `const char[N]' or
848      `const wchar_t[N]'.  We use the same logic when invoked as a C
849      front-end with -Wwrite-strings.
850      ??? We should change the type of an expression depending on the
851      state of a warning flag.  We should just be warning -- see how
852      this is handled in the C++ front-end for the deprecated implicit
853      conversion from string literals to `char*' or `wchar_t*'.
854
855      The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
856      array type being the unqualified version of that type.
857      Therefore, if we are constructing an array of const char, we must
858      construct the matching unqualified array type first.  The C front
859      end does not require this, but it does no harm, so we do it
860      unconditionally.  */
861   i_type = build_index_type (size_int (nchars - 1));
862   a_type = build_array_type (e_type, i_type);
863   if (c_dialect_cxx() || warn_write_strings)
864     a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
865
866   TREE_TYPE (value) = a_type;
867   TREE_CONSTANT (value) = 1;
868   TREE_READONLY (value) = 1;
869   TREE_STATIC (value) = 1;
870   return value;
871 }
872
873 /* Given a string of type STRING_TYPE, determine what kind of string
874    token would give an equivalent execution encoding: CPP_STRING,
875    CPP_STRING16, or CPP_STRING32.  Return CPP_OTHER in case of error.
876    This may not be exactly the string token type that initially created
877    the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
878    string type, and CPP_UTF8STRING is indistinguishable from CPP_STRING
879    at this point.
880
881    This effectively reverses part of the logic in lex_string and
882    fix_string_type.  */
883
884 static enum cpp_ttype
885 get_cpp_ttype_from_string_type (tree string_type)
886 {
887   gcc_assert (string_type);
888   if (TREE_CODE (string_type) == POINTER_TYPE)
889     string_type = TREE_TYPE (string_type);
890
891   if (TREE_CODE (string_type) != ARRAY_TYPE)
892     return CPP_OTHER;
893
894   tree element_type = TREE_TYPE (string_type);
895   if (TREE_CODE (element_type) != INTEGER_TYPE)
896     return CPP_OTHER;
897
898   int bits_per_character = TYPE_PRECISION (element_type);
899   switch (bits_per_character)
900     {
901     case 8:
902       return CPP_STRING;  /* It could have also been CPP_UTF8STRING.  */
903     case 16:
904       return CPP_STRING16;
905     case 32:
906       return CPP_STRING32;
907     }
908
909   return CPP_OTHER;
910 }
911
912 /* The global record of string concatentations, for use in
913    extracting locations within string literals.  */
914
915 GTY(()) string_concat_db *g_string_concat_db;
916
917 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION.  */
918
919 const char *
920 c_get_substring_location (const substring_loc &substr_loc,
921                           location_t *out_loc)
922 {
923   enum cpp_ttype tok_type
924     = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
925   if (tok_type == CPP_OTHER)
926     return "unrecognized string type";
927
928   return get_location_within_string (parse_in, g_string_concat_db,
929                                      substr_loc.get_fmt_string_loc (),
930                                      tok_type,
931                                      substr_loc.get_caret_idx (),
932                                      substr_loc.get_start_idx (),
933                                      substr_loc.get_end_idx (),
934                                      out_loc);
935 }
936
937 \f
938 /* Return true iff T is a boolean promoted to int.  */
939
940 bool
941 bool_promoted_to_int_p (tree t)
942 {
943   return (CONVERT_EXPR_P (t)
944           && TREE_TYPE (t) == integer_type_node
945           && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
946 }
947
948 /* vector_targets_convertible_p is used for vector pointer types.  The
949    callers perform various checks that the qualifiers are satisfactory,
950    while OTOH vector_targets_convertible_p ignores the number of elements
951    in the vectors.  That's fine with vector pointers as we can consider,
952    say, a vector of 8 elements as two consecutive vectors of 4 elements,
953    and that does not require and conversion of the pointer values.
954    In contrast, vector_types_convertible_p and
955    vector_types_compatible_elements_p are used for vector value types.  */
956 /* True if pointers to distinct types T1 and T2 can be converted to
957    each other without an explicit cast.  Only returns true for opaque
958    vector types.  */
959 bool
960 vector_targets_convertible_p (const_tree t1, const_tree t2)
961 {
962   if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
963       && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
964       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
965     return true;
966
967   return false;
968 }
969
970 /* vector_types_convertible_p is used for vector value types.
971    It could in principle call vector_targets_convertible_p as a subroutine,
972    but then the check for vector type would be duplicated with its callers,
973    and also the purpose of vector_targets_convertible_p would become
974    muddled.
975    Where vector_types_convertible_p returns true, a conversion might still be
976    needed to make the types match.
977    In contrast, vector_targets_convertible_p is used for vector pointer
978    values, and vector_types_compatible_elements_p is used specifically
979    in the context for binary operators, as a check if use is possible without
980    conversion.  */
981 /* True if vector types T1 and T2 can be converted to each other
982    without an explicit cast.  If EMIT_LAX_NOTE is true, and T1 and T2
983    can only be converted with -flax-vector-conversions yet that is not
984    in effect, emit a note telling the user about that option if such
985    a note has not previously been emitted.  */
986 bool
987 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
988 {
989   static bool emitted_lax_note = false;
990   bool convertible_lax;
991
992   if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
993       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
994     return true;
995
996   convertible_lax =
997     (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
998      && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
999          || known_eq (TYPE_VECTOR_SUBPARTS (t1),
1000                       TYPE_VECTOR_SUBPARTS (t2)))
1001      && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
1002          == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
1003
1004   if (!convertible_lax || flag_lax_vector_conversions)
1005     return convertible_lax;
1006
1007   if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
1008       && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1009     return true;
1010
1011   if (emit_lax_note && !emitted_lax_note)
1012     {
1013       emitted_lax_note = true;
1014       inform (input_location, "use %<-flax-vector-conversions%> to permit "
1015               "conversions between vectors with differing "
1016               "element types or numbers of subparts");
1017     }
1018
1019   return false;
1020 }
1021
1022 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
1023    and have vector types, V0 has the same type as V1, and the number of
1024    elements of V0, V1, MASK is the same.
1025
1026    In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
1027    called with two arguments.  In this case implementation passes the
1028    first argument twice in order to share the same tree code.  This fact
1029    could enable the mask-values being twice the vector length.  This is
1030    an implementation accident and this semantics is not guaranteed to
1031    the user.  */
1032 tree
1033 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
1034                        bool complain)
1035 {
1036   tree ret;
1037   bool wrap = true;
1038   bool maybe_const = false;
1039   bool two_arguments = false;
1040
1041   if (v1 == NULL_TREE)
1042     {
1043       two_arguments = true;
1044       v1 = v0;
1045     }
1046
1047   if (v0 == error_mark_node || v1 == error_mark_node
1048       || mask == error_mark_node)
1049     return error_mark_node;
1050
1051   if (!gnu_vector_type_p (TREE_TYPE (mask))
1052       || !VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
1053     {
1054       if (complain)
1055         error_at (loc, "%<__builtin_shuffle%> last argument must "
1056                        "be an integer vector");
1057       return error_mark_node;
1058     }
1059
1060   if (!gnu_vector_type_p (TREE_TYPE (v0))
1061       || !gnu_vector_type_p (TREE_TYPE (v1)))
1062     {
1063       if (complain)
1064         error_at (loc, "%<__builtin_shuffle%> arguments must be vectors");
1065       return error_mark_node;
1066     }
1067
1068   if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1069     {
1070       if (complain)
1071         error_at (loc, "%<__builtin_shuffle%> argument vectors must be of "
1072                        "the same type");
1073       return error_mark_node;
1074     }
1075
1076   if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1077                 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1078       && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1079                    TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1080     {
1081       if (complain)
1082         error_at (loc, "%<__builtin_shuffle%> number of elements of the "
1083                        "argument vector(s) and the mask vector should "
1084                        "be the same");
1085       return error_mark_node;
1086     }
1087
1088   if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1089       != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1090     {
1091       if (complain)
1092         error_at (loc, "%<__builtin_shuffle%> argument vector(s) inner type "
1093                        "must have the same size as inner type of the mask");
1094       return error_mark_node;
1095     }
1096
1097   if (!c_dialect_cxx ())
1098     {
1099       /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR.  */
1100       v0 = c_fully_fold (v0, false, &maybe_const);
1101       wrap &= maybe_const;
1102
1103       if (two_arguments)
1104         v1 = v0 = save_expr (v0);
1105       else
1106         {
1107           v1 = c_fully_fold (v1, false, &maybe_const);
1108           wrap &= maybe_const;
1109         }
1110
1111       mask = c_fully_fold (mask, false, &maybe_const);
1112       wrap &= maybe_const;
1113     }
1114   else if (two_arguments)
1115     v1 = v0 = save_expr (v0);
1116
1117   ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1118
1119   if (!c_dialect_cxx () && !wrap)
1120     ret = c_wrap_maybe_const (ret, true);
1121
1122   return ret;
1123 }
1124
1125 /* Build a VEC_PERM_EXPR if V0, V1 are not error_mark_nodes
1126    and have vector types, V0 has the same element type as V1, and the
1127    number of elements the result is that of MASK.  */
1128 tree
1129 c_build_shufflevector (location_t loc, tree v0, tree v1,
1130                        const vec<tree> &mask, bool complain)
1131 {
1132   tree ret;
1133   bool wrap = true;
1134   bool maybe_const = false;
1135
1136   if (v0 == error_mark_node || v1 == error_mark_node)
1137     return error_mark_node;
1138
1139   if (!gnu_vector_type_p (TREE_TYPE (v0))
1140       || !gnu_vector_type_p (TREE_TYPE (v1)))
1141     {
1142       if (complain)
1143         error_at (loc, "%<__builtin_shufflevector%> arguments must be vectors");
1144       return error_mark_node;
1145     }
1146
1147   /* ???  In principle one could select a constant part of a variable size
1148      vector but things get a bit awkward with trying to support this here.  */
1149   unsigned HOST_WIDE_INT v0n, v1n;
1150   if (!TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)).is_constant (&v0n)
1151       || !TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)).is_constant (&v1n))
1152     {
1153       if (complain)
1154         error_at (loc, "%<__builtin_shufflevector%> arguments must be constant"
1155                   " size vectors");
1156       return error_mark_node;
1157     }
1158
1159   if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v0)))
1160       != TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v1))))
1161     {
1162       if (complain)
1163         error_at (loc, "%<__builtin_shufflevector%> argument vectors must "
1164                   "have the same element type");
1165       return error_mark_node;
1166     }
1167
1168   if (!pow2p_hwi (mask.length ()))
1169     {
1170       if (complain)
1171         error_at (loc, "%<__builtin_shufflevector%> must specify a result "
1172                   "with a power of two number of elements");
1173       return error_mark_node;
1174     }
1175
1176   if (!c_dialect_cxx ())
1177     {
1178       /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR.  */
1179       v0 = c_fully_fold (v0, false, &maybe_const);
1180       wrap &= maybe_const;
1181
1182       v1 = c_fully_fold (v1, false, &maybe_const);
1183       wrap &= maybe_const;
1184     }
1185
1186   unsigned HOST_WIDE_INT maskl = MAX (mask.length (), MAX (v0n, v1n));
1187   unsigned HOST_WIDE_INT pad = (v0n < maskl ? maskl - v0n : 0);
1188   vec_perm_builder sel (maskl, maskl, 1);
1189   unsigned i;
1190   for (i = 0; i < mask.length (); ++i)
1191     {
1192       tree idx = mask[i];
1193       if (!tree_fits_shwi_p (idx))
1194         {
1195           if (complain)
1196             error_at (loc, "invalid element index %qE to "
1197                       "%<__builtin_shufflevector%>", idx);
1198           return error_mark_node;
1199         }
1200       HOST_WIDE_INT iidx = tree_to_shwi (idx);
1201       if (iidx < -1
1202           || (iidx != -1
1203               && (unsigned HOST_WIDE_INT) iidx >= v0n + v1n))
1204         {
1205           if (complain)
1206             error_at (loc, "invalid element index %qE to "
1207                       "%<__builtin_shufflevector%>", idx);
1208           return error_mark_node;
1209         }
1210       /* ???  Our VEC_PERM_EXPR does not allow for -1 yet.  */
1211       if (iidx == -1)
1212         iidx = i;
1213       /* ???  Our VEC_PERM_EXPR does not allow different sized inputs,
1214          so pad out a smaller v0.  */
1215       else if ((unsigned HOST_WIDE_INT) iidx >= v0n)
1216         iidx += pad;
1217       sel.quick_push (iidx);
1218     }
1219   /* ???  VEC_PERM_EXPR does not support a result that is smaller than
1220      the inputs, so we have to pad id out.  */
1221   for (; i < maskl; ++i)
1222     sel.quick_push (i);
1223
1224   vec_perm_indices indices (sel, 2, maskl);
1225
1226   tree ret_type = build_vector_type (TREE_TYPE (TREE_TYPE (v0)), maskl);
1227   tree mask_type = build_vector_type (build_nonstandard_integer_type
1228                 (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (ret_type))), 1),
1229                 maskl);
1230   /* Pad out arguments to the common vector size.  */
1231   if (v0n < maskl)
1232     {
1233       constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v0)) };
1234       v0 = build_constructor_single (ret_type, NULL_TREE, v0);
1235       for (i = 1; i < maskl / v0n; ++i)
1236         vec_safe_push (CONSTRUCTOR_ELTS (v0), elt);
1237     }
1238   if (v1n < maskl)
1239     {
1240       constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v1)) };
1241       v1 = build_constructor_single (ret_type, NULL_TREE, v1);
1242       for (i = 1; i < maskl / v1n; ++i)
1243         vec_safe_push (CONSTRUCTOR_ELTS (v1), elt);
1244     }
1245   ret = build3_loc (loc, VEC_PERM_EXPR, ret_type, v0, v1,
1246                     vec_perm_indices_to_tree (mask_type, indices));
1247   /* Get the lowpart we are interested in.  */
1248   if (mask.length () < maskl)
1249     {
1250       tree lpartt = build_vector_type (TREE_TYPE (ret_type), mask.length ());
1251       ret = build3_loc (loc, BIT_FIELD_REF,
1252                         lpartt, ret, TYPE_SIZE (lpartt), bitsize_zero_node);
1253       /* Wrap the lowpart operation in a TARGET_EXPR so it gets a separate
1254          temporary during gimplification.  See PR101530 for cases where
1255          we'd otherwise end up with non-toplevel BIT_FIELD_REFs.  */
1256       tree tem = create_tmp_var_raw (lpartt);
1257       DECL_CONTEXT (tem) = current_function_decl;
1258       ret = build4 (TARGET_EXPR, lpartt, tem, ret, NULL_TREE, NULL_TREE);
1259       TREE_SIDE_EFFECTS (ret) = 1;
1260     }
1261
1262   if (!c_dialect_cxx () && !wrap)
1263     ret = c_wrap_maybe_const (ret, true);
1264
1265   return ret;
1266 }
1267
1268 /* Build a VEC_CONVERT ifn for __builtin_convertvector builtin.  */
1269
1270 tree
1271 c_build_vec_convert (location_t loc1, tree expr, location_t loc2, tree type,
1272                      bool complain)
1273 {
1274   if (error_operand_p (type))
1275     return error_mark_node;
1276   if (error_operand_p (expr))
1277     return error_mark_node;
1278
1279   if (!gnu_vector_type_p (TREE_TYPE (expr))
1280       || (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1281           && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (expr))))
1282     {
1283       if (complain)
1284         error_at (loc1, "%<__builtin_convertvector%> first argument must "
1285                         "be an integer or floating vector");
1286       return error_mark_node;
1287     }
1288
1289   if (!gnu_vector_type_p (type)
1290       || (!VECTOR_INTEGER_TYPE_P (type) && !VECTOR_FLOAT_TYPE_P (type)))
1291     {
1292       if (complain)
1293         error_at (loc2, "%<__builtin_convertvector%> second argument must "
1294                         "be an integer or floating vector type");
1295       return error_mark_node;
1296     }
1297
1298   if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (expr)),
1299                 TYPE_VECTOR_SUBPARTS (type)))
1300     {
1301       if (complain)
1302         error_at (loc1, "%<__builtin_convertvector%> number of elements "
1303                         "of the first argument vector and the second argument "
1304                         "vector type should be the same");
1305       return error_mark_node;
1306     }
1307
1308   if ((TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (expr)))
1309        == TYPE_MAIN_VARIANT (TREE_TYPE (type)))
1310       || (VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1311           && VECTOR_INTEGER_TYPE_P (type)
1312           && (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (expr)))
1313               == TYPE_PRECISION (TREE_TYPE (type)))))
1314     return build1_loc (loc1, VIEW_CONVERT_EXPR, type, expr);
1315
1316   bool wrap = true;
1317   bool maybe_const = false;
1318   tree ret;
1319   if (!c_dialect_cxx ())
1320     {
1321       /* Avoid C_MAYBE_CONST_EXPRs inside of VEC_CONVERT argument.  */
1322       expr = c_fully_fold (expr, false, &maybe_const);
1323       wrap &= maybe_const;
1324     }
1325
1326   ret = build_call_expr_internal_loc (loc1, IFN_VEC_CONVERT, type, 1, expr);
1327
1328   if (!wrap)
1329     ret = c_wrap_maybe_const (ret, true);
1330
1331   return ret;
1332 }
1333
1334 /* Like tree.cc:get_narrower, but retain conversion from C++0x scoped enum
1335    to integral type.  */
1336
1337 tree
1338 c_common_get_narrower (tree op, int *unsignedp_ptr)
1339 {
1340   op = get_narrower (op, unsignedp_ptr);
1341
1342   if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1343       && ENUM_IS_SCOPED (TREE_TYPE (op)))
1344     {
1345       /* C++0x scoped enumerations don't implicitly convert to integral
1346          type; if we stripped an explicit conversion to a larger type we
1347          need to replace it so common_type will still work.  */
1348       tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1349                                           TYPE_UNSIGNED (TREE_TYPE (op)));
1350       op = fold_convert (type, op);
1351     }
1352   return op;
1353 }
1354
1355 /* This is a helper function of build_binary_op.
1356
1357    For certain operations if both args were extended from the same
1358    smaller type, do the arithmetic in that type and then extend.
1359
1360    BITWISE indicates a bitwise operation.
1361    For them, this optimization is safe only if
1362    both args are zero-extended or both are sign-extended.
1363    Otherwise, we might change the result.
1364    Eg, (short)-1 | (unsigned short)-1 is (int)-1
1365    but calculated in (unsigned short) it would be (unsigned short)-1.
1366 */
1367 tree
1368 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1369 {
1370   int unsigned0, unsigned1;
1371   tree arg0, arg1;
1372   int uns;
1373   tree type;
1374
1375   /* Cast OP0 and OP1 to RESULT_TYPE.  Doing so prevents
1376      excessive narrowing when we call get_narrower below.  For
1377      example, suppose that OP0 is of unsigned int extended
1378      from signed char and that RESULT_TYPE is long long int.
1379      If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1380      like
1381
1382      (long long int) (unsigned int) signed_char
1383
1384      which get_narrower would narrow down to
1385
1386      (unsigned int) signed char
1387
1388      If we do not cast OP0 first, get_narrower would return
1389      signed_char, which is inconsistent with the case of the
1390      explicit cast.  */
1391   op0 = convert (result_type, op0);
1392   op1 = convert (result_type, op1);
1393
1394   arg0 = c_common_get_narrower (op0, &unsigned0);
1395   arg1 = c_common_get_narrower (op1, &unsigned1);
1396
1397   /* UNS is 1 if the operation to be done is an unsigned one.  */
1398   uns = TYPE_UNSIGNED (result_type);
1399
1400   /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1401      but it *requires* conversion to FINAL_TYPE.  */
1402
1403   if ((TYPE_PRECISION (TREE_TYPE (op0))
1404        == TYPE_PRECISION (TREE_TYPE (arg0)))
1405       && TREE_TYPE (op0) != result_type)
1406     unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1407   if ((TYPE_PRECISION (TREE_TYPE (op1))
1408        == TYPE_PRECISION (TREE_TYPE (arg1)))
1409       && TREE_TYPE (op1) != result_type)
1410     unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1411
1412   /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE.  */
1413
1414   /* For bitwise operations, signedness of nominal type
1415      does not matter.  Consider only how operands were extended.  */
1416   if (bitwise)
1417     uns = unsigned0;
1418
1419   /* Note that in all three cases below we refrain from optimizing
1420      an unsigned operation on sign-extended args.
1421      That would not be valid.  */
1422
1423   /* Both args variable: if both extended in same way
1424      from same width, do it in that width.
1425      Do it unsigned if args were zero-extended.  */
1426   if ((TYPE_PRECISION (TREE_TYPE (arg0))
1427        < TYPE_PRECISION (result_type))
1428       && (TYPE_PRECISION (TREE_TYPE (arg1))
1429           == TYPE_PRECISION (TREE_TYPE (arg0)))
1430       && unsigned0 == unsigned1
1431       && (unsigned0 || !uns))
1432     return c_common_signed_or_unsigned_type
1433       (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
1434
1435   else if (TREE_CODE (arg0) == INTEGER_CST
1436            && (unsigned1 || !uns)
1437            && (TYPE_PRECISION (TREE_TYPE (arg1))
1438                < TYPE_PRECISION (result_type))
1439            && (type
1440                = c_common_signed_or_unsigned_type (unsigned1,
1441                                                    TREE_TYPE (arg1)))
1442            && !POINTER_TYPE_P (type)
1443            && int_fits_type_p (arg0, type))
1444     return type;
1445
1446   else if (TREE_CODE (arg1) == INTEGER_CST
1447            && (unsigned0 || !uns)
1448            && (TYPE_PRECISION (TREE_TYPE (arg0))
1449                < TYPE_PRECISION (result_type))
1450            && (type
1451                = c_common_signed_or_unsigned_type (unsigned0,
1452                                                    TREE_TYPE (arg0)))
1453            && !POINTER_TYPE_P (type)
1454            && int_fits_type_p (arg1, type))
1455     return type;
1456
1457   return result_type;
1458 }
1459
1460 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1461    real of type TO_TYPE.  This is a helper function for unsafe_conversion_p.  */
1462
1463 static bool
1464 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1465 {
1466   tree type_low_bound = TYPE_MIN_VALUE (from_type);
1467   tree type_high_bound = TYPE_MAX_VALUE (from_type);
1468   REAL_VALUE_TYPE real_low_bound =
1469           real_value_from_int_cst (0, type_low_bound);
1470   REAL_VALUE_TYPE real_high_bound =
1471           real_value_from_int_cst (0, type_high_bound);
1472
1473   return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1474          && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1475 }
1476
1477 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1478    to the complex/real/integer type TYPE.  Function returns non-zero when:
1479         * EXPR is a constant which cannot be exactly converted to TYPE.
1480         * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1481           for EXPR type and TYPE being both integers or both real, or both
1482           complex.
1483         * EXPR is not a constant of complex type and TYPE is a real or
1484           an integer.
1485         * EXPR is not a constant of real type and TYPE is an integer.
1486         * EXPR is not a constant of integer type which cannot be
1487           exactly converted to real type.
1488
1489    Function allows conversions between types of different signedness if
1490    CHECK_SIGN is false and can return SAFE_CONVERSION (zero) in that
1491    case.  Function can return UNSAFE_SIGN if CHECK_SIGN is true.
1492
1493    RESULT, when non-null is the result of the conversion.  When constant
1494    it is included in the text of diagnostics.
1495
1496    Function allows conversions from complex constants to non-complex types,
1497    provided that imaginary part is zero and real part can be safely converted
1498    to TYPE.  */
1499
1500 enum conversion_safety
1501 unsafe_conversion_p (tree type, tree expr, tree result, bool check_sign)
1502 {
1503   enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1504   tree expr_type = TREE_TYPE (expr);
1505
1506   expr = fold_for_warn (expr);
1507
1508   if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1509     {
1510       /* If type is complex, we are interested in compatibility with
1511          underlying type.  */
1512       if (TREE_CODE (type) == COMPLEX_TYPE)
1513           type = TREE_TYPE (type);
1514
1515       /* Warn for real constant that is not an exact integer converted
1516          to integer type.  */
1517       if (TREE_CODE (expr_type) == REAL_TYPE
1518           && TREE_CODE (type) == INTEGER_TYPE)
1519         {
1520           if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1521             give_warning = UNSAFE_REAL;
1522         }
1523       /* Warn for an integer constant that does not fit into integer type.  */
1524       else if (TREE_CODE (expr_type) == INTEGER_TYPE
1525                && TREE_CODE (type) == INTEGER_TYPE
1526                && !int_fits_type_p (expr, type))
1527         {
1528           if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1529               && tree_int_cst_sgn (expr) < 0)
1530             {
1531               if (check_sign)
1532                 give_warning = UNSAFE_SIGN;
1533             }
1534           else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1535             {
1536               if (check_sign)
1537                 give_warning = UNSAFE_SIGN;
1538             }
1539           else
1540             give_warning = UNSAFE_OTHER;
1541         }
1542       else if (TREE_CODE (type) == REAL_TYPE)
1543         {
1544           /* Warn for an integer constant that does not fit into real type.  */
1545           if (TREE_CODE (expr_type) == INTEGER_TYPE)
1546             {
1547               REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1548               if (!exact_real_truncate (TYPE_MODE (type), &a))
1549                 give_warning = UNSAFE_REAL;
1550             }
1551           /* Warn for a real constant that does not fit into a smaller
1552              real type.  */
1553           else if (TREE_CODE (expr_type) == REAL_TYPE
1554                    && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1555             {
1556               REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1557               if (!exact_real_truncate (TYPE_MODE (type), &a))
1558                 give_warning = UNSAFE_REAL;
1559             }
1560         }
1561     }
1562
1563   else if (TREE_CODE (expr) == COMPLEX_CST)
1564     {
1565       tree imag_part = TREE_IMAGPART (expr);
1566       /* Conversion from complex constant with zero imaginary part,
1567          perform check for conversion of real part.  */
1568       if ((TREE_CODE (imag_part) == REAL_CST
1569            && real_zerop (imag_part))
1570           || (TREE_CODE (imag_part) == INTEGER_CST
1571               && integer_zerop (imag_part)))
1572         /* Note: in this branch we use recursive call to unsafe_conversion_p
1573            with different type of EXPR, but it is still safe, because when EXPR
1574            is a constant, it's type is not used in text of generated warnings
1575            (otherwise they could sound misleading).  */
1576         return unsafe_conversion_p (type, TREE_REALPART (expr), result,
1577                                     check_sign);
1578       /* Conversion from complex constant with non-zero imaginary part.  */
1579       else
1580         {
1581           /* Conversion to complex type.
1582              Perform checks for both real and imaginary parts.  */
1583           if (TREE_CODE (type) == COMPLEX_TYPE)
1584             {
1585               enum conversion_safety re_safety =
1586                 unsafe_conversion_p (type, TREE_REALPART (expr),
1587                                      result, check_sign);
1588               enum conversion_safety im_safety =
1589                 unsafe_conversion_p (type, imag_part, result, check_sign);
1590
1591               /* Merge the results into appropriate single warning.  */
1592
1593               /* Note: this case includes SAFE_CONVERSION, i.e. success.  */
1594               if (re_safety == im_safety)
1595                 give_warning = re_safety;
1596               else if (!re_safety && im_safety)
1597                 give_warning = im_safety;
1598               else if (re_safety && !im_safety)
1599                 give_warning = re_safety;
1600               else
1601                 give_warning = UNSAFE_OTHER;
1602             }
1603           /* Warn about conversion from complex to real or integer type.  */
1604           else
1605             give_warning = UNSAFE_IMAGINARY;
1606         }
1607     }
1608
1609   /* Checks for remaining case: EXPR is not constant.  */
1610   else
1611     {
1612       /* Warn for real types converted to integer types.  */
1613       if (TREE_CODE (expr_type) == REAL_TYPE
1614           && TREE_CODE (type) == INTEGER_TYPE)
1615         give_warning = UNSAFE_REAL;
1616
1617       else if (TREE_CODE (expr_type) == INTEGER_TYPE
1618                && TREE_CODE (type) == INTEGER_TYPE)
1619         {
1620           /* Don't warn about unsigned char y = 0xff, x = (int) y;  */
1621           expr = get_unwidened (expr, 0);
1622           expr_type = TREE_TYPE (expr);
1623
1624           /* Don't warn for short y; short x = ((int)y & 0xff);  */
1625           if (TREE_CODE (expr) == BIT_AND_EXPR
1626               || TREE_CODE (expr) == BIT_IOR_EXPR
1627               || TREE_CODE (expr) == BIT_XOR_EXPR)
1628             {
1629               /* If both args were extended from a shortest type,
1630                  use that type if that is safe.  */
1631               expr_type = shorten_binary_op (expr_type,
1632                                              TREE_OPERAND (expr, 0),
1633                                              TREE_OPERAND (expr, 1),
1634                                              /* bitwise */1);
1635
1636               if (TREE_CODE (expr) == BIT_AND_EXPR)
1637                 {
1638                   tree op0 = TREE_OPERAND (expr, 0);
1639                   tree op1 = TREE_OPERAND (expr, 1);
1640                   bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1641                   bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1642
1643                   /* If one of the operands is a non-negative constant
1644                      that fits in the target type, then the type of the
1645                      other operand does not matter. */
1646                   if ((TREE_CODE (op0) == INTEGER_CST
1647                        && int_fits_type_p (op0, c_common_signed_type (type))
1648                        && int_fits_type_p (op0, c_common_unsigned_type (type)))
1649                       || (TREE_CODE (op1) == INTEGER_CST
1650                           && int_fits_type_p (op1, c_common_signed_type (type))
1651                           && int_fits_type_p (op1,
1652                                               c_common_unsigned_type (type))))
1653                     return SAFE_CONVERSION;
1654                   /* If constant is unsigned and fits in the target
1655                      type, then the result will also fit.  */
1656                   else if ((TREE_CODE (op0) == INTEGER_CST
1657                             && unsigned0
1658                             && int_fits_type_p (op0, type))
1659                            || (TREE_CODE (op1) == INTEGER_CST
1660                                && unsigned1
1661                                && int_fits_type_p (op1, type)))
1662                     return SAFE_CONVERSION;
1663                 }
1664             }
1665           /* Warn for integer types converted to smaller integer types.  */
1666           if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1667             give_warning = UNSAFE_OTHER;
1668
1669           /* When they are the same width but different signedness,
1670              then the value may change.  */
1671           else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1672                      && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1673                     /* Even when converted to a bigger type, if the type is
1674                        unsigned but expr is signed, then negative values
1675                        will be changed.  */
1676                     || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1677                    && check_sign)
1678             give_warning = UNSAFE_SIGN;
1679         }
1680
1681       /* Warn for integer types converted to real types if and only if
1682          all the range of values of the integer type cannot be
1683          represented by the real type.  */
1684       else if (TREE_CODE (expr_type) == INTEGER_TYPE
1685                && TREE_CODE (type) == REAL_TYPE)
1686         {
1687           /* Don't warn about char y = 0xff; float x = (int) y;  */
1688           expr = get_unwidened (expr, 0);
1689           expr_type = TREE_TYPE (expr);
1690
1691           if (!int_safely_convertible_to_real_p (expr_type, type))
1692             give_warning = UNSAFE_OTHER;
1693         }
1694
1695       /* Warn for real types converted to smaller real types.  */
1696       else if (TREE_CODE (expr_type) == REAL_TYPE
1697                && TREE_CODE (type) == REAL_TYPE
1698                && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1699         give_warning = UNSAFE_REAL;
1700
1701       /* Check conversion between two complex types.  */
1702       else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1703                && TREE_CODE (type) == COMPLEX_TYPE)
1704         {
1705           /* Extract underlying types (i.e., type of real and imaginary
1706              parts) of expr_type and type.  */
1707           tree from_type = TREE_TYPE (expr_type);
1708           tree to_type = TREE_TYPE (type);
1709
1710           /* Warn for real types converted to integer types.  */
1711           if (TREE_CODE (from_type) == REAL_TYPE
1712               && TREE_CODE (to_type) == INTEGER_TYPE)
1713             give_warning = UNSAFE_REAL;
1714
1715           /* Warn for real types converted to smaller real types.  */
1716           else if (TREE_CODE (from_type) == REAL_TYPE
1717                    && TREE_CODE (to_type) == REAL_TYPE
1718                    && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1719             give_warning = UNSAFE_REAL;
1720
1721           /* Check conversion for complex integer types.  Here implementation
1722              is simpler than for real-domain integers because it does not
1723              involve sophisticated cases, such as bitmasks, casts, etc.  */
1724           else if (TREE_CODE (from_type) == INTEGER_TYPE
1725                    && TREE_CODE (to_type) == INTEGER_TYPE)
1726             {
1727               /* Warn for integer types converted to smaller integer types.  */
1728               if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1729                 give_warning = UNSAFE_OTHER;
1730
1731               /* Check for different signedness, see case for real-domain
1732                  integers (above) for a more detailed comment.  */
1733               else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1734                          && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1735                         || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1736                        && check_sign)
1737                 give_warning = UNSAFE_SIGN;
1738             }
1739           else if (TREE_CODE (from_type) == INTEGER_TYPE
1740                    && TREE_CODE (to_type) == REAL_TYPE
1741                    && !int_safely_convertible_to_real_p (from_type, to_type))
1742             give_warning = UNSAFE_OTHER;
1743         }
1744
1745       /* Warn for complex types converted to real or integer types.  */
1746       else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1747                && TREE_CODE (type) != COMPLEX_TYPE)
1748         give_warning = UNSAFE_IMAGINARY;
1749     }
1750
1751   return give_warning;
1752 }
1753
1754
1755 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1756    Invoke this function on every expression that is converted implicitly,
1757    i.e. because of language rules and not because of an explicit cast.
1758    INIT_CONST is true if the conversion is for arithmetic types for a static
1759    initializer and folding must apply accordingly (discarding floating-point
1760    exceptions and assuming the default rounding mode is in effect).  */
1761
1762 tree
1763 convert_and_check (location_t loc, tree type, tree expr, bool init_const)
1764 {
1765   tree result;
1766   tree expr_for_warning;
1767
1768   /* Convert from a value with possible excess precision rather than
1769      via the semantic type, but do not warn about values not fitting
1770      exactly in the semantic type.  */
1771   if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1772     {
1773       tree orig_type = TREE_TYPE (expr);
1774       expr = TREE_OPERAND (expr, 0);
1775       expr_for_warning = (init_const
1776                           ? convert_init (orig_type, expr)
1777                           : convert (orig_type, expr));
1778       if (orig_type == type)
1779         return expr_for_warning;
1780     }
1781   else
1782     expr_for_warning = expr;
1783
1784   if (TREE_TYPE (expr) == type)
1785     return expr;
1786
1787   result = init_const ? convert_init (type, expr) : convert (type, expr);
1788
1789   if (c_inhibit_evaluation_warnings == 0
1790       && !TREE_OVERFLOW_P (expr)
1791       && result != error_mark_node)
1792     warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1793
1794   return result;
1795 }
1796 \f
1797 /* A node in a list that describes references to variables (EXPR), which are
1798    either read accesses if WRITER is zero, or write accesses, in which case
1799    WRITER is the parent of EXPR.  */
1800 struct tlist
1801 {
1802   struct tlist *next;
1803   tree expr, writer;
1804 };
1805
1806 /* Used to implement a cache the results of a call to verify_tree.  We only
1807    use this for SAVE_EXPRs.  */
1808 struct tlist_cache
1809 {
1810   struct tlist_cache *next;
1811   struct tlist *cache_before_sp;
1812   struct tlist *cache_after_sp;
1813   tree expr;
1814 };
1815
1816 /* Obstack to use when allocating tlist structures, and corresponding
1817    firstobj.  */
1818 static struct obstack tlist_obstack;
1819 static char *tlist_firstobj = 0;
1820
1821 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1822    warnings.  */
1823 static struct tlist *warned_ids;
1824 /* SAVE_EXPRs need special treatment.  We process them only once and then
1825    cache the results.  */
1826 static struct tlist_cache *save_expr_cache;
1827
1828 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1829 static void merge_tlist (struct tlist **, struct tlist *, int);
1830 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1831 static bool warning_candidate_p (tree);
1832 static bool candidate_equal_p (const_tree, const_tree);
1833 static void warn_for_collisions (struct tlist *);
1834 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1835 static struct tlist *new_tlist (struct tlist *, tree, tree);
1836
1837 /* Create a new struct tlist and fill in its fields.  */
1838 static struct tlist *
1839 new_tlist (struct tlist *next, tree t, tree writer)
1840 {
1841   struct tlist *l;
1842   l = XOBNEW (&tlist_obstack, struct tlist);
1843   l->next = next;
1844   l->expr = t;
1845   l->writer = writer;
1846   return l;
1847 }
1848
1849 /* Add duplicates of the nodes found in ADD to the list *TO.  If EXCLUDE_WRITER
1850    is nonnull, we ignore any node we find which has a writer equal to it.  */
1851
1852 static void
1853 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1854 {
1855   while (add)
1856     {
1857       struct tlist *next = add->next;
1858       if (!copy)
1859         add->next = *to;
1860       if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1861         *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1862       add = next;
1863     }
1864 }
1865
1866 /* Merge the nodes of ADD into TO.  This merging process is done so that for
1867    each variable that already exists in TO, no new node is added; however if
1868    there is a write access recorded in ADD, and an occurrence on TO is only
1869    a read access, then the occurrence in TO will be modified to record the
1870    write.  */
1871
1872 static void
1873 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1874 {
1875   struct tlist **end = to;
1876
1877   while (*end)
1878     end = &(*end)->next;
1879
1880   while (add)
1881     {
1882       int found = 0;
1883       struct tlist *tmp2;
1884       struct tlist *next = add->next;
1885
1886       for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1887         if (candidate_equal_p (tmp2->expr, add->expr))
1888           {
1889             found = 1;
1890             if (!tmp2->writer)
1891               tmp2->writer = add->writer;
1892           }
1893       if (!found)
1894         {
1895           *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1896           end = &(*end)->next;
1897           *end = 0;
1898         }
1899       add = next;
1900     }
1901 }
1902
1903 /* WRITTEN is a variable, WRITER is its parent.  Warn if any of the variable
1904    references in list LIST conflict with it, excluding reads if ONLY writers
1905    is nonzero.  */
1906
1907 static void
1908 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1909                        int only_writes)
1910 {
1911   struct tlist *tmp;
1912
1913   /* Avoid duplicate warnings.  */
1914   for (tmp = warned_ids; tmp; tmp = tmp->next)
1915     if (candidate_equal_p (tmp->expr, written))
1916       return;
1917
1918   while (list)
1919     {
1920       if (candidate_equal_p (list->expr, written)
1921           && !candidate_equal_p (list->writer, writer)
1922           && (!only_writes || list->writer))
1923         {
1924           warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1925           warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1926                       OPT_Wsequence_point, "operation on %qE may be undefined",
1927                       list->expr);
1928         }
1929       list = list->next;
1930     }
1931 }
1932
1933 /* Given a list LIST of references to variables, find whether any of these
1934    can cause conflicts due to missing sequence points.  */
1935
1936 static void
1937 warn_for_collisions (struct tlist *list)
1938 {
1939   struct tlist *tmp;
1940
1941   for (tmp = list; tmp; tmp = tmp->next)
1942     {
1943       if (tmp->writer)
1944         warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1945     }
1946 }
1947
1948 /* Return nonzero if X is a tree that can be verified by the sequence point
1949    warnings.  */
1950
1951 static bool
1952 warning_candidate_p (tree x)
1953 {
1954   if (DECL_P (x) && DECL_ARTIFICIAL (x))
1955     return false;
1956
1957   if (TREE_CODE (x) == BLOCK)
1958     return false;
1959
1960   /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.cc
1961      (lvalue_p) crash on TRY/CATCH. */
1962   if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1963     return false;
1964
1965   if (!lvalue_p (x))
1966     return false;
1967
1968   /* No point to track non-const calls, they will never satisfy
1969      operand_equal_p.  */
1970   if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1971     return false;
1972
1973   if (TREE_CODE (x) == STRING_CST)
1974     return false;
1975
1976   return true;
1977 }
1978
1979 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1980 static bool
1981 candidate_equal_p (const_tree x, const_tree y)
1982 {
1983   return (x == y) || (x && y && operand_equal_p (x, y, 0));
1984 }
1985
1986 /* Walk the tree X, and record accesses to variables.  If X is written by the
1987    parent tree, WRITER is the parent.
1988    We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP.  If this
1989    expression or its only operand forces a sequence point, then everything up
1990    to the sequence point is stored in PBEFORE_SP.  Everything else gets stored
1991    in PNO_SP.
1992    Once we return, we will have emitted warnings if any subexpression before
1993    such a sequence point could be undefined.  On a higher level, however, the
1994    sequence point may not be relevant, and we'll merge the two lists.
1995
1996    Example: (b++, a) + b;
1997    The call that processes the COMPOUND_EXPR will store the increment of B
1998    in PBEFORE_SP, and the use of A in PNO_SP.  The higher-level call that
1999    processes the PLUS_EXPR will need to merge the two lists so that
2000    eventually, all accesses end up on the same list (and we'll warn about the
2001    unordered subexpressions b++ and b.
2002
2003    A note on merging.  If we modify the former example so that our expression
2004    becomes
2005      (b++, b) + a
2006    care must be taken not simply to add all three expressions into the final
2007    PNO_SP list.  The function merge_tlist takes care of that by merging the
2008    before-SP list of the COMPOUND_EXPR into its after-SP list in a special
2009    way, so that no more than one access to B is recorded.  */
2010
2011 static void
2012 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
2013              tree writer)
2014 {
2015   struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
2016   enum tree_code code;
2017   enum tree_code_class cl;
2018
2019  restart:
2020   /* X may be NULL if it is the operand of an empty statement expression
2021      ({ }).  */
2022   if (x == NULL)
2023     return;
2024
2025   code = TREE_CODE (x);
2026   cl = TREE_CODE_CLASS (code);
2027
2028   if (warning_candidate_p (x))
2029     *pno_sp = new_tlist (*pno_sp, x, writer);
2030
2031   switch (code)
2032     {
2033     case CONSTRUCTOR:
2034     case SIZEOF_EXPR:
2035     case PAREN_SIZEOF_EXPR:
2036       return;
2037
2038     case COMPOUND_EXPR:
2039     case TRUTH_ANDIF_EXPR:
2040     case TRUTH_ORIF_EXPR:
2041     sequenced_binary:
2042       tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
2043       verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2044       warn_for_collisions (tmp_nosp);
2045       merge_tlist (pbefore_sp, tmp_before, 0);
2046       merge_tlist (pbefore_sp, tmp_nosp, 0);
2047       verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
2048       warn_for_collisions (tmp_list2);
2049       merge_tlist (pbefore_sp, tmp_list3, 0);
2050       merge_tlist (pno_sp, tmp_list2, 0);
2051       return;
2052
2053     case COND_EXPR:
2054       tmp_before = tmp_list2 = 0;
2055       verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
2056       warn_for_collisions (tmp_list2);
2057       merge_tlist (pbefore_sp, tmp_before, 0);
2058       merge_tlist (pbefore_sp, tmp_list2, 0);
2059
2060       tmp_list3 = tmp_nosp = 0;
2061       verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
2062       warn_for_collisions (tmp_nosp);
2063       merge_tlist (pbefore_sp, tmp_list3, 0);
2064
2065       tmp_list3 = tmp_list2 = 0;
2066       verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
2067       warn_for_collisions (tmp_list2);
2068       merge_tlist (pbefore_sp, tmp_list3, 0);
2069       /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
2070          two first, to avoid warning for (a ? b++ : b++).  */
2071       merge_tlist (&tmp_nosp, tmp_list2, 0);
2072       add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2073       return;
2074
2075     case PREDECREMENT_EXPR:
2076     case PREINCREMENT_EXPR:
2077     case POSTDECREMENT_EXPR:
2078     case POSTINCREMENT_EXPR:
2079       verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
2080       return;
2081
2082     case MODIFY_EXPR:
2083       tmp_before = tmp_nosp = tmp_list3 = 0;
2084       verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
2085       verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
2086       /* Expressions inside the LHS are not ordered wrt. the sequence points
2087          in the RHS.  Example:
2088            *a = (a++, 2)
2089          Despite the fact that the modification of "a" is in the before_sp
2090          list (tmp_before), it conflicts with the use of "a" in the LHS.
2091          We can handle this by adding the contents of tmp_list3
2092          to those of tmp_before, and redoing the collision warnings for that
2093          list.  */
2094       add_tlist (&tmp_before, tmp_list3, x, 1);
2095       warn_for_collisions (tmp_before);
2096       /* Exclude the LHS itself here; we first have to merge it into the
2097          tmp_nosp list.  This is done to avoid warning for "a = a"; if we
2098          didn't exclude the LHS, we'd get it twice, once as a read and once
2099          as a write.  */
2100       add_tlist (pno_sp, tmp_list3, x, 0);
2101       warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
2102
2103       merge_tlist (pbefore_sp, tmp_before, 0);
2104       if (warning_candidate_p (TREE_OPERAND (x, 0)))
2105         merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
2106       add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
2107       return;
2108
2109     case CALL_EXPR:
2110       /* We need to warn about conflicts among arguments and conflicts between
2111          args and the function address.  Side effects of the function address,
2112          however, are not ordered by the sequence point of the call.  */
2113       {
2114         call_expr_arg_iterator iter;
2115         tree arg;
2116         tmp_before = tmp_nosp = 0;
2117         verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
2118         FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
2119           {
2120             tmp_list2 = tmp_list3 = 0;
2121             verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
2122             merge_tlist (&tmp_list3, tmp_list2, 0);
2123             add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
2124           }
2125         add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
2126         warn_for_collisions (tmp_before);
2127         add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
2128         return;
2129       }
2130
2131     case TREE_LIST:
2132       /* Scan all the list, e.g. indices of multi dimensional array.  */
2133       while (x)
2134         {
2135           tmp_before = tmp_nosp = 0;
2136           verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
2137           merge_tlist (&tmp_nosp, tmp_before, 0);
2138           add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2139           x = TREE_CHAIN (x);
2140         }
2141       return;
2142
2143     case SAVE_EXPR:
2144       {
2145         struct tlist_cache *t;
2146         for (t = save_expr_cache; t; t = t->next)
2147           if (candidate_equal_p (t->expr, x))
2148             break;
2149
2150         if (!t)
2151           {
2152             t = XOBNEW (&tlist_obstack, struct tlist_cache);
2153             t->next = save_expr_cache;
2154             t->expr = x;
2155             save_expr_cache = t;
2156
2157             tmp_before = tmp_nosp = 0;
2158             verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2159             warn_for_collisions (tmp_nosp);
2160
2161             tmp_list3 = 0;
2162             merge_tlist (&tmp_list3, tmp_nosp, 0);
2163             t->cache_before_sp = tmp_before;
2164             t->cache_after_sp = tmp_list3;
2165           }
2166         merge_tlist (pbefore_sp, t->cache_before_sp, 1);
2167         add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
2168         return;
2169       }
2170
2171     case ADDR_EXPR:
2172       x = TREE_OPERAND (x, 0);
2173       if (DECL_P (x))
2174         return;
2175       writer = 0;
2176       goto restart;
2177
2178     case VIEW_CONVERT_EXPR:
2179       if (location_wrapper_p (x))
2180         {
2181           x = TREE_OPERAND (x, 0);
2182           goto restart;
2183         }
2184       goto do_default;
2185
2186     case LSHIFT_EXPR:
2187     case RSHIFT_EXPR:
2188     case COMPONENT_REF:
2189     case ARRAY_REF:
2190       if (cxx_dialect >= cxx17)
2191         goto sequenced_binary;
2192       goto do_default;
2193
2194     default:
2195     do_default:
2196       /* For other expressions, simply recurse on their operands.
2197          Manual tail recursion for unary expressions.
2198          Other non-expressions need not be processed.  */
2199       if (cl == tcc_unary)
2200         {
2201           x = TREE_OPERAND (x, 0);
2202           writer = 0;
2203           goto restart;
2204         }
2205       else if (IS_EXPR_CODE_CLASS (cl))
2206         {
2207           int lp;
2208           int max = TREE_OPERAND_LENGTH (x);
2209           for (lp = 0; lp < max; lp++)
2210             {
2211               tmp_before = tmp_nosp = 0;
2212               verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
2213               merge_tlist (&tmp_nosp, tmp_before, 0);
2214               add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2215             }
2216         }
2217       return;
2218     }
2219 }
2220
2221 static constexpr size_t verify_sequence_points_limit = 1024;
2222
2223 /* Called from verify_sequence_points via walk_tree.  */
2224
2225 static tree
2226 verify_tree_lim_r (tree *tp, int *walk_subtrees, void *data)
2227 {
2228   if (++*((size_t *) data) > verify_sequence_points_limit)
2229     return integer_zero_node;
2230
2231   if (TYPE_P (*tp))
2232     *walk_subtrees = 0;
2233
2234   return NULL_TREE;
2235 }
2236
2237 /* Try to warn for undefined behavior in EXPR due to missing sequence
2238    points.  */
2239
2240 void
2241 verify_sequence_points (tree expr)
2242 {
2243   tlist *before_sp = nullptr, *after_sp = nullptr;
2244
2245   /* verify_tree is highly recursive, and merge_tlist is O(n^2),
2246      so we return early if the expression is too big.  */
2247   size_t n = 0;
2248   if (walk_tree (&expr, verify_tree_lim_r, &n, nullptr))
2249     return;
2250
2251   warned_ids = nullptr;
2252   save_expr_cache = nullptr;
2253   if (!tlist_firstobj)
2254     {
2255       gcc_obstack_init (&tlist_obstack);
2256       tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
2257     }
2258
2259   verify_tree (expr, &before_sp, &after_sp, NULL_TREE);
2260   warn_for_collisions (after_sp);
2261   obstack_free (&tlist_obstack, tlist_firstobj);
2262 }
2263 \f
2264 /* Validate the expression after `case' and apply default promotions.  */
2265
2266 static tree
2267 check_case_value (location_t loc, tree value)
2268 {
2269   if (value == NULL_TREE)
2270     return value;
2271
2272   if (TREE_CODE (value) == INTEGER_CST)
2273     /* Promote char or short to int.  */
2274     value = perform_integral_promotions (value);
2275   else if (value != error_mark_node)
2276     {
2277       error_at (loc, "case label does not reduce to an integer constant");
2278       value = error_mark_node;
2279     }
2280
2281   constant_expression_warning (value);
2282
2283   return value;
2284 }
2285 \f
2286 /* Return an integer type with BITS bits of precision,
2287    that is unsigned if UNSIGNEDP is nonzero, otherwise signed.  */
2288
2289 tree
2290 c_common_type_for_size (unsigned int bits, int unsignedp)
2291 {
2292   int i;
2293
2294   if (bits == TYPE_PRECISION (integer_type_node))
2295     return unsignedp ? unsigned_type_node : integer_type_node;
2296
2297   if (bits == TYPE_PRECISION (signed_char_type_node))
2298     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2299
2300   if (bits == TYPE_PRECISION (short_integer_type_node))
2301     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2302
2303   if (bits == TYPE_PRECISION (long_integer_type_node))
2304     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2305
2306   if (bits == TYPE_PRECISION (long_long_integer_type_node))
2307     return (unsignedp ? long_long_unsigned_type_node
2308             : long_long_integer_type_node);
2309
2310   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2311     if (int_n_enabled_p[i]
2312         && bits == int_n_data[i].bitsize)
2313       return (unsignedp ? int_n_trees[i].unsigned_type
2314               : int_n_trees[i].signed_type);
2315
2316   if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2317     return (unsignedp ? widest_unsigned_literal_type_node
2318             : widest_integer_literal_type_node);
2319
2320   if (bits <= TYPE_PRECISION (intQI_type_node))
2321     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2322
2323   if (bits <= TYPE_PRECISION (intHI_type_node))
2324     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2325
2326   if (bits <= TYPE_PRECISION (intSI_type_node))
2327     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2328
2329   if (bits <= TYPE_PRECISION (intDI_type_node))
2330     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2331
2332   return NULL_TREE;
2333 }
2334
2335 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2336    that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2337    and saturating if SATP is nonzero, otherwise not saturating.  */
2338
2339 tree
2340 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2341                                     int unsignedp, int satp)
2342 {
2343   enum mode_class mclass;
2344   if (ibit == 0)
2345     mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2346   else
2347     mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2348
2349   opt_scalar_mode opt_mode;
2350   scalar_mode mode;
2351   FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2352     {
2353       mode = opt_mode.require ();
2354       if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2355         break;
2356     }
2357
2358   if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2359     {
2360       sorry ("GCC cannot support operators with integer types and "
2361              "fixed-point types that have too many integral and "
2362              "fractional bits together");
2363       return NULL_TREE;
2364     }
2365
2366   return c_common_type_for_mode (mode, satp);
2367 }
2368
2369 /* Used for communication between c_common_type_for_mode and
2370    c_register_builtin_type.  */
2371 tree registered_builtin_types;
2372
2373 /* Return a data type that has machine mode MODE.
2374    If the mode is an integer,
2375    then UNSIGNEDP selects between signed and unsigned types.
2376    If the mode is a fixed-point mode,
2377    then UNSIGNEDP selects between saturating and nonsaturating types.  */
2378
2379 tree
2380 c_common_type_for_mode (machine_mode mode, int unsignedp)
2381 {
2382   tree t;
2383   int i;
2384
2385   if (mode == TYPE_MODE (integer_type_node))
2386     return unsignedp ? unsigned_type_node : integer_type_node;
2387
2388   if (mode == TYPE_MODE (signed_char_type_node))
2389     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2390
2391   if (mode == TYPE_MODE (short_integer_type_node))
2392     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2393
2394   if (mode == TYPE_MODE (long_integer_type_node))
2395     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2396
2397   if (mode == TYPE_MODE (long_long_integer_type_node))
2398     return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2399
2400   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2401     if (int_n_enabled_p[i]
2402         && mode == int_n_data[i].m)
2403       return (unsignedp ? int_n_trees[i].unsigned_type
2404               : int_n_trees[i].signed_type);
2405
2406   if (mode == QImode)
2407     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2408
2409   if (mode == HImode)
2410     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2411
2412   if (mode == SImode)
2413     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2414
2415   if (mode == DImode)
2416     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2417
2418 #if HOST_BITS_PER_WIDE_INT >= 64
2419   if (mode == TYPE_MODE (intTI_type_node))
2420     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2421 #endif
2422
2423   if (mode == TYPE_MODE (float_type_node))
2424     return float_type_node;
2425
2426   if (mode == TYPE_MODE (double_type_node))
2427     return double_type_node;
2428
2429   if (mode == TYPE_MODE (long_double_type_node))
2430     return long_double_type_node;
2431
2432   for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2433     if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2434         && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2435       return FLOATN_NX_TYPE_NODE (i);
2436
2437   if (mode == TYPE_MODE (void_type_node))
2438     return void_type_node;
2439
2440   if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2441       || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2442     {
2443       unsigned int precision
2444         = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2445       return (unsignedp
2446               ? make_unsigned_type (precision)
2447               : make_signed_type (precision));
2448     }
2449
2450   if (COMPLEX_MODE_P (mode))
2451     {
2452       machine_mode inner_mode;
2453       tree inner_type;
2454
2455       if (mode == TYPE_MODE (complex_float_type_node))
2456         return complex_float_type_node;
2457       if (mode == TYPE_MODE (complex_double_type_node))
2458         return complex_double_type_node;
2459       if (mode == TYPE_MODE (complex_long_double_type_node))
2460         return complex_long_double_type_node;
2461
2462       for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2463         if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2464             && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2465           return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2466
2467       if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2468         return complex_integer_type_node;
2469
2470       inner_mode = GET_MODE_INNER (mode);
2471       inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2472       if (inner_type != NULL_TREE)
2473         return build_complex_type (inner_type);
2474     }
2475   else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
2476            && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2477     {
2478       unsigned int elem_bits = vector_element_size (GET_MODE_BITSIZE (mode),
2479                                                     GET_MODE_NUNITS (mode));
2480       tree bool_type = build_nonstandard_boolean_type (elem_bits);
2481       return build_vector_type_for_mode (bool_type, mode);
2482     }
2483   else if (VECTOR_MODE_P (mode)
2484            && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2485     {
2486       machine_mode inner_mode = GET_MODE_INNER (mode);
2487       tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2488       if (inner_type != NULL_TREE)
2489         return build_vector_type_for_mode (inner_type, mode);
2490     }
2491
2492   if (dfloat32_type_node != NULL_TREE
2493       && mode == TYPE_MODE (dfloat32_type_node))
2494     return dfloat32_type_node;
2495   if (dfloat64_type_node != NULL_TREE
2496       && mode == TYPE_MODE (dfloat64_type_node))
2497     return dfloat64_type_node;
2498   if (dfloat128_type_node != NULL_TREE
2499       && mode == TYPE_MODE (dfloat128_type_node))
2500     return dfloat128_type_node;
2501
2502   if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2503     {
2504       if (mode == TYPE_MODE (short_fract_type_node))
2505         return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2506       if (mode == TYPE_MODE (fract_type_node))
2507         return unsignedp ? sat_fract_type_node : fract_type_node;
2508       if (mode == TYPE_MODE (long_fract_type_node))
2509         return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2510       if (mode == TYPE_MODE (long_long_fract_type_node))
2511         return unsignedp ? sat_long_long_fract_type_node
2512                          : long_long_fract_type_node;
2513
2514       if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2515         return unsignedp ? sat_unsigned_short_fract_type_node
2516                          : unsigned_short_fract_type_node;
2517       if (mode == TYPE_MODE (unsigned_fract_type_node))
2518         return unsignedp ? sat_unsigned_fract_type_node
2519                          : unsigned_fract_type_node;
2520       if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2521         return unsignedp ? sat_unsigned_long_fract_type_node
2522                          : unsigned_long_fract_type_node;
2523       if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2524         return unsignedp ? sat_unsigned_long_long_fract_type_node
2525                          : unsigned_long_long_fract_type_node;
2526
2527       if (mode == TYPE_MODE (short_accum_type_node))
2528         return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2529       if (mode == TYPE_MODE (accum_type_node))
2530         return unsignedp ? sat_accum_type_node : accum_type_node;
2531       if (mode == TYPE_MODE (long_accum_type_node))
2532         return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2533       if (mode == TYPE_MODE (long_long_accum_type_node))
2534         return unsignedp ? sat_long_long_accum_type_node
2535                          : long_long_accum_type_node;
2536
2537       if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2538         return unsignedp ? sat_unsigned_short_accum_type_node
2539                          : unsigned_short_accum_type_node;
2540       if (mode == TYPE_MODE (unsigned_accum_type_node))
2541         return unsignedp ? sat_unsigned_accum_type_node
2542                          : unsigned_accum_type_node;
2543       if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2544         return unsignedp ? sat_unsigned_long_accum_type_node
2545                          : unsigned_long_accum_type_node;
2546       if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2547         return unsignedp ? sat_unsigned_long_long_accum_type_node
2548                          : unsigned_long_long_accum_type_node;
2549
2550       if (mode == QQmode)
2551         return unsignedp ? sat_qq_type_node : qq_type_node;
2552       if (mode == HQmode)
2553         return unsignedp ? sat_hq_type_node : hq_type_node;
2554       if (mode == SQmode)
2555         return unsignedp ? sat_sq_type_node : sq_type_node;
2556       if (mode == DQmode)
2557         return unsignedp ? sat_dq_type_node : dq_type_node;
2558       if (mode == TQmode)
2559         return unsignedp ? sat_tq_type_node : tq_type_node;
2560
2561       if (mode == UQQmode)
2562         return unsignedp ? sat_uqq_type_node : uqq_type_node;
2563       if (mode == UHQmode)
2564         return unsignedp ? sat_uhq_type_node : uhq_type_node;
2565       if (mode == USQmode)
2566         return unsignedp ? sat_usq_type_node : usq_type_node;
2567       if (mode == UDQmode)
2568         return unsignedp ? sat_udq_type_node : udq_type_node;
2569       if (mode == UTQmode)
2570         return unsignedp ? sat_utq_type_node : utq_type_node;
2571
2572       if (mode == HAmode)
2573         return unsignedp ? sat_ha_type_node : ha_type_node;
2574       if (mode == SAmode)
2575         return unsignedp ? sat_sa_type_node : sa_type_node;
2576       if (mode == DAmode)
2577         return unsignedp ? sat_da_type_node : da_type_node;
2578       if (mode == TAmode)
2579         return unsignedp ? sat_ta_type_node : ta_type_node;
2580
2581       if (mode == UHAmode)
2582         return unsignedp ? sat_uha_type_node : uha_type_node;
2583       if (mode == USAmode)
2584         return unsignedp ? sat_usa_type_node : usa_type_node;
2585       if (mode == UDAmode)
2586         return unsignedp ? sat_uda_type_node : uda_type_node;
2587       if (mode == UTAmode)
2588         return unsignedp ? sat_uta_type_node : uta_type_node;
2589     }
2590
2591   for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2592     {
2593       tree type = TREE_VALUE (t);
2594       if (TYPE_MODE (type) == mode
2595           && VECTOR_TYPE_P (type) == VECTOR_MODE_P (mode)
2596           && !!unsignedp == !!TYPE_UNSIGNED (type))
2597         return type;
2598     }
2599   return NULL_TREE;
2600 }
2601
2602 tree
2603 c_common_unsigned_type (tree type)
2604 {
2605   return c_common_signed_or_unsigned_type (1, type);
2606 }
2607
2608 /* Return a signed type the same as TYPE in other respects.  */
2609
2610 tree
2611 c_common_signed_type (tree type)
2612 {
2613   return c_common_signed_or_unsigned_type (0, type);
2614 }
2615
2616 /* Return a type the same as TYPE except unsigned or
2617    signed according to UNSIGNEDP.  */
2618
2619 tree
2620 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2621 {
2622   tree type1;
2623   int i;
2624
2625   /* This block of code emulates the behavior of the old
2626      c_common_unsigned_type. In particular, it returns
2627      long_unsigned_type_node if passed a long, even when a int would
2628      have the same size. This is necessary for warnings to work
2629      correctly in archs where sizeof(int) == sizeof(long) */
2630
2631   type1 = TYPE_MAIN_VARIANT (type);
2632   if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2633     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2634   if (type1 == integer_type_node || type1 == unsigned_type_node)
2635     return unsignedp ? unsigned_type_node : integer_type_node;
2636   if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2637     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2638   if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2639     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2640   if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2641     return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2642
2643   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2644     if (int_n_enabled_p[i]
2645         && (type1 == int_n_trees[i].unsigned_type
2646             || type1 == int_n_trees[i].signed_type))
2647       return (unsignedp ? int_n_trees[i].unsigned_type
2648               : int_n_trees[i].signed_type);
2649
2650 #if HOST_BITS_PER_WIDE_INT >= 64
2651   if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2652     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2653 #endif
2654   if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2655     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2656   if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2657     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2658   if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2659     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2660   if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2661     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2662
2663 #define C_COMMON_FIXED_TYPES(NAME)          \
2664   if (type1 == short_ ## NAME ## _type_node \
2665       || type1 == unsigned_short_ ## NAME ## _type_node) \
2666     return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2667                      : short_ ## NAME ## _type_node; \
2668   if (type1 == NAME ## _type_node \
2669       || type1 == unsigned_ ## NAME ## _type_node) \
2670     return unsignedp ? unsigned_ ## NAME ## _type_node \
2671                      : NAME ## _type_node; \
2672   if (type1 == long_ ## NAME ## _type_node \
2673       || type1 == unsigned_long_ ## NAME ## _type_node) \
2674     return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2675                      : long_ ## NAME ## _type_node; \
2676   if (type1 == long_long_ ## NAME ## _type_node \
2677       || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2678     return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2679                      : long_long_ ## NAME ## _type_node;
2680
2681 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2682   if (type1 == NAME ## _type_node \
2683       || type1 == u ## NAME ## _type_node) \
2684     return unsignedp ? u ## NAME ## _type_node \
2685                      : NAME ## _type_node;
2686
2687 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2688   if (type1 == sat_ ## short_ ## NAME ## _type_node \
2689       || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2690     return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2691                      : sat_ ## short_ ## NAME ## _type_node; \
2692   if (type1 == sat_ ## NAME ## _type_node \
2693       || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2694     return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2695                      : sat_ ## NAME ## _type_node; \
2696   if (type1 == sat_ ## long_ ## NAME ## _type_node \
2697       || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2698     return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2699                      : sat_ ## long_ ## NAME ## _type_node; \
2700   if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2701       || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2702     return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2703                      : sat_ ## long_long_ ## NAME ## _type_node;
2704
2705 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME)     \
2706   if (type1 == sat_ ## NAME ## _type_node \
2707       || type1 == sat_ ## u ## NAME ## _type_node) \
2708     return unsignedp ? sat_ ## u ## NAME ## _type_node \
2709                      : sat_ ## NAME ## _type_node;
2710
2711   C_COMMON_FIXED_TYPES (fract);
2712   C_COMMON_FIXED_TYPES_SAT (fract);
2713   C_COMMON_FIXED_TYPES (accum);
2714   C_COMMON_FIXED_TYPES_SAT (accum);
2715
2716   C_COMMON_FIXED_MODE_TYPES (qq);
2717   C_COMMON_FIXED_MODE_TYPES (hq);
2718   C_COMMON_FIXED_MODE_TYPES (sq);
2719   C_COMMON_FIXED_MODE_TYPES (dq);
2720   C_COMMON_FIXED_MODE_TYPES (tq);
2721   C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2722   C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2723   C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2724   C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2725   C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2726   C_COMMON_FIXED_MODE_TYPES (ha);
2727   C_COMMON_FIXED_MODE_TYPES (sa);
2728   C_COMMON_FIXED_MODE_TYPES (da);
2729   C_COMMON_FIXED_MODE_TYPES (ta);
2730   C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2731   C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2732   C_COMMON_FIXED_MODE_TYPES_SAT (da);
2733   C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2734
2735   /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2736      the precision; they have precision set to match their range, but
2737      may use a wider mode to match an ABI.  If we change modes, we may
2738      wind up with bad conversions.  For INTEGER_TYPEs in C, must check
2739      the precision as well, so as to yield correct results for
2740      bit-field types.  C++ does not have these separate bit-field
2741      types, and producing a signed or unsigned variant of an
2742      ENUMERAL_TYPE may cause other problems as well.  */
2743
2744   if (!INTEGRAL_TYPE_P (type)
2745       || TYPE_UNSIGNED (type) == unsignedp)
2746     return type;
2747
2748 #define TYPE_OK(node)                                                       \
2749   (TYPE_MODE (type) == TYPE_MODE (node)                                     \
2750    && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2751   if (TYPE_OK (signed_char_type_node))
2752     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2753   if (TYPE_OK (integer_type_node))
2754     return unsignedp ? unsigned_type_node : integer_type_node;
2755   if (TYPE_OK (short_integer_type_node))
2756     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2757   if (TYPE_OK (long_integer_type_node))
2758     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2759   if (TYPE_OK (long_long_integer_type_node))
2760     return (unsignedp ? long_long_unsigned_type_node
2761             : long_long_integer_type_node);
2762
2763   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2764     if (int_n_enabled_p[i]
2765         && TYPE_MODE (type) == int_n_data[i].m
2766         && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2767       return (unsignedp ? int_n_trees[i].unsigned_type
2768               : int_n_trees[i].signed_type);
2769
2770 #if HOST_BITS_PER_WIDE_INT >= 64
2771   if (TYPE_OK (intTI_type_node))
2772     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2773 #endif
2774   if (TYPE_OK (intDI_type_node))
2775     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2776   if (TYPE_OK (intSI_type_node))
2777     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2778   if (TYPE_OK (intHI_type_node))
2779     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2780   if (TYPE_OK (intQI_type_node))
2781     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2782 #undef TYPE_OK
2783
2784   return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2785 }
2786
2787 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP.  */
2788
2789 tree
2790 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2791 {
2792   int i;
2793
2794   /* Extended integer types of the same width as a standard type have
2795      lesser rank, so those of the same width as int promote to int or
2796      unsigned int and are valid for printf formats expecting int or
2797      unsigned int.  To avoid such special cases, avoid creating
2798      extended integer types for bit-fields if a standard integer type
2799      is available.  */
2800   if (width == TYPE_PRECISION (integer_type_node))
2801     return unsignedp ? unsigned_type_node : integer_type_node;
2802   if (width == TYPE_PRECISION (signed_char_type_node))
2803     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2804   if (width == TYPE_PRECISION (short_integer_type_node))
2805     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2806   if (width == TYPE_PRECISION (long_integer_type_node))
2807     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2808   if (width == TYPE_PRECISION (long_long_integer_type_node))
2809     return (unsignedp ? long_long_unsigned_type_node
2810             : long_long_integer_type_node);
2811   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2812     if (int_n_enabled_p[i]
2813         && width == int_n_data[i].bitsize)
2814       return (unsignedp ? int_n_trees[i].unsigned_type
2815               : int_n_trees[i].signed_type);
2816   return build_nonstandard_integer_type (width, unsignedp);
2817 }
2818
2819 /* The C version of the register_builtin_type langhook.  */
2820
2821 void
2822 c_register_builtin_type (tree type, const char* name)
2823 {
2824   tree decl;
2825
2826   decl = build_decl (UNKNOWN_LOCATION,
2827                      TYPE_DECL, get_identifier (name), type);
2828   DECL_ARTIFICIAL (decl) = 1;
2829   if (!TYPE_NAME (type))
2830     TYPE_NAME (type) = decl;
2831   lang_hooks.decls.pushdecl (decl);
2832
2833   registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2834 }
2835 \f
2836 /* Print an error message for invalid operands to arith operation
2837    CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2838    RICHLOC is a rich location for the message, containing either
2839    three separate locations for each of the operator and operands
2840
2841       lhs op rhs
2842       ~~~ ^~ ~~~
2843
2844    (C FE), or one location ranging over all over them
2845
2846       lhs op rhs
2847       ~~~~^~~~~~
2848
2849    (C++ FE).  */
2850
2851 void
2852 binary_op_error (rich_location *richloc, enum tree_code code,
2853                  tree type0, tree type1)
2854 {
2855   const char *opname;
2856
2857   switch (code)
2858     {
2859     case PLUS_EXPR:
2860       opname = "+"; break;
2861     case MINUS_EXPR:
2862       opname = "-"; break;
2863     case MULT_EXPR:
2864       opname = "*"; break;
2865     case MAX_EXPR:
2866       opname = "max"; break;
2867     case MIN_EXPR:
2868       opname = "min"; break;
2869     case EQ_EXPR:
2870       opname = "=="; break;
2871     case NE_EXPR:
2872       opname = "!="; break;
2873     case LE_EXPR:
2874       opname = "<="; break;
2875     case GE_EXPR:
2876       opname = ">="; break;
2877     case LT_EXPR:
2878       opname = "<"; break;
2879     case GT_EXPR:
2880       opname = ">"; break;
2881     case LSHIFT_EXPR:
2882       opname = "<<"; break;
2883     case RSHIFT_EXPR:
2884       opname = ">>"; break;
2885     case TRUNC_MOD_EXPR:
2886     case FLOOR_MOD_EXPR:
2887       opname = "%"; break;
2888     case TRUNC_DIV_EXPR:
2889     case FLOOR_DIV_EXPR:
2890       opname = "/"; break;
2891     case BIT_AND_EXPR:
2892       opname = "&"; break;
2893     case BIT_IOR_EXPR:
2894       opname = "|"; break;
2895     case TRUTH_ANDIF_EXPR:
2896       opname = "&&"; break;
2897     case TRUTH_ORIF_EXPR:
2898       opname = "||"; break;
2899     case BIT_XOR_EXPR:
2900       opname = "^"; break;
2901     default:
2902       gcc_unreachable ();
2903     }
2904   error_at (richloc,
2905             "invalid operands to binary %s (have %qT and %qT)",
2906             opname, type0, type1);
2907 }
2908 \f
2909 /* Given an expression as a tree, return its original type.  Do this
2910    by stripping any conversion that preserves the sign and precision.  */
2911 static tree
2912 expr_original_type (tree expr)
2913 {
2914   STRIP_SIGN_NOPS (expr);
2915   return TREE_TYPE (expr);
2916 }
2917
2918 /* Subroutine of build_binary_op, used for comparison operations.
2919    See if the operands have both been converted from subword integer types
2920    and, if so, perhaps change them both back to their original type.
2921    This function is also responsible for converting the two operands
2922    to the proper common type for comparison.
2923
2924    The arguments of this function are all pointers to local variables
2925    of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2926    RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2927
2928    LOC is the location of the comparison.
2929
2930    If this function returns non-NULL_TREE, it means that the comparison has
2931    a constant value.  What this function returns is an expression for
2932    that value.  */
2933
2934 tree
2935 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2936                  tree *restype_ptr, enum tree_code *rescode_ptr)
2937 {
2938   tree type;
2939   tree op0 = *op0_ptr;
2940   tree op1 = *op1_ptr;
2941   int unsignedp0, unsignedp1;
2942   int real1, real2;
2943   tree primop0, primop1;
2944   enum tree_code code = *rescode_ptr;
2945
2946   /* Throw away any conversions to wider types
2947      already present in the operands.  */
2948
2949   primop0 = c_common_get_narrower (op0, &unsignedp0);
2950   primop1 = c_common_get_narrower (op1, &unsignedp1);
2951
2952   /* If primopN is first sign-extended from primopN's precision to opN's
2953      precision, then zero-extended from opN's precision to
2954      *restype_ptr precision, shortenings might be invalid.  */
2955   if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2956       && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2957       && !unsignedp0
2958       && TYPE_UNSIGNED (TREE_TYPE (op0)))
2959     primop0 = op0;
2960   if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2961       && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2962       && !unsignedp1
2963       && TYPE_UNSIGNED (TREE_TYPE (op1)))
2964     primop1 = op1;
2965
2966   /* Handle the case that OP0 does not *contain* a conversion
2967      but it *requires* conversion to FINAL_TYPE.  */
2968
2969   if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2970     unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2971   if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2972     unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2973
2974   /* If one of the operands must be floated, we cannot optimize.  */
2975   real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
2976   real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
2977
2978   /* If first arg is constant, swap the args (changing operation
2979      so value is preserved), for canonicalization.  Don't do this if
2980      the second arg is 0.  */
2981
2982   if (TREE_CONSTANT (primop0)
2983       && !integer_zerop (primop1) && !real_zerop (primop1)
2984       && !fixed_zerop (primop1))
2985     {
2986       std::swap (primop0, primop1);
2987       std::swap (op0, op1);
2988       *op0_ptr = op0;
2989       *op1_ptr = op1;
2990       std::swap (unsignedp0, unsignedp1);
2991       std::swap (real1, real2);
2992
2993       switch (code)
2994         {
2995         case LT_EXPR:
2996           code = GT_EXPR;
2997           break;
2998         case GT_EXPR:
2999           code = LT_EXPR;
3000           break;
3001         case LE_EXPR:
3002           code = GE_EXPR;
3003           break;
3004         case GE_EXPR:
3005           code = LE_EXPR;
3006           break;
3007         default:
3008           break;
3009         }
3010       *rescode_ptr = code;
3011     }
3012
3013   /* If comparing an integer against a constant more bits wide,
3014      maybe we can deduce a value of 1 or 0 independent of the data.
3015      Or else truncate the constant now
3016      rather than extend the variable at run time.
3017
3018      This is only interesting if the constant is the wider arg.
3019      Also, it is not safe if the constant is unsigned and the
3020      variable arg is signed, since in this case the variable
3021      would be sign-extended and then regarded as unsigned.
3022      Our technique fails in this case because the lowest/highest
3023      possible unsigned results don't follow naturally from the
3024      lowest/highest possible values of the variable operand.
3025      For just EQ_EXPR and NE_EXPR there is another technique that
3026      could be used: see if the constant can be faithfully represented
3027      in the other operand's type, by truncating it and reextending it
3028      and see if that preserves the constant's value.  */
3029
3030   if (!real1 && !real2
3031       && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
3032       && TREE_CODE (primop1) == INTEGER_CST
3033       && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
3034     {
3035       int min_gt, max_gt, min_lt, max_lt;
3036       tree maxval, minval;
3037       /* 1 if comparison is nominally unsigned.  */
3038       int unsignedp = TYPE_UNSIGNED (*restype_ptr);
3039       tree val;
3040
3041       type = c_common_signed_or_unsigned_type (unsignedp0,
3042                                                TREE_TYPE (primop0));
3043
3044       maxval = TYPE_MAX_VALUE (type);
3045       minval = TYPE_MIN_VALUE (type);
3046
3047       if (unsignedp && !unsignedp0)
3048         *restype_ptr = c_common_signed_type (*restype_ptr);
3049
3050       if (TREE_TYPE (primop1) != *restype_ptr)
3051         {
3052           /* Convert primop1 to target type, but do not introduce
3053              additional overflow.  We know primop1 is an int_cst.  */
3054           primop1 = force_fit_type (*restype_ptr,
3055                                     wi::to_wide
3056                                      (primop1,
3057                                       TYPE_PRECISION (*restype_ptr)),
3058                                     0, TREE_OVERFLOW (primop1));
3059         }
3060       if (type != *restype_ptr)
3061         {
3062           minval = convert (*restype_ptr, minval);
3063           maxval = convert (*restype_ptr, maxval);
3064         }
3065
3066       min_gt = tree_int_cst_lt (primop1, minval);
3067       max_gt = tree_int_cst_lt (primop1, maxval);
3068       min_lt = tree_int_cst_lt (minval, primop1);
3069       max_lt = tree_int_cst_lt (maxval, primop1);
3070
3071       val = 0;
3072       /* This used to be a switch, but Genix compiler can't handle that.  */
3073       if (code == NE_EXPR)
3074         {
3075           if (max_lt || min_gt)
3076             val = truthvalue_true_node;
3077         }
3078       else if (code == EQ_EXPR)
3079         {
3080           if (max_lt || min_gt)
3081             val = truthvalue_false_node;
3082         }
3083       else if (code == LT_EXPR)
3084         {
3085           if (max_lt)
3086             val = truthvalue_true_node;
3087           if (!min_lt)
3088             val = truthvalue_false_node;
3089         }
3090       else if (code == GT_EXPR)
3091         {
3092           if (min_gt)
3093             val = truthvalue_true_node;
3094           if (!max_gt)
3095             val = truthvalue_false_node;
3096         }
3097       else if (code == LE_EXPR)
3098         {
3099           if (!max_gt)
3100             val = truthvalue_true_node;
3101           if (min_gt)
3102             val = truthvalue_false_node;
3103         }
3104       else if (code == GE_EXPR)
3105         {
3106           if (!min_lt)
3107             val = truthvalue_true_node;
3108           if (max_lt)
3109             val = truthvalue_false_node;
3110         }
3111
3112       /* If primop0 was sign-extended and unsigned comparison specd,
3113          we did a signed comparison above using the signed type bounds.
3114          But the comparison we output must be unsigned.
3115
3116          Also, for inequalities, VAL is no good; but if the signed
3117          comparison had *any* fixed result, it follows that the
3118          unsigned comparison just tests the sign in reverse
3119          (positive values are LE, negative ones GE).
3120          So we can generate an unsigned comparison
3121          against an extreme value of the signed type.  */
3122
3123       if (unsignedp && !unsignedp0)
3124         {
3125           if (val != 0)
3126             switch (code)
3127               {
3128               case LT_EXPR:
3129               case GE_EXPR:
3130                 primop1 = TYPE_MIN_VALUE (type);
3131                 val = 0;
3132                 break;
3133
3134               case LE_EXPR:
3135               case GT_EXPR:
3136                 primop1 = TYPE_MAX_VALUE (type);
3137                 val = 0;
3138                 break;
3139
3140               default:
3141                 break;
3142               }
3143           type = c_common_unsigned_type (type);
3144         }
3145
3146       if (TREE_CODE (primop0) != INTEGER_CST
3147           /* Don't warn if it's from a (non-system) macro.  */
3148           && !(from_macro_expansion_at
3149                (expansion_point_location_if_in_system_header
3150                 (EXPR_LOCATION (primop0)))))
3151         {
3152           if (val == truthvalue_false_node)
3153             warning_at (loc, OPT_Wtype_limits,
3154                         "comparison is always false due to limited range of data type");
3155           if (val == truthvalue_true_node)
3156             warning_at (loc, OPT_Wtype_limits,
3157                         "comparison is always true due to limited range of data type");
3158         }
3159
3160       if (val != 0)
3161         {
3162           /* Don't forget to evaluate PRIMOP0 if it has side effects.  */
3163           if (TREE_SIDE_EFFECTS (primop0))
3164             return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
3165           return val;
3166         }
3167
3168       /* Value is not predetermined, but do the comparison
3169          in the type of the operand that is not constant.
3170          TYPE is already properly set.  */
3171     }
3172
3173   /* If either arg is decimal float and the other is float, find the
3174      proper common type to use for comparison.  */
3175   else if (real1 && real2
3176            && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3177            && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
3178     type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3179
3180   /* If either arg is decimal float and the other is float, fail.  */
3181   else if (real1 && real2
3182            && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3183                || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
3184     {
3185       type = *restype_ptr;
3186       primop0 = op0;
3187       primop1 = op1;
3188     }
3189
3190   else if (real1 && real2
3191            && (TYPE_PRECISION (TREE_TYPE (primop0))
3192                == TYPE_PRECISION (TREE_TYPE (primop1))))
3193     type = TREE_TYPE (primop0);
3194
3195   /* If args' natural types are both narrower than nominal type
3196      and both extend in the same manner, compare them
3197      in the type of the wider arg.
3198      Otherwise must actually extend both to the nominal
3199      common type lest different ways of extending
3200      alter the result.
3201      (eg, (short)-1 == (unsigned short)-1  should be 0.)  */
3202
3203   else if (unsignedp0 == unsignedp1 && real1 == real2
3204            && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
3205            && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
3206     {
3207       type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3208       type = c_common_signed_or_unsigned_type (unsignedp0
3209                                                || TYPE_UNSIGNED (*restype_ptr),
3210                                                type);
3211       /* Make sure shorter operand is extended the right way
3212          to match the longer operand.  */
3213       primop0
3214         = convert (c_common_signed_or_unsigned_type (unsignedp0,
3215                                                      TREE_TYPE (primop0)),
3216                    primop0);
3217       primop1
3218         = convert (c_common_signed_or_unsigned_type (unsignedp1,
3219                                                      TREE_TYPE (primop1)),
3220                    primop1);
3221     }
3222   else
3223     {
3224       /* Here we must do the comparison on the nominal type
3225          using the args exactly as we received them.  */
3226       type = *restype_ptr;
3227       primop0 = op0;
3228       primop1 = op1;
3229
3230       /* We want to fold unsigned comparisons of >= and < against zero.
3231          For these, we may also issue a warning if we have a non-constant
3232          compared against zero, where the zero was spelled as "0" (rather
3233          than merely folding to it).
3234          If we have at least one constant, then op1 is constant
3235          and we may have a non-constant expression as op0.  */
3236       if (!real1 && !real2 && integer_zerop (primop1)
3237           && TYPE_UNSIGNED (*restype_ptr))
3238         {
3239           tree value = NULL_TREE;
3240           /* All unsigned values are >= 0, so we warn.  However,
3241              if OP0 is a constant that is >= 0, the signedness of
3242              the comparison isn't an issue, so suppress the
3243              warning.  */
3244           tree folded_op0 = fold_for_warn (op0);
3245           bool warn = 
3246             warn_type_limits && !in_system_header_at (loc)
3247             && !(TREE_CODE (folded_op0) == INTEGER_CST
3248                  && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3249                                              folded_op0)))
3250             /* Do not warn for enumeration types.  */
3251             && (TREE_CODE (expr_original_type (folded_op0)) != ENUMERAL_TYPE);
3252           
3253           switch (code)
3254             {
3255             case GE_EXPR:
3256               if (warn)
3257                 warning_at (loc, OPT_Wtype_limits,
3258                             "comparison of unsigned expression in %<>= 0%> "
3259                             "is always true");
3260               value = truthvalue_true_node;
3261               break;
3262
3263             case LT_EXPR:
3264               if (warn)
3265                 warning_at (loc, OPT_Wtype_limits,
3266                             "comparison of unsigned expression in %<< 0%> "
3267                             "is always false");
3268               value = truthvalue_false_node;
3269               break;
3270
3271             default:
3272               break;
3273             }
3274
3275           if (value != NULL_TREE)
3276             {
3277               /* Don't forget to evaluate PRIMOP0 if it has side effects.  */
3278               if (TREE_SIDE_EFFECTS (primop0))
3279                 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3280                                primop0, value);
3281               return value;
3282             }
3283         }
3284     }
3285
3286   *op0_ptr = convert (type, primop0);
3287   *op1_ptr = convert (type, primop1);
3288
3289   *restype_ptr = truthvalue_type_node;
3290
3291   return NULL_TREE;
3292 }
3293 \f
3294 /* Return a tree for the sum or difference (RESULTCODE says which)
3295    of pointer PTROP and integer INTOP.  */
3296
3297 tree
3298 pointer_int_sum (location_t loc, enum tree_code resultcode,
3299                  tree ptrop, tree intop, bool complain)
3300 {
3301   tree size_exp, ret;
3302
3303   /* The result is a pointer of the same type that is being added.  */
3304   tree result_type = TREE_TYPE (ptrop);
3305
3306   if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
3307     {
3308       if (complain && warn_pointer_arith)
3309         pedwarn (loc, OPT_Wpointer_arith,
3310                  "pointer of type %<void *%> used in arithmetic");
3311       else if (!complain)
3312         return error_mark_node;
3313       size_exp = integer_one_node;
3314     }
3315   else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3316     {
3317       if (complain && warn_pointer_arith)
3318         pedwarn (loc, OPT_Wpointer_arith,
3319                  "pointer to a function used in arithmetic");
3320       else if (!complain)
3321         return error_mark_node;
3322       size_exp = integer_one_node;
3323     }
3324   else if (!verify_type_context (loc, TCTX_POINTER_ARITH,
3325                                  TREE_TYPE (result_type)))
3326     size_exp = integer_one_node;
3327   else
3328     {
3329       if (!complain && !COMPLETE_TYPE_P (TREE_TYPE (result_type)))
3330         return error_mark_node;
3331       size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3332       /* Wrap the pointer expression in a SAVE_EXPR to make sure it
3333          is evaluated first when the size expression may depend
3334          on it for VM types.  */
3335       if (TREE_SIDE_EFFECTS (size_exp)
3336           && TREE_SIDE_EFFECTS (ptrop)
3337           && variably_modified_type_p (TREE_TYPE (ptrop), NULL))
3338         {
3339           ptrop = save_expr (ptrop);
3340           size_exp = build2 (COMPOUND_EXPR, TREE_TYPE (intop), ptrop, size_exp);
3341         }
3342     }
3343
3344   /* We are manipulating pointer values, so we don't need to warn
3345      about relying on undefined signed overflow.  We disable the
3346      warning here because we use integer types so fold won't know that
3347      they are really pointers.  */
3348   fold_defer_overflow_warnings ();
3349
3350   /* If what we are about to multiply by the size of the elements
3351      contains a constant term, apply distributive law
3352      and multiply that constant term separately.
3353      This helps produce common subexpressions.  */
3354   if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3355       && !TREE_CONSTANT (intop)
3356       && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3357       && TREE_CONSTANT (size_exp)
3358       /* If the constant comes from pointer subtraction,
3359          skip this optimization--it would cause an error.  */
3360       && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3361       /* If the constant is unsigned, and smaller than the pointer size,
3362          then we must skip this optimization.  This is because it could cause
3363          an overflow error if the constant is negative but INTOP is not.  */
3364       && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (intop))
3365           || (TYPE_PRECISION (TREE_TYPE (intop))
3366               == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3367     {
3368       enum tree_code subcode = resultcode;
3369       tree int_type = TREE_TYPE (intop);
3370       if (TREE_CODE (intop) == MINUS_EXPR)
3371         subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3372       /* Convert both subexpression types to the type of intop,
3373          because weird cases involving pointer arithmetic
3374          can result in a sum or difference with different type args.  */
3375       ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3376                                subcode, ptrop,
3377                                convert (int_type, TREE_OPERAND (intop, 1)),
3378                                true);
3379       intop = convert (int_type, TREE_OPERAND (intop, 0));
3380     }
3381
3382   /* Convert the integer argument to a type the same size as sizetype
3383      so the multiply won't overflow spuriously.  */
3384   if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3385       || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3386     intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3387                                              TYPE_UNSIGNED (sizetype)), intop);
3388
3389   /* Replace the integer argument with a suitable product by the object size.
3390      Do this multiplication as signed, then convert to the appropriate type
3391      for the pointer operation and disregard an overflow that occurred only
3392      because of the sign-extension change in the latter conversion.  */
3393   {
3394     tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3395                               convert (TREE_TYPE (intop), size_exp));
3396     intop = convert (sizetype, t);
3397     if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3398       intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3399   }
3400
3401   /* Create the sum or difference.  */
3402   if (resultcode == MINUS_EXPR)
3403     intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3404
3405   ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3406
3407   fold_undefer_and_ignore_overflow_warnings ();
3408
3409   return ret;
3410 }
3411 \f
3412 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3413    and if NON_CONST is known not to be permitted in an evaluated part
3414    of a constant expression.  */
3415
3416 tree
3417 c_wrap_maybe_const (tree expr, bool non_const)
3418 {
3419   location_t loc = EXPR_LOCATION (expr);
3420
3421   /* This should never be called for C++.  */
3422   if (c_dialect_cxx ())
3423     gcc_unreachable ();
3424
3425   /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING.  */
3426   STRIP_TYPE_NOPS (expr);
3427   expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3428   C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3429   protected_set_expr_location (expr, loc);
3430
3431   return expr;
3432 }
3433
3434 /* Return whether EXPR is a declaration whose address can never be NULL.
3435    The address of the first struct member could be NULL only if it were
3436    accessed through a NULL pointer, and such an access would be invalid.
3437    The address of a weak symbol may be null unless it has a definition.  */
3438
3439 bool
3440 decl_with_nonnull_addr_p (const_tree expr)
3441 {
3442   if (!DECL_P (expr))
3443     return false;
3444
3445   if (TREE_CODE (expr) == FIELD_DECL
3446       || TREE_CODE (expr) == PARM_DECL
3447       || TREE_CODE (expr) == LABEL_DECL)
3448     return true;
3449
3450   if (!VAR_OR_FUNCTION_DECL_P (expr))
3451     return false;
3452
3453   if (!DECL_WEAK (expr))
3454     /* Ordinary (non-weak) symbols have nonnull addresses.  */
3455     return true;
3456
3457   if (DECL_INITIAL (expr) && DECL_INITIAL (expr) != error_mark_node)
3458     /* Initialized weak symbols have nonnull addresses.  */
3459     return true;
3460
3461   if (DECL_EXTERNAL (expr) || !TREE_STATIC (expr))
3462     /* Uninitialized extern weak symbols and weak symbols with no
3463        allocated storage might have a null address.  */
3464     return false;
3465
3466   tree attribs = DECL_ATTRIBUTES (expr);
3467   if (lookup_attribute ("weakref", attribs))
3468     /* Weakref symbols might have a null address unless their referent
3469        is known not to.  Don't bother following weakref targets here.  */
3470     return false;
3471
3472   return true;
3473 }
3474
3475 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3476    or for an `if' or `while' statement or ?..: exp.  It should already
3477    have been validated to be of suitable type; otherwise, a bad
3478    diagnostic may result.
3479
3480    The EXPR is located at LOCATION.
3481
3482    This preparation consists of taking the ordinary
3483    representation of an expression expr and producing a valid tree
3484    boolean expression describing whether expr is nonzero.  We could
3485    simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3486    but we optimize comparisons, &&, ||, and !.
3487
3488    The resulting type should always be `truthvalue_type_node'.  */
3489
3490 tree
3491 c_common_truthvalue_conversion (location_t location, tree expr)
3492 {
3493   STRIP_ANY_LOCATION_WRAPPER (expr);
3494   switch (TREE_CODE (expr))
3495     {
3496     case EQ_EXPR:   case NE_EXPR:   case UNEQ_EXPR: case LTGT_EXPR:
3497     case LE_EXPR:   case GE_EXPR:   case LT_EXPR:   case GT_EXPR:
3498     case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3499     case ORDERED_EXPR: case UNORDERED_EXPR:
3500       if (TREE_TYPE (expr) == truthvalue_type_node)
3501         return expr;
3502       expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3503                      TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3504       goto ret;
3505
3506     case TRUTH_ANDIF_EXPR:
3507     case TRUTH_ORIF_EXPR:
3508     case TRUTH_AND_EXPR:
3509     case TRUTH_OR_EXPR:
3510     case TRUTH_XOR_EXPR:
3511       if (TREE_TYPE (expr) == truthvalue_type_node)
3512         return expr;
3513       expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3514                      c_common_truthvalue_conversion (location,
3515                                                      TREE_OPERAND (expr, 0)),
3516                      c_common_truthvalue_conversion (location,
3517                                                      TREE_OPERAND (expr, 1)));
3518       goto ret;
3519
3520     case TRUTH_NOT_EXPR:
3521       if (TREE_TYPE (expr) == truthvalue_type_node)
3522         return expr;
3523       expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3524                      c_common_truthvalue_conversion (location,
3525                                                      TREE_OPERAND (expr, 0)));
3526       goto ret;
3527
3528     case ERROR_MARK:
3529       return expr;
3530
3531     case INTEGER_CST:
3532       if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3533           && !integer_zerop (expr)
3534           && !integer_onep (expr))
3535         warning_at (location, OPT_Wint_in_bool_context,
3536                     "enum constant in boolean context");
3537       return integer_zerop (expr) ? truthvalue_false_node
3538                                   : truthvalue_true_node;
3539
3540     case REAL_CST:
3541       return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3542              ? truthvalue_true_node
3543              : truthvalue_false_node;
3544
3545     case FIXED_CST:
3546       return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3547                             &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3548              ? truthvalue_true_node
3549              : truthvalue_false_node;
3550
3551     case FUNCTION_DECL:
3552       expr = build_unary_op (location, ADDR_EXPR, expr, false);
3553       /* Fall through.  */
3554
3555     case ADDR_EXPR:
3556       {
3557         tree inner = TREE_OPERAND (expr, 0);
3558         if (decl_with_nonnull_addr_p (inner)
3559             /* Check both EXPR and INNER for suppression.  */
3560             && !warning_suppressed_p (expr, OPT_Waddress)
3561             && !warning_suppressed_p (inner, OPT_Waddress))
3562           {
3563             /* Common Ada programmer's mistake.  */
3564             warning_at (location,
3565                         OPT_Waddress,
3566                         "the address of %qD will always evaluate as %<true%>",
3567                         inner);
3568             suppress_warning (inner, OPT_Waddress);
3569             return truthvalue_true_node;
3570           }
3571         break;
3572       }
3573
3574     case COMPLEX_EXPR:
3575       expr = build_binary_op (EXPR_LOCATION (expr),
3576                               (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3577                                ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3578                 c_common_truthvalue_conversion (location,
3579                                                 TREE_OPERAND (expr, 0)),
3580                 c_common_truthvalue_conversion (location,
3581                                                 TREE_OPERAND (expr, 1)),
3582                               false);
3583       goto ret;
3584
3585     case NEGATE_EXPR:
3586     case ABS_EXPR:
3587     case ABSU_EXPR:
3588     case FLOAT_EXPR:
3589     case EXCESS_PRECISION_EXPR:
3590       /* These don't change whether an object is nonzero or zero.  */
3591       return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3592
3593     case LROTATE_EXPR:
3594     case RROTATE_EXPR:
3595       /* These don't change whether an object is zero or nonzero, but
3596          we can't ignore them if their second arg has side-effects.  */
3597       if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3598         {
3599           expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3600                          TREE_OPERAND (expr, 1),
3601                          c_common_truthvalue_conversion
3602                          (location, TREE_OPERAND (expr, 0)));
3603           goto ret;
3604         }
3605       else
3606         return c_common_truthvalue_conversion (location,
3607                                                TREE_OPERAND (expr, 0));
3608
3609     case MULT_EXPR:
3610       warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3611                   "%<*%> in boolean context, suggest %<&&%> instead");
3612       break;
3613
3614     case LSHIFT_EXPR:
3615       /* We will only warn on signed shifts here, because the majority of
3616          false positive warnings happen in code where unsigned arithmetic
3617          was used in anticipation of a possible overflow.
3618          Furthermore, if we see an unsigned type here we know that the
3619          result of the shift is not subject to integer promotion rules.  */
3620       if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3621           && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3622         warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3623                     "%<<<%> in boolean context, did you mean %<<%>?");
3624       break;
3625
3626     case COND_EXPR:
3627       if (warn_int_in_bool_context
3628           && !from_macro_definition_at (EXPR_LOCATION (expr)))
3629         {
3630           tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3631           tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3632           if (TREE_CODE (val1) == INTEGER_CST
3633               && TREE_CODE (val2) == INTEGER_CST
3634               && !integer_zerop (val1)
3635               && !integer_zerop (val2)
3636               && (!integer_onep (val1)
3637                   || !integer_onep (val2)))
3638             warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3639                         "%<?:%> using integer constants in boolean context, "
3640                         "the expression will always evaluate to %<true%>");
3641           else if ((TREE_CODE (val1) == INTEGER_CST
3642                     && !integer_zerop (val1)
3643                     && !integer_onep (val1))
3644                    || (TREE_CODE (val2) == INTEGER_CST
3645                        && !integer_zerop (val2)
3646                        && !integer_onep (val2)))
3647             warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3648                         "%<?:%> using integer constants in boolean context");
3649         }
3650       /* Distribute the conversion into the arms of a COND_EXPR.  */
3651       if (c_dialect_cxx ())
3652         /* Avoid premature folding.  */
3653         break;
3654       else
3655         {
3656           int w = warn_int_in_bool_context;
3657           warn_int_in_bool_context = 0;
3658           /* Folding will happen later for C.  */
3659           expr = build3 (COND_EXPR, truthvalue_type_node,
3660                          TREE_OPERAND (expr, 0),
3661                          c_common_truthvalue_conversion (location,
3662                                                          TREE_OPERAND (expr, 1)),
3663                          c_common_truthvalue_conversion (location,
3664                                                          TREE_OPERAND (expr, 2)));
3665           warn_int_in_bool_context = w;
3666           goto ret;
3667         }
3668
3669     CASE_CONVERT:
3670       {
3671         tree totype = TREE_TYPE (expr);
3672         tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3673
3674         if (POINTER_TYPE_P (totype)
3675             && !c_inhibit_evaluation_warnings
3676             && TREE_CODE (fromtype) == REFERENCE_TYPE)
3677           {
3678             tree inner = expr;
3679             STRIP_NOPS (inner);
3680
3681             if (DECL_P (inner))
3682               warning_at (location,
3683                           OPT_Waddress,
3684                           "the compiler can assume that the address of "
3685                           "%qD will always evaluate to %<true%>",
3686                           inner);
3687           }
3688
3689         /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3690            since that affects how `default_conversion' will behave.  */
3691         if (TREE_CODE (totype) == REFERENCE_TYPE
3692             || TREE_CODE (fromtype) == REFERENCE_TYPE)
3693           break;
3694         /* Don't strip a conversion from C++0x scoped enum, since they
3695            don't implicitly convert to other types.  */
3696         if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3697             && ENUM_IS_SCOPED (fromtype))
3698           break;
3699         /* If this isn't narrowing the argument, we can ignore it.  */
3700         if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3701           {
3702             tree op0 = TREE_OPERAND (expr, 0);
3703             if ((TREE_CODE (fromtype) == POINTER_TYPE
3704                  && TREE_CODE (totype) == INTEGER_TYPE)
3705                 || warning_suppressed_p (expr, OPT_Waddress))
3706               /* Suppress -Waddress for casts to intptr_t, propagating
3707                  any suppression from the enclosing expression to its
3708                  operand.  */
3709               suppress_warning (op0, OPT_Waddress);
3710             return c_common_truthvalue_conversion (location, op0);
3711           }
3712       }
3713       break;
3714
3715     case MODIFY_EXPR:
3716       if (!warning_suppressed_p (expr, OPT_Wparentheses)
3717           && warn_parentheses
3718           && warning_at (location, OPT_Wparentheses,
3719                          "suggest parentheses around assignment used as "
3720                          "truth value"))
3721         suppress_warning (expr, OPT_Wparentheses);
3722       break;
3723
3724     case CONST_DECL:
3725       {
3726         tree folded_expr = fold_for_warn (expr);
3727         if (folded_expr != expr)
3728           return c_common_truthvalue_conversion (location, folded_expr);
3729       }
3730       break;
3731
3732     default:
3733       break;
3734     }
3735
3736   if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3737     {
3738       tree t = save_expr (expr);
3739       expr = (build_binary_op
3740               (EXPR_LOCATION (expr),
3741                (TREE_SIDE_EFFECTS (expr)
3742                 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3743         c_common_truthvalue_conversion
3744                (location,
3745                 build_unary_op (location, REALPART_EXPR, t, false)),
3746         c_common_truthvalue_conversion
3747                (location,
3748                 build_unary_op (location, IMAGPART_EXPR, t, false)),
3749                false));
3750       goto ret;
3751     }
3752
3753   if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
3754     {
3755       tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3756                                           FCONST0 (TYPE_MODE
3757                                                    (TREE_TYPE (expr))));
3758       return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3759     }
3760   else
3761     return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3762
3763  ret:
3764   protected_set_expr_location (expr, location);
3765   return expr;
3766 }
3767 \f
3768 static void def_builtin_1  (enum built_in_function fncode,
3769                             const char *name,
3770                             enum built_in_class fnclass,
3771                             tree fntype, tree libtype,
3772                             bool both_p, bool fallback_p, bool nonansi_p,
3773                             tree fnattrs, bool implicit_p);
3774
3775
3776 /* Apply the TYPE_QUALS to the new DECL.  */
3777
3778 void
3779 c_apply_type_quals_to_decl (int type_quals, tree decl)
3780 {
3781   tree type = TREE_TYPE (decl);
3782
3783   if (type == error_mark_node)
3784     return;
3785
3786   if ((type_quals & TYPE_QUAL_CONST)
3787       || (type && TREE_CODE (type) == REFERENCE_TYPE))
3788     /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3789        constructor can produce constant init, so rely on cp_finish_decl to
3790        clear TREE_READONLY if the variable has non-constant init.  */
3791     TREE_READONLY (decl) = 1;
3792   if (type_quals & TYPE_QUAL_VOLATILE)
3793     {
3794       TREE_SIDE_EFFECTS (decl) = 1;
3795       TREE_THIS_VOLATILE (decl) = 1;
3796     }
3797   if (type_quals & TYPE_QUAL_RESTRICT)
3798     {
3799       while (type && TREE_CODE (type) == ARRAY_TYPE)
3800         /* Allow 'restrict' on arrays of pointers.
3801            FIXME currently we just ignore it.  */
3802         type = TREE_TYPE (type);
3803       if (!type
3804           || !POINTER_TYPE_P (type)
3805           || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3806         error ("invalid use of %<restrict%>");
3807     }
3808 }
3809
3810 /* Return the typed-based alias set for T, which may be an expression
3811    or a type.  Return -1 if we don't do anything special.  */
3812
3813 alias_set_type
3814 c_common_get_alias_set (tree t)
3815 {
3816   /* For VLAs, use the alias set of the element type rather than the
3817      default of alias set 0 for types compared structurally.  */
3818   if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3819     {
3820       if (TREE_CODE (t) == ARRAY_TYPE)
3821         return get_alias_set (TREE_TYPE (t));
3822       return -1;
3823     }
3824
3825   /* That's all the expressions we handle specially.  */
3826   if (!TYPE_P (t))
3827     return -1;
3828
3829   /* Unlike char, char8_t doesn't alias. */
3830   if (flag_char8_t && t == char8_type_node)
3831     return -1;
3832
3833   /* The C standard guarantees that any object may be accessed via an
3834      lvalue that has narrow character type (except char8_t).  */
3835   if (t == char_type_node
3836       || t == signed_char_type_node
3837       || t == unsigned_char_type_node)
3838     return 0;
3839
3840   /* The C standard specifically allows aliasing between signed and
3841      unsigned variants of the same type.  We treat the signed
3842      variant as canonical.  */
3843   if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
3844     {
3845       tree t1 = c_common_signed_type (t);
3846
3847       /* t1 == t can happen for boolean nodes which are always unsigned.  */
3848       if (t1 != t)
3849         return get_alias_set (t1);
3850     }
3851
3852   return -1;
3853 }
3854 \f
3855 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3856    the IS_SIZEOF parameter indicates which operator is being applied.
3857    The COMPLAIN flag controls whether we should diagnose possibly
3858    ill-formed constructs or not.  LOC is the location of the SIZEOF or
3859    TYPEOF operator.  If MIN_ALIGNOF, the least alignment required for
3860    a type in any context should be returned, rather than the normal
3861    alignment for that type.  */
3862
3863 tree
3864 c_sizeof_or_alignof_type (location_t loc,
3865                           tree type, bool is_sizeof, bool min_alignof,
3866                           int complain)
3867 {
3868   const char *op_name;
3869   tree value = NULL;
3870   enum tree_code type_code = TREE_CODE (type);
3871
3872   op_name = is_sizeof ? "sizeof" : "__alignof__";
3873
3874   if (type_code == FUNCTION_TYPE)
3875     {
3876       if (is_sizeof)
3877         {
3878           if (complain && warn_pointer_arith)
3879             pedwarn (loc, OPT_Wpointer_arith,
3880                      "invalid application of %<sizeof%> to a function type");
3881           else if (!complain)
3882             return error_mark_node;
3883           value = size_one_node;
3884         }
3885       else
3886         {
3887           if (complain)
3888             {
3889               if (c_dialect_cxx ())
3890                 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3891                          "%<alignof%> applied to a function type");
3892               else
3893                 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3894                          "%<_Alignof%> applied to a function type");
3895             }
3896           value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3897         }
3898     }
3899   else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3900     {
3901       if (type_code == VOID_TYPE
3902           && complain && warn_pointer_arith)
3903         pedwarn (loc, OPT_Wpointer_arith,
3904                  "invalid application of %qs to a void type", op_name);
3905       else if (!complain)
3906         return error_mark_node;
3907       value = size_one_node;
3908     }
3909   else if (!COMPLETE_TYPE_P (type)
3910            && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3911     {
3912       if (complain)
3913         error_at (loc, "invalid application of %qs to incomplete type %qT",
3914                   op_name, type);
3915       return error_mark_node;
3916     }
3917   else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3918            && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3919     {
3920       if (complain)
3921         error_at (loc, "invalid application of %qs to array type %qT of "
3922                   "incomplete element type", op_name, type);
3923       return error_mark_node;
3924     }
3925   else if (!verify_type_context (loc, is_sizeof ? TCTX_SIZEOF : TCTX_ALIGNOF,
3926                                  type, !complain))
3927     {
3928       if (!complain)
3929         return error_mark_node;
3930       value = size_one_node;
3931     }
3932   else
3933     {
3934       if (is_sizeof)
3935         /* Convert in case a char is more than one unit.  */
3936         value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3937                                 size_int (TYPE_PRECISION (char_type_node)
3938                                           / BITS_PER_UNIT));
3939       else if (min_alignof)
3940         value = size_int (min_align_of_type (type));
3941       else
3942         value = size_int (TYPE_ALIGN_UNIT (type));
3943     }
3944
3945   /* VALUE will have the middle-end integer type sizetype.
3946      However, we should really return a value of type `size_t',
3947      which is just a typedef for an ordinary integer type.  */
3948   value = fold_convert_loc (loc, size_type_node, value);
3949
3950   return value;
3951 }
3952
3953 /* Implement the __alignof keyword: Return the minimum required
3954    alignment of EXPR, measured in bytes.  For VAR_DECLs,
3955    FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3956    from an "aligned" __attribute__ specification).  LOC is the
3957    location of the ALIGNOF operator.  */
3958
3959 tree
3960 c_alignof_expr (location_t loc, tree expr)
3961 {
3962   tree t;
3963
3964   if (!verify_type_context (loc, TCTX_ALIGNOF, TREE_TYPE (expr)))
3965     t = size_one_node;
3966
3967   else if (VAR_OR_FUNCTION_DECL_P (expr))
3968     t = size_int (DECL_ALIGN_UNIT (expr));
3969
3970   else if (TREE_CODE (expr) == COMPONENT_REF
3971            && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3972     {
3973       error_at (loc, "%<__alignof%> applied to a bit-field");
3974       t = size_one_node;
3975     }
3976   else if (TREE_CODE (expr) == COMPONENT_REF
3977            && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3978     t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3979
3980   else if (INDIRECT_REF_P (expr))
3981     {
3982       tree t = TREE_OPERAND (expr, 0);
3983       tree best = t;
3984       int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3985
3986       while (CONVERT_EXPR_P (t)
3987              && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3988         {
3989           int thisalign;
3990
3991           t = TREE_OPERAND (t, 0);
3992           thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3993           if (thisalign > bestalign)
3994             best = t, bestalign = thisalign;
3995         }
3996       return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
3997     }
3998   else
3999     return c_alignof (loc, TREE_TYPE (expr));
4000
4001   return fold_convert_loc (loc, size_type_node, t);
4002 }
4003 \f
4004 /* Handle C and C++ default attributes.  */
4005
4006 enum built_in_attribute
4007 {
4008 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
4009 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
4010 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
4011 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
4012 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
4013 #include "builtin-attrs.def"
4014 #undef DEF_ATTR_NULL_TREE
4015 #undef DEF_ATTR_INT
4016 #undef DEF_ATTR_STRING
4017 #undef DEF_ATTR_IDENT
4018 #undef DEF_ATTR_TREE_LIST
4019   ATTR_LAST
4020 };
4021
4022 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
4023
4024 static void c_init_attributes (void);
4025
4026 enum c_builtin_type
4027 {
4028 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
4029 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
4030 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
4031 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
4032 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4033 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4034 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
4035 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4036                             ARG6) NAME,
4037 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4038                             ARG6, ARG7) NAME,
4039 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4040                             ARG6, ARG7, ARG8) NAME,
4041 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4042                             ARG6, ARG7, ARG8, ARG9) NAME,
4043 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4044                              ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
4045 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4046                              ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
4047 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
4048 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
4049 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
4050 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4051 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4052 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4053                                 NAME,
4054 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4055                                 ARG6) NAME,
4056 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4057                                 ARG6, ARG7) NAME,
4058 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
4059 #include "builtin-types.def"
4060 #undef DEF_PRIMITIVE_TYPE
4061 #undef DEF_FUNCTION_TYPE_0
4062 #undef DEF_FUNCTION_TYPE_1
4063 #undef DEF_FUNCTION_TYPE_2
4064 #undef DEF_FUNCTION_TYPE_3
4065 #undef DEF_FUNCTION_TYPE_4
4066 #undef DEF_FUNCTION_TYPE_5
4067 #undef DEF_FUNCTION_TYPE_6
4068 #undef DEF_FUNCTION_TYPE_7
4069 #undef DEF_FUNCTION_TYPE_8
4070 #undef DEF_FUNCTION_TYPE_9
4071 #undef DEF_FUNCTION_TYPE_10
4072 #undef DEF_FUNCTION_TYPE_11
4073 #undef DEF_FUNCTION_TYPE_VAR_0
4074 #undef DEF_FUNCTION_TYPE_VAR_1
4075 #undef DEF_FUNCTION_TYPE_VAR_2
4076 #undef DEF_FUNCTION_TYPE_VAR_3
4077 #undef DEF_FUNCTION_TYPE_VAR_4
4078 #undef DEF_FUNCTION_TYPE_VAR_5
4079 #undef DEF_FUNCTION_TYPE_VAR_6
4080 #undef DEF_FUNCTION_TYPE_VAR_7
4081 #undef DEF_POINTER_TYPE
4082   BT_LAST
4083 };
4084
4085 typedef enum c_builtin_type builtin_type;
4086
4087 /* A temporary array for c_common_nodes_and_builtins.  Used in
4088    communication with def_fn_type.  */
4089 static tree builtin_types[(int) BT_LAST + 1];
4090
4091 /* A helper function for c_common_nodes_and_builtins.  Build function type
4092    for DEF with return type RET and N arguments.  If VAR is true, then the
4093    function should be variadic after those N arguments.
4094
4095    Takes special care not to ICE if any of the types involved are
4096    error_mark_node, which indicates that said type is not in fact available
4097    (see builtin_type_for_size).  In which case the function type as a whole
4098    should be error_mark_node.  */
4099
4100 static void
4101 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
4102 {
4103   tree t;
4104   tree *args = XALLOCAVEC (tree, n);
4105   va_list list;
4106   int i;
4107
4108   va_start (list, n);
4109   for (i = 0; i < n; ++i)
4110     {
4111       builtin_type a = (builtin_type) va_arg (list, int);
4112       t = builtin_types[a];
4113       if (t == error_mark_node)
4114         goto egress;
4115       args[i] = t;
4116     }
4117
4118   t = builtin_types[ret];
4119   if (t == error_mark_node)
4120     goto egress;
4121   if (var)
4122     t = build_varargs_function_type_array (t, n, args);
4123   else
4124     t = build_function_type_array (t, n, args);
4125
4126  egress:
4127   builtin_types[def] = t;
4128   va_end (list);
4129 }
4130
4131 /* Build builtin functions common to both C and C++ language
4132    frontends.  */
4133
4134 static void
4135 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
4136 {
4137 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
4138   builtin_types[ENUM] = VALUE;
4139 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
4140   def_fn_type (ENUM, RETURN, 0, 0);
4141 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
4142   def_fn_type (ENUM, RETURN, 0, 1, ARG1);
4143 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
4144   def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
4145 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4146   def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
4147 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4148   def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
4149 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4150   def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4151 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4152                             ARG6)                                       \
4153   def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4154 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4155                             ARG6, ARG7)                                 \
4156   def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4157 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4158                             ARG6, ARG7, ARG8)                           \
4159   def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,  \
4160                ARG7, ARG8);
4161 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4162                             ARG6, ARG7, ARG8, ARG9)                     \
4163   def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,  \
4164                ARG7, ARG8, ARG9);
4165 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4166                              ARG6, ARG7, ARG8, ARG9, ARG10)              \
4167   def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,  \
4168                ARG7, ARG8, ARG9, ARG10);
4169 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4170                              ARG6, ARG7, ARG8, ARG9, ARG10, ARG11)       \
4171   def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,  \
4172                ARG7, ARG8, ARG9, ARG10, ARG11);
4173 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
4174   def_fn_type (ENUM, RETURN, 1, 0);
4175 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
4176   def_fn_type (ENUM, RETURN, 1, 1, ARG1);
4177 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
4178   def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
4179 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4180   def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
4181 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4182   def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
4183 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4184   def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4185 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4186                                 ARG6) \
4187   def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4188 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4189                                 ARG6, ARG7)                             \
4190   def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4191 #define DEF_POINTER_TYPE(ENUM, TYPE) \
4192   builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
4193
4194 #include "builtin-types.def"
4195
4196 #undef DEF_PRIMITIVE_TYPE
4197 #undef DEF_FUNCTION_TYPE_0
4198 #undef DEF_FUNCTION_TYPE_1
4199 #undef DEF_FUNCTION_TYPE_2
4200 #undef DEF_FUNCTION_TYPE_3
4201 #undef DEF_FUNCTION_TYPE_4
4202 #undef DEF_FUNCTION_TYPE_5
4203 #undef DEF_FUNCTION_TYPE_6
4204 #undef DEF_FUNCTION_TYPE_7
4205 #undef DEF_FUNCTION_TYPE_8
4206 #undef DEF_FUNCTION_TYPE_9
4207 #undef DEF_FUNCTION_TYPE_10
4208 #undef DEF_FUNCTION_TYPE_11
4209 #undef DEF_FUNCTION_TYPE_VAR_0
4210 #undef DEF_FUNCTION_TYPE_VAR_1
4211 #undef DEF_FUNCTION_TYPE_VAR_2
4212 #undef DEF_FUNCTION_TYPE_VAR_3
4213 #undef DEF_FUNCTION_TYPE_VAR_4
4214 #undef DEF_FUNCTION_TYPE_VAR_5
4215 #undef DEF_FUNCTION_TYPE_VAR_6
4216 #undef DEF_FUNCTION_TYPE_VAR_7
4217 #undef DEF_POINTER_TYPE
4218   builtin_types[(int) BT_LAST] = NULL_TREE;
4219
4220   c_init_attributes ();
4221
4222 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
4223                     NONANSI_P, ATTRS, IMPLICIT, COND)                   \
4224   if (NAME && COND)                                                     \
4225     def_builtin_1 (ENUM, NAME, CLASS,                                   \
4226                    builtin_types[(int) TYPE],                           \
4227                    builtin_types[(int) LIBTYPE],                        \
4228                    BOTH_P, FALLBACK_P, NONANSI_P,                       \
4229                    built_in_attributes[(int) ATTRS], IMPLICIT);
4230 #include "builtins.def"
4231
4232   targetm.init_builtins ();
4233
4234   build_common_builtin_nodes ();
4235 }
4236
4237 /* Like get_identifier, but avoid warnings about null arguments when
4238    the argument may be NULL for targets where GCC lacks stdint.h type
4239    information.  */
4240
4241 static inline tree
4242 c_get_ident (const char *id)
4243 {
4244   return get_identifier (id);
4245 }
4246
4247 /* Build tree nodes and builtin functions common to both C and C++ language
4248    frontends.  */
4249
4250 void
4251 c_common_nodes_and_builtins (void)
4252 {
4253   int char8_type_size;
4254   int char16_type_size;
4255   int char32_type_size;
4256   int wchar_type_size;
4257   tree array_domain_type;
4258   tree va_list_ref_type_node;
4259   tree va_list_arg_type_node;
4260   int i;
4261
4262   build_common_tree_nodes (flag_signed_char);
4263
4264   /* Define `int' and `char' first so that dbx will output them first.  */
4265   record_builtin_type (RID_INT, NULL, integer_type_node);
4266   record_builtin_type (RID_CHAR, "char", char_type_node);
4267
4268   /* `signed' is the same as `int'.  FIXME: the declarations of "signed",
4269      "unsigned long", "long long unsigned" and "unsigned short" were in C++
4270      but not C.  Are the conditionals here needed?  */
4271   if (c_dialect_cxx ())
4272     record_builtin_type (RID_SIGNED, NULL, integer_type_node);
4273   record_builtin_type (RID_LONG, "long int", long_integer_type_node);
4274   record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
4275   record_builtin_type (RID_MAX, "long unsigned int",
4276                        long_unsigned_type_node);
4277
4278   for (i = 0; i < NUM_INT_N_ENTS; i ++)
4279     {
4280       char name[25];
4281
4282       sprintf (name, "__int%d", int_n_data[i].bitsize);
4283       record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4284                            int_n_trees[i].signed_type);
4285       sprintf (name, "__int%d__", int_n_data[i].bitsize);
4286       record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4287                            int_n_trees[i].signed_type);
4288       ridpointers[RID_FIRST_INT_N + i]
4289         = DECL_NAME (TYPE_NAME (int_n_trees[i].signed_type));
4290
4291       sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
4292       record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4293       sprintf (name, "__int%d__ unsigned", int_n_data[i].bitsize);
4294       record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4295     }
4296
4297   if (c_dialect_cxx ())
4298     record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
4299   record_builtin_type (RID_MAX, "long long int",
4300                        long_long_integer_type_node);
4301   record_builtin_type (RID_MAX, "long long unsigned int",
4302                        long_long_unsigned_type_node);
4303   if (c_dialect_cxx ())
4304     record_builtin_type (RID_MAX, "long long unsigned",
4305                          long_long_unsigned_type_node);
4306   record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4307   record_builtin_type (RID_MAX, "short unsigned int",
4308                        short_unsigned_type_node);
4309   if (c_dialect_cxx ())
4310     record_builtin_type (RID_MAX, "unsigned short",
4311                          short_unsigned_type_node);
4312
4313   /* Define both `signed char' and `unsigned char'.  */
4314   record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4315   record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4316
4317   /* These are types that c_common_type_for_size and
4318      c_common_type_for_mode use.  */
4319   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4320                                          TYPE_DECL, NULL_TREE,
4321                                          intQI_type_node));
4322   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4323                                          TYPE_DECL, NULL_TREE,
4324                                          intHI_type_node));
4325   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4326                                          TYPE_DECL, NULL_TREE,
4327                                          intSI_type_node));
4328   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4329                                          TYPE_DECL, NULL_TREE,
4330                                          intDI_type_node));
4331 #if HOST_BITS_PER_WIDE_INT >= 64
4332   /* Note that this is different than the __int128 type that's part of
4333      the generic __intN support.  */
4334   if (targetm.scalar_mode_supported_p (TImode))
4335     lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4336                                            TYPE_DECL,
4337                                            get_identifier ("__int128_t"),
4338                                            intTI_type_node));
4339 #endif
4340   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4341                                          TYPE_DECL, NULL_TREE,
4342                                          unsigned_intQI_type_node));
4343   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4344                                          TYPE_DECL, NULL_TREE,
4345                                          unsigned_intHI_type_node));
4346   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4347                                          TYPE_DECL, NULL_TREE,
4348                                          unsigned_intSI_type_node));
4349   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4350                                          TYPE_DECL, NULL_TREE,
4351                                          unsigned_intDI_type_node));
4352 #if HOST_BITS_PER_WIDE_INT >= 64
4353   if (targetm.scalar_mode_supported_p (TImode))
4354     lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4355                                            TYPE_DECL,
4356                                            get_identifier ("__uint128_t"),
4357                                            unsigned_intTI_type_node));
4358 #endif
4359
4360   /* Create the widest literal types.  */
4361   if (targetm.scalar_mode_supported_p (TImode))
4362     {
4363       widest_integer_literal_type_node = intTI_type_node;
4364       widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4365     }
4366   else
4367     {
4368       widest_integer_literal_type_node = intDI_type_node;
4369       widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4370     }
4371
4372   signed_size_type_node = c_common_signed_type (size_type_node);
4373
4374   pid_type_node =
4375     TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4376
4377   record_builtin_type (RID_FLOAT, NULL, float_type_node);
4378   record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4379   record_builtin_type (RID_MAX, "long double", long_double_type_node);
4380
4381   if (!c_dialect_cxx ())
4382     for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4383       if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4384         record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4385                              FLOATN_NX_TYPE_NODE (i));
4386
4387   /* Only supported decimal floating point extension if the target
4388      actually supports underlying modes. */
4389   if (targetm.scalar_mode_supported_p (SDmode)
4390       && targetm.scalar_mode_supported_p (DDmode)
4391       && targetm.scalar_mode_supported_p (TDmode))
4392     {
4393       record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4394       record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4395       record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4396     }
4397
4398   if (targetm.fixed_point_supported_p ())
4399     {
4400       record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4401       record_builtin_type (RID_FRACT, NULL, fract_type_node);
4402       record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4403       record_builtin_type (RID_MAX, "long long _Fract",
4404                            long_long_fract_type_node);
4405       record_builtin_type (RID_MAX, "unsigned short _Fract",
4406                            unsigned_short_fract_type_node);
4407       record_builtin_type (RID_MAX, "unsigned _Fract",
4408                            unsigned_fract_type_node);
4409       record_builtin_type (RID_MAX, "unsigned long _Fract",
4410                            unsigned_long_fract_type_node);
4411       record_builtin_type (RID_MAX, "unsigned long long _Fract",
4412                            unsigned_long_long_fract_type_node);
4413       record_builtin_type (RID_MAX, "_Sat short _Fract",
4414                            sat_short_fract_type_node);
4415       record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4416       record_builtin_type (RID_MAX, "_Sat long _Fract",
4417                            sat_long_fract_type_node);
4418       record_builtin_type (RID_MAX, "_Sat long long _Fract",
4419                            sat_long_long_fract_type_node);
4420       record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4421                            sat_unsigned_short_fract_type_node);
4422       record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4423                            sat_unsigned_fract_type_node);
4424       record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4425                            sat_unsigned_long_fract_type_node);
4426       record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4427                            sat_unsigned_long_long_fract_type_node);
4428       record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4429       record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4430       record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4431       record_builtin_type (RID_MAX, "long long _Accum",
4432                            long_long_accum_type_node);
4433       record_builtin_type (RID_MAX, "unsigned short _Accum",
4434                            unsigned_short_accum_type_node);
4435       record_builtin_type (RID_MAX, "unsigned _Accum",
4436                            unsigned_accum_type_node);
4437       record_builtin_type (RID_MAX, "unsigned long _Accum",
4438                            unsigned_long_accum_type_node);
4439       record_builtin_type (RID_MAX, "unsigned long long _Accum",
4440                            unsigned_long_long_accum_type_node);
4441       record_builtin_type (RID_MAX, "_Sat short _Accum",
4442                            sat_short_accum_type_node);
4443       record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4444       record_builtin_type (RID_MAX, "_Sat long _Accum",
4445                            sat_long_accum_type_node);
4446       record_builtin_type (RID_MAX, "_Sat long long _Accum",
4447                           sat_long_long_accum_type_node);
4448       record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4449                            sat_unsigned_short_accum_type_node);
4450       record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4451                            sat_unsigned_accum_type_node);
4452       record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4453                            sat_unsigned_long_accum_type_node);
4454       record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4455                            sat_unsigned_long_long_accum_type_node);
4456
4457     }
4458
4459   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4460                                          TYPE_DECL,
4461                                          get_identifier ("complex int"),
4462                                          complex_integer_type_node));
4463   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4464                                          TYPE_DECL,
4465                                          get_identifier ("complex float"),
4466                                          complex_float_type_node));
4467   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4468                                          TYPE_DECL,
4469                                          get_identifier ("complex double"),
4470                                          complex_double_type_node));
4471   lang_hooks.decls.pushdecl
4472     (build_decl (UNKNOWN_LOCATION,
4473                  TYPE_DECL, get_identifier ("complex long double"),
4474                  complex_long_double_type_node));
4475
4476   if (!c_dialect_cxx ())
4477     for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4478       if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4479         {
4480           char buf[30];
4481           sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4482                    floatn_nx_types[i].extended ? "x" : "");
4483           lang_hooks.decls.pushdecl
4484             (build_decl (UNKNOWN_LOCATION,
4485                          TYPE_DECL,
4486                          get_identifier (buf),
4487                          COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4488         }
4489
4490   /* Make fileptr_type_node a distinct void * type until
4491      FILE type is defined.  Likewise for const struct tm*.  */
4492   for (unsigned i = 0; i < ARRAY_SIZE (builtin_structptr_types); ++i)
4493     builtin_structptr_types[i].node
4494       = build_variant_type_copy (builtin_structptr_types[i].base);
4495
4496   record_builtin_type (RID_VOID, NULL, void_type_node);
4497
4498   /* Set the TYPE_NAME for any variants that were built before
4499      record_builtin_type gave names to the built-in types. */
4500   {
4501     tree void_name = TYPE_NAME (void_type_node);
4502     TYPE_NAME (void_type_node) = NULL_TREE;
4503     TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4504       = void_name;
4505     TYPE_NAME (void_type_node) = void_name;
4506   }
4507
4508   void_list_node = build_void_list_node ();
4509
4510   /* Make a type to be the domain of a few array types
4511      whose domains don't really matter.
4512      200 is small enough that it always fits in size_t
4513      and large enough that it can hold most function names for the
4514      initializations of __FUNCTION__ and __PRETTY_FUNCTION__.  */
4515   array_domain_type = build_index_type (size_int (200));
4516
4517   /* Make a type for arrays of characters.
4518      With luck nothing will ever really depend on the length of this
4519      array type.  */
4520   char_array_type_node
4521     = build_array_type (char_type_node, array_domain_type);
4522
4523   string_type_node = build_pointer_type (char_type_node);
4524   const_string_type_node
4525     = build_pointer_type (build_qualified_type
4526                           (char_type_node, TYPE_QUAL_CONST));
4527
4528   /* This is special for C++ so functions can be overloaded.  */
4529   wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4530   wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4531   wchar_type_size = TYPE_PRECISION (wchar_type_node);
4532   underlying_wchar_type_node = wchar_type_node;
4533   if (c_dialect_cxx ())
4534     {
4535       if (TYPE_UNSIGNED (wchar_type_node))
4536         wchar_type_node = make_unsigned_type (wchar_type_size);
4537       else
4538         wchar_type_node = make_signed_type (wchar_type_size);
4539       record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4540     }
4541
4542   /* This is for wide string constants.  */
4543   wchar_array_type_node
4544     = build_array_type (wchar_type_node, array_domain_type);
4545
4546   /* Define 'char8_t'.  */
4547   char8_type_node = get_identifier (CHAR8_TYPE);
4548   char8_type_node = TREE_TYPE (identifier_global_value (char8_type_node));
4549   char8_type_size = TYPE_PRECISION (char8_type_node);
4550   if (c_dialect_cxx ())
4551     {
4552       char8_type_node = make_unsigned_type (char8_type_size);
4553       TYPE_STRING_FLAG (char8_type_node) = true;
4554
4555       if (flag_char8_t)
4556         record_builtin_type (RID_CHAR8, "char8_t", char8_type_node);
4557     }
4558
4559   /* This is for UTF-8 string constants.  */
4560   char8_array_type_node
4561     = build_array_type (char8_type_node, array_domain_type);
4562
4563   /* Define 'char16_t'.  */
4564   char16_type_node = get_identifier (CHAR16_TYPE);
4565   char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4566   char16_type_size = TYPE_PRECISION (char16_type_node);
4567   if (c_dialect_cxx ())
4568     {
4569       char16_type_node = make_unsigned_type (char16_type_size);
4570
4571       if (cxx_dialect >= cxx11)
4572         record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4573     }
4574
4575   /* This is for UTF-16 string constants.  */
4576   char16_array_type_node
4577     = build_array_type (char16_type_node, array_domain_type);
4578
4579   /* Define 'char32_t'.  */
4580   char32_type_node = get_identifier (CHAR32_TYPE);
4581   char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4582   char32_type_size = TYPE_PRECISION (char32_type_node);
4583   if (c_dialect_cxx ())
4584     {
4585       char32_type_node = make_unsigned_type (char32_type_size);
4586
4587       if (cxx_dialect >= cxx11)
4588         record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4589     }
4590
4591   /* This is for UTF-32 string constants.  */
4592   char32_array_type_node
4593     = build_array_type (char32_type_node, array_domain_type);
4594
4595   wint_type_node =
4596     TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4597
4598   intmax_type_node =
4599     TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4600   uintmax_type_node =
4601     TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4602
4603   if (SIG_ATOMIC_TYPE)
4604     sig_atomic_type_node =
4605       TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4606   if (INT8_TYPE)
4607     int8_type_node =
4608       TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4609   if (INT16_TYPE)
4610     int16_type_node =
4611       TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4612   if (INT32_TYPE)
4613     int32_type_node =
4614       TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4615   if (INT64_TYPE)
4616     int64_type_node =
4617       TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4618   if (UINT8_TYPE)
4619     uint8_type_node =
4620       TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4621   if (UINT16_TYPE)
4622     c_uint16_type_node = uint16_type_node =
4623       TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4624   if (UINT32_TYPE)
4625     c_uint32_type_node = uint32_type_node =
4626       TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4627   if (UINT64_TYPE)
4628     c_uint64_type_node = uint64_type_node =
4629       TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4630   if (INT_LEAST8_TYPE)
4631     int_least8_type_node =
4632       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4633   if (INT_LEAST16_TYPE)
4634     int_least16_type_node =
4635       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4636   if (INT_LEAST32_TYPE)
4637     int_least32_type_node =
4638       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4639   if (INT_LEAST64_TYPE)
4640     int_least64_type_node =
4641       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4642   if (UINT_LEAST8_TYPE)
4643     uint_least8_type_node =
4644       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4645   if (UINT_LEAST16_TYPE)
4646     uint_least16_type_node =
4647       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4648   if (UINT_LEAST32_TYPE)
4649     uint_least32_type_node =
4650       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4651   if (UINT_LEAST64_TYPE)
4652     uint_least64_type_node =
4653       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4654   if (INT_FAST8_TYPE)
4655     int_fast8_type_node =
4656       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4657   if (INT_FAST16_TYPE)
4658     int_fast16_type_node =
4659       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4660   if (INT_FAST32_TYPE)
4661     int_fast32_type_node =
4662       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4663   if (INT_FAST64_TYPE)
4664     int_fast64_type_node =
4665       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4666   if (UINT_FAST8_TYPE)
4667     uint_fast8_type_node =
4668       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4669   if (UINT_FAST16_TYPE)
4670     uint_fast16_type_node =
4671       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4672   if (UINT_FAST32_TYPE)
4673     uint_fast32_type_node =
4674       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4675   if (UINT_FAST64_TYPE)
4676     uint_fast64_type_node =
4677       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4678   if (INTPTR_TYPE)
4679     intptr_type_node =
4680       TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4681   if (UINTPTR_TYPE)
4682     uintptr_type_node =
4683       TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4684
4685   default_function_type
4686     = build_varargs_function_type_list (integer_type_node, NULL_TREE);
4687   unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4688
4689   lang_hooks.decls.pushdecl
4690     (build_decl (UNKNOWN_LOCATION,
4691                  TYPE_DECL, get_identifier ("__builtin_va_list"),
4692                  va_list_type_node));
4693   if (targetm.enum_va_list_p)
4694     {
4695       int l;
4696       const char *pname;
4697       tree ptype;
4698
4699       for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4700         {
4701           lang_hooks.decls.pushdecl
4702             (build_decl (UNKNOWN_LOCATION,
4703                          TYPE_DECL, get_identifier (pname),
4704                          ptype));
4705
4706         }
4707     }
4708
4709   if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4710     {
4711       va_list_arg_type_node = va_list_ref_type_node =
4712         build_pointer_type (TREE_TYPE (va_list_type_node));
4713     }
4714   else
4715     {
4716       va_list_arg_type_node = va_list_type_node;
4717       va_list_ref_type_node = build_reference_type (va_list_type_node);
4718     }
4719
4720   c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4721
4722   main_identifier_node = get_identifier ("main");
4723
4724   /* Create the built-in __null node.  It is important that this is
4725      not shared.  */
4726   null_node = make_int_cst (1, 1);
4727   TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4728
4729   /* Create the built-in nullptr node.  This part of its initialization is
4730      common to C and C++.  The front ends can further adjust its definition
4731      in {c,cxx}_init_decl_processing.  In particular, we aren't setting the
4732      alignment here for C++ backward ABI bug compatibility.  */
4733   nullptr_type_node = make_node (NULLPTR_TYPE);
4734   TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4735   TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4736   TYPE_UNSIGNED (nullptr_type_node) = 1;
4737   TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4738   SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4739   nullptr_node = build_int_cst (nullptr_type_node, 0);
4740
4741   /* Since builtin_types isn't gc'ed, don't export these nodes.  */
4742   memset (builtin_types, 0, sizeof (builtin_types));
4743 }
4744
4745 /* The number of named compound-literals generated thus far.  */
4746 static GTY(()) int compound_literal_number;
4747
4748 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal.  */
4749
4750 void
4751 set_compound_literal_name (tree decl)
4752 {
4753   char *name;
4754   ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4755                            compound_literal_number);
4756   compound_literal_number++;
4757   DECL_NAME (decl) = get_identifier (name);
4758 }
4759
4760 /* build_va_arg helper function.  Return a VA_ARG_EXPR with location LOC, type
4761    TYPE and operand OP.  */
4762
4763 static tree
4764 build_va_arg_1 (location_t loc, tree type, tree op)
4765 {
4766   tree expr = build1 (VA_ARG_EXPR, type, op);
4767   SET_EXPR_LOCATION (expr, loc);
4768   return expr;
4769 }
4770
4771 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4772    va_arg (EXPR, TYPE) at source location LOC.  */
4773
4774 tree
4775 build_va_arg (location_t loc, tree expr, tree type)
4776 {
4777   tree va_type = TREE_TYPE (expr);
4778   tree canon_va_type = (va_type == error_mark_node
4779                         ? error_mark_node
4780                         : targetm.canonical_va_list_type (va_type));
4781
4782   if (va_type == error_mark_node
4783       || canon_va_type == NULL_TREE)
4784     {
4785       if (canon_va_type == NULL_TREE)
4786         error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4787
4788       /* Let's handle things neutrally, if expr:
4789          - has undeclared type, or
4790          - is not an va_list type.  */
4791       return build_va_arg_1 (loc, type, error_mark_node);
4792     }
4793
4794   if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4795     {
4796       /* Case 1: Not an array type.  */
4797
4798       /* Take the address, to get '&ap'.  Note that &ap is not a va_list
4799          type.  */
4800       c_common_mark_addressable_vec (expr);
4801       expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4802
4803       return build_va_arg_1 (loc, type, expr);
4804     }
4805
4806   /* Case 2: Array type.
4807
4808      Background:
4809
4810      For contrast, let's start with the simple case (case 1).  If
4811      canon_va_type is not an array type, but say a char *, then when
4812      passing-by-value a va_list, the type of the va_list param decl is
4813      the same as for another va_list decl (all ap's are char *):
4814
4815      f2_1 (char * ap)
4816        D.1815 = VA_ARG (&ap, 0B, 1);
4817        return D.1815;
4818
4819      f2 (int i)
4820        char * ap.0;
4821        char * ap;
4822        __builtin_va_start (&ap, 0);
4823        ap.0 = ap;
4824        res = f2_1 (ap.0);
4825        __builtin_va_end (&ap);
4826        D.1812 = res;
4827        return D.1812;
4828
4829      However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4830      va_list the type of the va_list param decl (case 2b, struct * ap) is not
4831      the same as for another va_list decl (case 2a, struct ap[1]).
4832
4833      f2_1 (struct  * ap)
4834        D.1844 = VA_ARG (ap, 0B, 0);
4835        return D.1844;
4836
4837      f2 (int i)
4838        struct  ap[1];
4839        __builtin_va_start (&ap, 0);
4840        res = f2_1 (&ap);
4841        __builtin_va_end (&ap);
4842        D.1841 = res;
4843        return D.1841;
4844
4845      Case 2b is different because:
4846      - on the callee side, the parm decl has declared type va_list, but
4847        grokdeclarator changes the type of the parm decl to a pointer to the
4848        array elem type.
4849      - on the caller side, the pass-by-value uses &ap.
4850
4851      We unify these two cases (case 2a: va_list is array type,
4852      case 2b: va_list is pointer to array elem type), by adding '&' for the
4853      array type case, such that we have a pointer to array elem in both
4854      cases.  */
4855
4856   if (TREE_CODE (va_type) == ARRAY_TYPE)
4857     {
4858       /* Case 2a: va_list is array type.  */
4859
4860       /* Take the address, to get '&ap'.  Make sure it's a pointer to array
4861          elem type.  */
4862       c_common_mark_addressable_vec (expr);
4863       expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4864                      expr);
4865
4866       /* Verify that &ap is still recognized as having va_list type.  */
4867       tree canon_expr_type
4868         = targetm.canonical_va_list_type (TREE_TYPE (expr));
4869       gcc_assert (canon_expr_type != NULL_TREE);
4870     }
4871   else
4872     {
4873       /* Case 2b: va_list is pointer to array elem type.  */
4874       gcc_assert (POINTER_TYPE_P (va_type));
4875
4876       /* Comparison as in std_canonical_va_list_type.  */
4877       gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4878                   == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4879
4880       /* Don't take the address.  We've already got '&ap'.  */
4881       ;
4882     }
4883
4884   return build_va_arg_1 (loc, type, expr);
4885 }
4886
4887
4888 /* Linked list of disabled built-in functions.  */
4889
4890 struct disabled_builtin
4891 {
4892   const char *name;
4893   struct disabled_builtin *next;
4894 };
4895 static disabled_builtin *disabled_builtins = NULL;
4896
4897 static bool builtin_function_disabled_p (const char *);
4898
4899 /* Disable a built-in function specified by -fno-builtin-NAME.  If NAME
4900    begins with "__builtin_", give an error.  */
4901
4902 void
4903 disable_builtin_function (const char *name)
4904 {
4905   if (startswith (name, "__builtin_"))
4906     error ("cannot disable built-in function %qs", name);
4907   else
4908     {
4909       disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4910       new_disabled_builtin->name = name;
4911       new_disabled_builtin->next = disabled_builtins;
4912       disabled_builtins = new_disabled_builtin;
4913     }
4914 }
4915
4916
4917 /* Return true if the built-in function NAME has been disabled, false
4918    otherwise.  */
4919
4920 static bool
4921 builtin_function_disabled_p (const char *name)
4922 {
4923   disabled_builtin *p;
4924   for (p = disabled_builtins; p != NULL; p = p->next)
4925     {
4926       if (strcmp (name, p->name) == 0)
4927         return true;
4928     }
4929   return false;
4930 }
4931
4932
4933 /* Worker for DEF_BUILTIN.
4934    Possibly define a builtin function with one or two names.
4935    Does not declare a non-__builtin_ function if flag_no_builtin, or if
4936    nonansi_p and flag_no_nonansi_builtin.  */
4937
4938 static void
4939 def_builtin_1 (enum built_in_function fncode,
4940                const char *name,
4941                enum built_in_class fnclass,
4942                tree fntype, tree libtype,
4943                bool both_p, bool fallback_p, bool nonansi_p,
4944                tree fnattrs, bool implicit_p)
4945 {
4946   tree decl;
4947   const char *libname;
4948
4949   if (fntype == error_mark_node)
4950     return;
4951
4952   gcc_assert ((!both_p && !fallback_p)
4953               || startswith (name, "__builtin_"));
4954
4955   libname = name + strlen ("__builtin_");
4956   decl = add_builtin_function (name, fntype, fncode, fnclass,
4957                                (fallback_p ? libname : NULL),
4958                                fnattrs);
4959
4960   set_builtin_decl (fncode, decl, implicit_p);
4961
4962   if (both_p
4963       && !flag_no_builtin && !builtin_function_disabled_p (libname)
4964       && !(nonansi_p && flag_no_nonansi_builtin))
4965     add_builtin_function (libname, libtype, fncode, fnclass,
4966                           NULL, fnattrs);
4967 }
4968 \f
4969 /* Nonzero if the type T promotes to int.  This is (nearly) the
4970    integral promotions defined in ISO C99 6.3.1.1/2.  */
4971
4972 bool
4973 c_promoting_integer_type_p (const_tree t)
4974 {
4975   switch (TREE_CODE (t))
4976     {
4977     case INTEGER_TYPE:
4978       return (TYPE_MAIN_VARIANT (t) == char_type_node
4979               || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4980               || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4981               || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4982               || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
4983               || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
4984
4985     case ENUMERAL_TYPE:
4986       /* ??? Technically all enumerations not larger than an int
4987          promote to an int.  But this is used along code paths
4988          that only want to notice a size change.  */
4989       return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
4990
4991     case BOOLEAN_TYPE:
4992       return true;
4993
4994     default:
4995       return false;
4996     }
4997 }
4998
4999 /* Return 1 if PARMS specifies a fixed number of parameters
5000    and none of their types is affected by default promotions.  */
5001
5002 bool
5003 self_promoting_args_p (const_tree parms)
5004 {
5005   const_tree t;
5006   for (t = parms; t; t = TREE_CHAIN (t))
5007     {
5008       tree type = TREE_VALUE (t);
5009
5010       if (type == error_mark_node)
5011         continue;
5012
5013       if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
5014         return false;
5015
5016       if (type == NULL_TREE)
5017         return false;
5018
5019       if (TYPE_MAIN_VARIANT (type) == float_type_node)
5020         return false;
5021
5022       if (c_promoting_integer_type_p (type))
5023         return false;
5024     }
5025   return true;
5026 }
5027
5028 /* Recursively remove any '*' or '&' operator from TYPE.  */
5029 tree
5030 strip_pointer_operator (tree t)
5031 {
5032   while (POINTER_TYPE_P (t))
5033     t = TREE_TYPE (t);
5034   return t;
5035 }
5036
5037 /* Recursively remove pointer or array type from TYPE. */
5038 tree
5039 strip_pointer_or_array_types (tree t)
5040 {
5041   while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
5042     t = TREE_TYPE (t);
5043   return t;
5044 }
5045
5046 /* Used to compare case labels.  K1 and K2 are actually tree nodes
5047    representing case labels, or NULL_TREE for a `default' label.
5048    Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
5049    K2, and 0 if K1 and K2 are equal.  */
5050
5051 int
5052 case_compare (splay_tree_key k1, splay_tree_key k2)
5053 {
5054   /* Consider a NULL key (such as arises with a `default' label) to be
5055      smaller than anything else.  */
5056   if (!k1)
5057     return k2 ? -1 : 0;
5058   else if (!k2)
5059     return k1 ? 1 : 0;
5060
5061   return tree_int_cst_compare ((tree) k1, (tree) k2);
5062 }
5063
5064 /* Process a case label, located at LOC, for the range LOW_VALUE
5065    ... HIGH_VALUE.  If LOW_VALUE and HIGH_VALUE are both NULL_TREE
5066    then this case label is actually a `default' label.  If only
5067    HIGH_VALUE is NULL_TREE, then case label was declared using the
5068    usual C/C++ syntax, rather than the GNU case range extension.
5069    CASES is a tree containing all the case ranges processed so far;
5070    COND is the condition for the switch-statement itself.
5071    Returns the CASE_LABEL_EXPR created, or ERROR_MARK_NODE if no
5072    CASE_LABEL_EXPR is created.  ATTRS are the attributes to be applied
5073    to the label.  */
5074
5075 tree
5076 c_add_case_label (location_t loc, splay_tree cases, tree cond,
5077                   tree low_value, tree high_value, tree attrs)
5078 {
5079   tree type;
5080   tree label;
5081   tree case_label;
5082   splay_tree_node node;
5083
5084   /* Create the LABEL_DECL itself.  */
5085   label = create_artificial_label (loc);
5086   decl_attributes (&label, attrs, 0);
5087
5088   /* If there was an error processing the switch condition, bail now
5089      before we get more confused.  */
5090   if (!cond || cond == error_mark_node)
5091     goto error_out;
5092
5093   if ((low_value && TREE_TYPE (low_value)
5094        && POINTER_TYPE_P (TREE_TYPE (low_value)))
5095       || (high_value && TREE_TYPE (high_value)
5096           && POINTER_TYPE_P (TREE_TYPE (high_value))))
5097     {
5098       error_at (loc, "pointers are not permitted as case values");
5099       goto error_out;
5100     }
5101
5102   /* Case ranges are a GNU extension.  */
5103   if (high_value)
5104     pedwarn (loc, OPT_Wpedantic,
5105              "range expressions in switch statements are non-standard");
5106
5107   type = TREE_TYPE (cond);
5108   if (low_value)
5109     {
5110       low_value = check_case_value (loc, low_value);
5111       low_value = convert_and_check (loc, type, low_value);
5112       low_value = fold (low_value);
5113       if (low_value == error_mark_node)
5114         goto error_out;
5115     }
5116   if (high_value)
5117     {
5118       high_value = check_case_value (loc, high_value);
5119       high_value = convert_and_check (loc, type, high_value);
5120       high_value = fold (high_value);
5121       if (high_value == error_mark_node)
5122         goto error_out;
5123     }
5124
5125   if (low_value && high_value)
5126     {
5127       /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
5128          really a case range, even though it was written that way.
5129          Remove the HIGH_VALUE to simplify later processing.  */
5130       if (tree_int_cst_equal (low_value, high_value))
5131         high_value = NULL_TREE;
5132       else if (!tree_int_cst_lt (low_value, high_value))
5133         warning_at (loc, 0, "empty range specified");
5134     }
5135
5136   /* Look up the LOW_VALUE in the table of case labels we already
5137      have.  */
5138   node = splay_tree_lookup (cases, (splay_tree_key) low_value);
5139   /* If there was not an exact match, check for overlapping ranges.
5140      There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
5141      that's a `default' label and the only overlap is an exact match.  */
5142   if (!node && (low_value || high_value))
5143     {
5144       splay_tree_node low_bound;
5145       splay_tree_node high_bound;
5146
5147       /* Even though there wasn't an exact match, there might be an
5148          overlap between this case range and another case range.
5149          Since we've (inductively) not allowed any overlapping case
5150          ranges, we simply need to find the greatest low case label
5151          that is smaller that LOW_VALUE, and the smallest low case
5152          label that is greater than LOW_VALUE.  If there is an overlap
5153          it will occur in one of these two ranges.  */
5154       low_bound = splay_tree_predecessor (cases,
5155                                           (splay_tree_key) low_value);
5156       high_bound = splay_tree_successor (cases,
5157                                          (splay_tree_key) low_value);
5158
5159       /* Check to see if the LOW_BOUND overlaps.  It is smaller than
5160          the LOW_VALUE, so there is no need to check unless the
5161          LOW_BOUND is in fact itself a case range.  */
5162       if (low_bound
5163           && CASE_HIGH ((tree) low_bound->value)
5164           && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
5165                                     low_value) >= 0)
5166         node = low_bound;
5167       /* Check to see if the HIGH_BOUND overlaps.  The low end of that
5168          range is bigger than the low end of the current range, so we
5169          are only interested if the current range is a real range, and
5170          not an ordinary case label.  */
5171       else if (high_bound
5172                && high_value
5173                && (tree_int_cst_compare ((tree) high_bound->key,
5174                                          high_value)
5175                    <= 0))
5176         node = high_bound;
5177     }
5178   /* If there was an overlap, issue an error.  */
5179   if (node)
5180     {
5181       tree duplicate = CASE_LABEL ((tree) node->value);
5182
5183       if (high_value)
5184         {
5185           error_at (loc, "duplicate (or overlapping) case value");
5186           inform (DECL_SOURCE_LOCATION (duplicate),
5187                   "this is the first entry overlapping that value");
5188         }
5189       else if (low_value)
5190         {
5191           error_at (loc, "duplicate case value") ;
5192           inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
5193         }
5194       else
5195         {
5196           error_at (loc, "multiple default labels in one switch");
5197           inform (DECL_SOURCE_LOCATION (duplicate),
5198                   "this is the first default label");
5199         }
5200       goto error_out;
5201     }
5202
5203   /* Add a CASE_LABEL to the statement-tree.  */
5204   case_label = add_stmt (build_case_label (low_value, high_value, label));
5205   /* Register this case label in the splay tree.  */
5206   splay_tree_insert (cases,
5207                      (splay_tree_key) low_value,
5208                      (splay_tree_value) case_label);
5209
5210   return case_label;
5211
5212  error_out:
5213   /* Add a label so that the back-end doesn't think that the beginning of
5214      the switch is unreachable.  Note that we do not add a case label, as
5215      that just leads to duplicates and thence to failure later on.  */
5216   if (!cases->root)
5217     {
5218       tree t = create_artificial_label (loc);
5219       add_stmt (build_stmt (loc, LABEL_EXPR, t));
5220     }
5221   return error_mark_node;
5222 }
5223
5224 /* Subroutine of c_switch_covers_all_cases_p, called via
5225    splay_tree_foreach.  Return 1 if it doesn't cover all the cases.
5226    ARGS[0] is initially NULL and after the first iteration is the
5227    so far highest case label.  ARGS[1] is the minimum of SWITCH_COND's
5228    type.  */
5229
5230 static int
5231 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
5232 {
5233   tree label = (tree) node->value;
5234   tree *args = (tree *) data;
5235
5236   /* If there is a default case, we shouldn't have called this.  */
5237   gcc_assert (CASE_LOW (label));
5238
5239   if (args[0] == NULL_TREE)
5240     {
5241       if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
5242         return 1;
5243     }
5244   else if (wi::add (wi::to_widest (args[0]), 1)
5245            != wi::to_widest (CASE_LOW (label)))
5246     return 1;
5247   if (CASE_HIGH (label))
5248     args[0] = CASE_HIGH (label);
5249   else
5250     args[0] = CASE_LOW (label);
5251   return 0;
5252 }
5253
5254 /* Return true if switch with CASES and switch condition with type
5255    covers all possible values in the case labels.  */
5256
5257 bool
5258 c_switch_covers_all_cases_p (splay_tree cases, tree type)
5259 {
5260   /* If there is default:, this is always the case.  */
5261   splay_tree_node default_node
5262     = splay_tree_lookup (cases, (splay_tree_key) NULL);
5263   if (default_node)
5264     return true;
5265
5266   if (!INTEGRAL_TYPE_P (type))
5267     return false;
5268
5269   tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
5270   if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
5271     return false;
5272
5273   /* If there are no cases at all, or if the highest case label
5274      is smaller than TYPE_MAX_VALUE, return false.  */
5275   if (args[0] == NULL_TREE
5276       || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
5277     return false;
5278
5279   return true;
5280 }
5281
5282 /* Return true if stmt can fall through.  Used by block_may_fallthru
5283    default case.  */
5284
5285 bool
5286 c_block_may_fallthru (const_tree stmt)
5287 {
5288   switch (TREE_CODE (stmt))
5289     {
5290     case SWITCH_STMT:
5291       return (!SWITCH_STMT_ALL_CASES_P (stmt)
5292               || !SWITCH_STMT_NO_BREAK_P (stmt)
5293               || block_may_fallthru (SWITCH_STMT_BODY (stmt)));
5294
5295     default:
5296       return true;
5297     }
5298 }
5299
5300 /* Finish an expression taking the address of LABEL (an
5301    IDENTIFIER_NODE).  Returns an expression for the address.
5302
5303    LOC is the location for the expression returned.  */
5304
5305 tree
5306 finish_label_address_expr (tree label, location_t loc)
5307 {
5308   tree result;
5309
5310   pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
5311
5312   if (label == error_mark_node)
5313     return error_mark_node;
5314
5315   label = lookup_label (label);
5316   if (label == NULL_TREE)
5317     result = null_pointer_node;
5318   else
5319     {
5320       TREE_USED (label) = 1;
5321       result = build1 (ADDR_EXPR, ptr_type_node, label);
5322       /* The current function is not necessarily uninlinable.
5323          Computed gotos are incompatible with inlining, but the value
5324          here could be used only in a diagnostic, for example.  */
5325       protected_set_expr_location (result, loc);
5326     }
5327
5328   return result;
5329 }
5330 \f
5331
5332 /* Given a boolean expression ARG, return a tree representing an increment
5333    or decrement (as indicated by CODE) of ARG.  The front end must check for
5334    invalid cases (e.g., decrement in C++).  */
5335 tree
5336 boolean_increment (enum tree_code code, tree arg)
5337 {
5338   tree val;
5339   tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5340
5341   arg = stabilize_reference (arg);
5342   switch (code)
5343     {
5344     case PREINCREMENT_EXPR:
5345       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5346       break;
5347     case POSTINCREMENT_EXPR:
5348       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5349       arg = save_expr (arg);
5350       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5351       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5352       break;
5353     case PREDECREMENT_EXPR:
5354       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5355                     invert_truthvalue_loc (input_location, arg));
5356       break;
5357     case POSTDECREMENT_EXPR:
5358       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5359                     invert_truthvalue_loc (input_location, arg));
5360       arg = save_expr (arg);
5361       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5362       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5363       break;
5364     default:
5365       gcc_unreachable ();
5366     }
5367   TREE_SIDE_EFFECTS (val) = 1;
5368   return val;
5369 }
5370 \f
5371 /* Built-in macros for stddef.h and stdint.h, that require macros
5372    defined in this file.  */
5373 void
5374 c_stddef_cpp_builtins(void)
5375 {
5376   builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5377   builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5378   builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5379   builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5380   builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5381   builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5382   if (flag_char8_t)
5383     builtin_define_with_value ("__CHAR8_TYPE__", CHAR8_TYPE, 0);
5384   builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5385   builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5386   if (SIG_ATOMIC_TYPE)
5387     builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5388   if (INT8_TYPE)
5389     builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5390   if (INT16_TYPE)
5391     builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5392   if (INT32_TYPE)
5393     builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5394   if (INT64_TYPE)
5395     builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5396   if (UINT8_TYPE)
5397     builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5398   if (UINT16_TYPE)
5399     builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5400   if (UINT32_TYPE)
5401     builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5402   if (UINT64_TYPE)
5403     builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5404   if (INT_LEAST8_TYPE)
5405     builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5406   if (INT_LEAST16_TYPE)
5407     builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5408   if (INT_LEAST32_TYPE)
5409     builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5410   if (INT_LEAST64_TYPE)
5411     builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5412   if (UINT_LEAST8_TYPE)
5413     builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5414   if (UINT_LEAST16_TYPE)
5415     builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5416   if (UINT_LEAST32_TYPE)
5417     builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5418   if (UINT_LEAST64_TYPE)
5419     builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5420   if (INT_FAST8_TYPE)
5421     builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5422   if (INT_FAST16_TYPE)
5423     builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5424   if (INT_FAST32_TYPE)
5425     builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5426   if (INT_FAST64_TYPE)
5427     builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5428   if (UINT_FAST8_TYPE)
5429     builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5430   if (UINT_FAST16_TYPE)
5431     builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5432   if (UINT_FAST32_TYPE)
5433     builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5434   if (UINT_FAST64_TYPE)
5435     builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5436   if (INTPTR_TYPE)
5437     builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5438   if (UINTPTR_TYPE)
5439     builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5440   /* GIMPLE FE testcases need access to the GCC internal 'sizetype'.
5441      Expose it as __SIZETYPE__.  */
5442   if (flag_gimple)
5443     builtin_define_with_value ("__SIZETYPE__", SIZETYPE, 0);
5444 }
5445
5446 static void
5447 c_init_attributes (void)
5448 {
5449   /* Fill in the built_in_attributes array.  */
5450 #define DEF_ATTR_NULL_TREE(ENUM)                                \
5451   built_in_attributes[(int) ENUM] = NULL_TREE;
5452 #define DEF_ATTR_INT(ENUM, VALUE)                               \
5453   built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5454 #define DEF_ATTR_STRING(ENUM, VALUE)                            \
5455   built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5456 #define DEF_ATTR_IDENT(ENUM, STRING)                            \
5457   built_in_attributes[(int) ENUM] = get_identifier (STRING);
5458 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5459   built_in_attributes[(int) ENUM]                       \
5460     = tree_cons (built_in_attributes[(int) PURPOSE],    \
5461                  built_in_attributes[(int) VALUE],      \
5462                  built_in_attributes[(int) CHAIN]);
5463 #include "builtin-attrs.def"
5464 #undef DEF_ATTR_NULL_TREE
5465 #undef DEF_ATTR_INT
5466 #undef DEF_ATTR_IDENT
5467 #undef DEF_ATTR_TREE_LIST
5468 }
5469
5470 /* Check whether the byte alignment ALIGN is a valid user-specified
5471    alignment less than the supported maximum.  If so, return ALIGN's
5472    base-2 log; if not, output an error and return -1.  If OBJFILE
5473    then reject alignments greater than MAX_OFILE_ALIGNMENT when
5474    converted to bits.  Otherwise, consider valid only alignments
5475    that are less than HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT.
5476    Zero is not considered a valid argument (and results in -1 on
5477    return) but it only triggers a warning when WARN_ZERO is set.  */
5478
5479 int
5480 check_user_alignment (const_tree align, bool objfile, bool warn_zero)
5481 {
5482   if (error_operand_p (align))
5483     return -1;
5484
5485   if (TREE_CODE (align) != INTEGER_CST
5486       || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5487     {
5488       error ("requested alignment is not an integer constant");
5489       return -1;
5490     }
5491
5492   if (integer_zerop (align))
5493     {
5494       if (warn_zero)
5495         warning (OPT_Wattributes,
5496                  "requested alignment %qE is not a positive power of 2",
5497                  align);
5498       return -1;
5499     }
5500
5501   /* Log2 of the byte alignment ALIGN.  */
5502   int log2align;
5503   if (tree_int_cst_sgn (align) == -1
5504       || (log2align = tree_log2 (align)) == -1)
5505     {
5506       error ("requested alignment %qE is not a positive power of 2",
5507              align);
5508       return -1;
5509     }
5510
5511   if (objfile)
5512     {
5513       unsigned maxalign = MAX_OFILE_ALIGNMENT / BITS_PER_UNIT;
5514       if (!tree_fits_uhwi_p (align) || tree_to_uhwi (align) > maxalign)
5515         {
5516           error ("requested alignment %qE exceeds object file maximum %u",
5517                  align, maxalign);
5518           return -1;
5519         }
5520     }
5521
5522   if (log2align >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5523     {
5524       error ("requested alignment %qE exceeds maximum %u",
5525              align, 1U << (HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT - 1));
5526       return -1;
5527     }
5528
5529   return log2align;
5530 }
5531
5532 /* Determine the ELF symbol visibility for DECL, which is either a
5533    variable or a function.  It is an error to use this function if a
5534    definition of DECL is not available in this translation unit.
5535    Returns true if the final visibility has been determined by this
5536    function; false if the caller is free to make additional
5537    modifications.  */
5538
5539 bool
5540 c_determine_visibility (tree decl)
5541 {
5542   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5543
5544   /* If the user explicitly specified the visibility with an
5545      attribute, honor that.  DECL_VISIBILITY will have been set during
5546      the processing of the attribute.  We check for an explicit
5547      attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5548      to distinguish the use of an attribute from the use of a "#pragma
5549      GCC visibility push(...)"; in the latter case we still want other
5550      considerations to be able to overrule the #pragma.  */
5551   if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5552       || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5553           && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5554               || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5555     return true;
5556
5557   /* Set default visibility to whatever the user supplied with
5558      visibility_specified depending on #pragma GCC visibility.  */
5559   if (!DECL_VISIBILITY_SPECIFIED (decl))
5560     {
5561       if (visibility_options.inpragma
5562           || DECL_VISIBILITY (decl) != default_visibility)
5563         {
5564           DECL_VISIBILITY (decl) = default_visibility;
5565           DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5566           /* If visibility changed and DECL already has DECL_RTL, ensure
5567              symbol flags are updated.  */
5568           if (((VAR_P (decl) && TREE_STATIC (decl))
5569                || TREE_CODE (decl) == FUNCTION_DECL)
5570               && DECL_RTL_SET_P (decl))
5571             make_decl_rtl (decl);
5572         }
5573     }
5574   return false;
5575 }
5576
5577 /* Data to communicate through check_function_arguments_recurse between
5578    check_function_nonnull and check_nonnull_arg.  */
5579
5580 struct nonnull_arg_ctx
5581 {
5582   /* Location of the call.  */
5583   location_t loc;
5584   /* The function whose arguments are being checked and its type (used
5585      for calls through function pointers).  */
5586   const_tree fndecl, fntype;
5587   /* True if a warning has been issued.  */
5588   bool warned_p;
5589 };
5590
5591 /* Check the argument list of a function call to CTX.FNDECL of CTX.FNTYPE
5592    for null in argument slots that are marked as requiring a non-null
5593    pointer argument.  The NARGS arguments are passed in the array ARGARRAY.
5594    Return true if we have warned.  */
5595
5596 static bool
5597 check_function_nonnull (nonnull_arg_ctx &ctx, int nargs, tree *argarray)
5598 {
5599   int firstarg = 0;
5600   if (TREE_CODE (ctx.fntype) == METHOD_TYPE)
5601     {
5602       bool closure = false;
5603       if (ctx.fndecl)
5604         {
5605           /* For certain lambda expressions the C++ front end emits calls
5606              that pass a null this pointer as an argument named __closure
5607              to the member operator() of empty function.  Detect those
5608              and avoid checking them, but proceed to check the remaining
5609              arguments.  */
5610           tree arg0 = DECL_ARGUMENTS (ctx.fndecl);
5611           if (tree arg0name = DECL_NAME (arg0))
5612             closure = id_equal (arg0name, "__closure");
5613         }
5614
5615       /* In calls to C++ non-static member functions check the this
5616          pointer regardless of whether the function is declared with
5617          attribute nonnull.  */
5618       firstarg = 1;
5619       if (!closure)
5620         check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[0],
5621                                           firstarg, OPT_Wnonnull);
5622     }
5623
5624   tree attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (ctx.fntype));
5625   if (attrs == NULL_TREE)
5626     return ctx.warned_p;
5627
5628   tree a = attrs;
5629   /* See if any of the nonnull attributes has no arguments.  If so,
5630      then every pointer argument is checked (in which case the check
5631      for pointer type is done in check_nonnull_arg).  */
5632   if (TREE_VALUE (a) != NULL_TREE)
5633     do
5634       a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5635     while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5636
5637   if (a != NULL_TREE)
5638     for (int i = firstarg; i < nargs; i++)
5639       check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5640                                         i + 1, OPT_Wnonnull);
5641   else
5642     {
5643       /* Walk the argument list.  If we encounter an argument number we
5644          should check for non-null, do it.  */
5645       for (int i = firstarg; i < nargs; i++)
5646         {
5647           for (a = attrs; ; a = TREE_CHAIN (a))
5648             {
5649               a = lookup_attribute ("nonnull", a);
5650               if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5651                 break;
5652             }
5653
5654           if (a != NULL_TREE)
5655             check_function_arguments_recurse (check_nonnull_arg, &ctx,
5656                                               argarray[i], i + 1,
5657                                               OPT_Wnonnull);
5658         }
5659     }
5660   return ctx.warned_p;
5661 }
5662
5663 /* Check that the Nth argument of a function call (counting backwards
5664    from the end) is a (pointer)0.  The NARGS arguments are passed in the
5665    array ARGARRAY.  */
5666
5667 static void
5668 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5669 {
5670   tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5671
5672   if (attr)
5673     {
5674       int len = 0;
5675       int pos = 0;
5676       tree sentinel;
5677       function_args_iterator iter;
5678       tree t;
5679
5680       /* Skip over the named arguments.  */
5681       FOREACH_FUNCTION_ARGS (fntype, t, iter)
5682         {
5683           if (len == nargs)
5684             break;
5685           len++;
5686         }
5687
5688       if (TREE_VALUE (attr))
5689         {
5690           tree p = TREE_VALUE (TREE_VALUE (attr));
5691           pos = TREE_INT_CST_LOW (p);
5692         }
5693
5694       /* The sentinel must be one of the varargs, i.e.
5695          in position >= the number of fixed arguments.  */
5696       if ((nargs - 1 - pos) < len)
5697         {
5698           warning (OPT_Wformat_,
5699                    "not enough variable arguments to fit a sentinel");
5700           return;
5701         }
5702
5703       /* Validate the sentinel.  */
5704       sentinel = fold_for_warn (argarray[nargs - 1 - pos]);
5705       if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5706            || !integer_zerop (sentinel))
5707           /* Although __null (in C++) is only an integer we allow it
5708              nevertheless, as we are guaranteed that it's exactly
5709              as wide as a pointer, and we don't want to force
5710              users to cast the NULL they have written there.
5711              We warn with -Wstrict-null-sentinel, though.  */
5712           && (warn_strict_null_sentinel || null_node != sentinel))
5713         warning (OPT_Wformat_, "missing sentinel in function call");
5714     }
5715 }
5716
5717 /* Check that the same argument isn't passed to two or more
5718    restrict-qualified formal and issue a -Wrestrict warning
5719    if it is.  Return true if a warning has been issued.  */
5720
5721 static bool
5722 check_function_restrict (const_tree fndecl, const_tree fntype,
5723                          int nargs, tree *unfolded_argarray)
5724 {
5725   int i;
5726   tree parms = TYPE_ARG_TYPES (fntype);
5727
5728   /* Call fold_for_warn on all of the arguments.  */
5729   auto_vec<tree> argarray (nargs);
5730   for (i = 0; i < nargs; i++)
5731     argarray.quick_push (fold_for_warn (unfolded_argarray[i]));
5732
5733   if (fndecl
5734       && TREE_CODE (fndecl) == FUNCTION_DECL)
5735     {
5736       /* Avoid diagnosing calls built-ins with a zero size/bound
5737          here.  They are checked in more detail elsewhere.  */
5738       if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
5739           && nargs == 3
5740           && TREE_CODE (argarray[2]) == INTEGER_CST
5741           && integer_zerop (argarray[2]))
5742         return false;
5743
5744       if (DECL_ARGUMENTS (fndecl))
5745         parms = DECL_ARGUMENTS (fndecl);
5746     }
5747
5748   for (i = 0; i < nargs; i++)
5749     TREE_VISITED (argarray[i]) = 0;
5750
5751   bool warned = false;
5752
5753   for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5754     {
5755       tree type;
5756       if (TREE_CODE (parms) == PARM_DECL)
5757         {
5758           type = TREE_TYPE (parms);
5759           parms = DECL_CHAIN (parms);
5760         }
5761       else
5762         {
5763           type = TREE_VALUE (parms);
5764           parms = TREE_CHAIN (parms);
5765         }
5766       if (POINTER_TYPE_P (type)
5767           && TYPE_RESTRICT (type)
5768           && !TYPE_READONLY (TREE_TYPE (type)))
5769         warned |= warn_for_restrict (i, argarray.address (), nargs);
5770     }
5771
5772   for (i = 0; i < nargs; i++)
5773     TREE_VISITED (argarray[i]) = 0;
5774
5775   return warned;
5776 }
5777
5778 /* Helper for check_function_nonnull; given a list of operands which
5779    must be non-null in ARGS, determine if operand PARAM_NUM should be
5780    checked.  */
5781
5782 static bool
5783 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5784 {
5785   unsigned HOST_WIDE_INT arg_num = 0;
5786
5787   for (; args; args = TREE_CHAIN (args))
5788     {
5789       bool found = get_attribute_operand (TREE_VALUE (args), &arg_num);
5790
5791       gcc_assert (found);
5792
5793       if (arg_num == param_num)
5794         return true;
5795     }
5796   return false;
5797 }
5798
5799 /* Check that the function argument PARAM (which is operand number
5800    PARAM_NUM) is non-null.  This is called by check_function_nonnull
5801    via check_function_arguments_recurse.  */
5802
5803 static void
5804 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5805 {
5806   struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5807
5808   /* Just skip checking the argument if it's not a pointer.  This can
5809      happen if the "nonnull" attribute was given without an operand
5810      list (which means to check every pointer argument).  */
5811
5812   tree paramtype = TREE_TYPE (param);
5813   if (TREE_CODE (paramtype) != POINTER_TYPE
5814       && TREE_CODE (paramtype) != NULLPTR_TYPE)
5815     return;
5816
5817   /* Diagnose the simple cases of null arguments.  */
5818   if (!integer_zerop (fold_for_warn (param)))
5819     return;
5820
5821   auto_diagnostic_group adg;
5822
5823   const location_t loc = EXPR_LOC_OR_LOC (param, pctx->loc);
5824
5825   if (TREE_CODE (pctx->fntype) == METHOD_TYPE)
5826     --param_num;
5827
5828   bool warned;
5829   if (param_num == 0)
5830     {
5831       warned = warning_at (loc, OPT_Wnonnull,
5832                            "%qs pointer is null", "this");
5833       if (warned && pctx->fndecl)
5834         inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5835                 "in a call to non-static member function %qD",
5836                 pctx->fndecl);
5837     }
5838   else
5839     {
5840       warned = warning_at (loc, OPT_Wnonnull,
5841                            "argument %u null where non-null expected",
5842                            (unsigned) param_num);
5843       if (warned && pctx->fndecl)
5844         inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5845                 "in a call to function %qD declared %qs",
5846                 pctx->fndecl, "nonnull");
5847     }
5848
5849   if (warned)
5850     pctx->warned_p = true;
5851 }
5852
5853 /* Helper for attribute handling; fetch the operand number from
5854    the attribute argument list.  */
5855
5856 bool
5857 get_attribute_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5858 {
5859   /* Verify the arg number is a small constant.  */
5860   if (tree_fits_uhwi_p (arg_num_expr))
5861     {
5862       *valp = tree_to_uhwi (arg_num_expr);
5863       return true;
5864     }
5865   else
5866     return false;
5867 }
5868
5869 /* Arguments being collected for optimization.  */
5870 typedef const char *const_char_p;               /* For DEF_VEC_P.  */
5871 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5872
5873
5874 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5875    options in ARGS.  ATTR_P is true if this is for attribute(optimize), and
5876    false for #pragma GCC optimize.  */
5877
5878 bool
5879 parse_optimize_options (tree args, bool attr_p)
5880 {
5881   bool ret = true;
5882   unsigned opt_argc;
5883   unsigned i;
5884   const char **opt_argv;
5885   struct cl_decoded_option *decoded_options;
5886   unsigned int decoded_options_count;
5887   tree ap;
5888
5889   /* Build up argv vector.  Just in case the string is stored away, use garbage
5890      collected strings.  */
5891   vec_safe_truncate (optimize_args, 0);
5892   vec_safe_push (optimize_args, (const char *) NULL);
5893
5894   for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5895     {
5896       tree value = TREE_VALUE (ap);
5897
5898       if (TREE_CODE (value) == INTEGER_CST)
5899         {
5900           char buffer[HOST_BITS_PER_LONG / 3 + 4];
5901           sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5902           vec_safe_push (optimize_args, ggc_strdup (buffer));
5903         }
5904
5905       else if (TREE_CODE (value) == STRING_CST)
5906         {
5907           /* Split string into multiple substrings.  */
5908           size_t len = TREE_STRING_LENGTH (value);
5909           char *p = ASTRDUP (TREE_STRING_POINTER (value));
5910           char *end = p + len;
5911           char *comma;
5912           char *next_p = p;
5913
5914           while (next_p != NULL)
5915             {
5916               size_t len2;
5917               char *q, *r;
5918
5919               p = next_p;
5920               comma = strchr (p, ',');
5921               if (comma)
5922                 {
5923                   len2 = comma - p;
5924                   *comma = '\0';
5925                   next_p = comma+1;
5926                 }
5927               else
5928                 {
5929                   len2 = end - p;
5930                   next_p = NULL;
5931                 }
5932
5933               /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5934                  options.  */
5935               if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5936                 {
5937                   ret = false;
5938                   if (attr_p)
5939                     warning (OPT_Wattributes,
5940                              "bad option %qs to attribute %<optimize%>", p);
5941                   else
5942                     warning (OPT_Wpragmas,
5943                              "bad option %qs to pragma %<optimize%>", p);
5944                   continue;
5945                 }
5946
5947               /* Can't use GC memory here, see PR88007.  */
5948               r = q = XOBNEWVEC (&opts_obstack, char, len2 + 3);
5949
5950               if (*p != '-')
5951                 {
5952                   *r++ = '-';
5953
5954                   /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5955                      itself is -Os, and any other switch begins with a -f.  */
5956                   if ((*p >= '0' && *p <= '9')
5957                       || (p[0] == 's' && p[1] == '\0'))
5958                     *r++ = 'O';
5959                   else if (*p != 'O')
5960                     *r++ = 'f';
5961                 }
5962
5963               memcpy (r, p, len2);
5964               r[len2] = '\0';
5965               vec_safe_push (optimize_args, (const char *) q);
5966             }
5967
5968         }
5969     }
5970
5971   opt_argc = optimize_args->length ();
5972   opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5973
5974   for (i = 1; i < opt_argc; i++)
5975     opt_argv[i] = (*optimize_args)[i];
5976
5977   /* Now parse the options.  */
5978   decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
5979                                                 &decoded_options,
5980                                                 &decoded_options_count);
5981   /* Drop non-Optimization options.  */
5982   unsigned j = 1;
5983   for (i = 1; i < decoded_options_count; ++i)
5984     {
5985       if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
5986         {
5987           ret = false;
5988           if (attr_p)
5989             warning (OPT_Wattributes,
5990                      "bad option %qs to attribute %<optimize%>",
5991                      decoded_options[i].orig_option_with_args_text);
5992           else
5993             warning (OPT_Wpragmas,
5994                      "bad option %qs to pragma %<optimize%>",
5995                      decoded_options[i].orig_option_with_args_text);
5996           continue;
5997         }
5998       if (i != j)
5999         decoded_options[j] = decoded_options[i];
6000       j++;
6001     }
6002   decoded_options_count = j;
6003
6004   /* Merge the decoded options with save_decoded_options.  */
6005   unsigned save_opt_count = save_opt_decoded_options->length ();
6006   unsigned merged_decoded_options_count
6007     = save_opt_count + decoded_options_count;
6008   cl_decoded_option *merged_decoded_options
6009     = XNEWVEC (cl_decoded_option, merged_decoded_options_count);
6010
6011   /* Note the first decoded_options is used for the program name.  */
6012   for (unsigned i = 0; i < save_opt_count; ++i)
6013     merged_decoded_options[i + 1] = (*save_opt_decoded_options)[i];
6014   for (unsigned i = 1; i < decoded_options_count; ++i)
6015     merged_decoded_options[save_opt_count + i] = decoded_options[i];
6016
6017    /* And apply them.  */
6018   decode_options (&global_options, &global_options_set,
6019                   merged_decoded_options, merged_decoded_options_count,
6020                   input_location, global_dc, NULL);
6021   free (decoded_options);
6022
6023   targetm.override_options_after_change();
6024
6025   optimize_args->truncate (0);
6026   return ret;
6027 }
6028
6029 /* Check whether ATTR is a valid attribute fallthrough.  */
6030
6031 bool
6032 attribute_fallthrough_p (tree attr)
6033 {
6034   if (attr == error_mark_node)
6035    return false;
6036   tree t = lookup_attribute ("fallthrough", attr);
6037   if (t == NULL_TREE)
6038     return false;
6039   /* It is no longer true that "this attribute shall appear at most once in
6040      each attribute-list", but we still give a warning.  */
6041   if (lookup_attribute ("fallthrough", TREE_CHAIN (t)))
6042     warning (OPT_Wattributes, "attribute %<fallthrough%> specified multiple "
6043              "times");
6044   /* No attribute-argument-clause shall be present.  */
6045   else if (TREE_VALUE (t) != NULL_TREE)
6046     warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
6047              "a parameter");
6048   /* Warn if other attributes are found.  */
6049   for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
6050     {
6051       tree name = get_attribute_name (t);
6052       if (!is_attribute_p ("fallthrough", name))
6053         {
6054           if (!c_dialect_cxx () && get_attribute_namespace (t) == NULL_TREE)
6055             /* The specifications of standard attributes in C mean
6056                this is a constraint violation.  */
6057             pedwarn (input_location, OPT_Wattributes, "%qE attribute ignored",
6058                      get_attribute_name (t));
6059           else
6060             warning (OPT_Wattributes, "%qE attribute ignored", name);
6061         }
6062     }
6063   return true;
6064 }
6065
6066 \f
6067 /* Check for valid arguments being passed to a function with FNTYPE.
6068    There are NARGS arguments in the array ARGARRAY.  LOC should be used
6069    for diagnostics.  Return true if either -Wnonnull or -Wrestrict has
6070    been issued.
6071
6072    The arguments in ARGARRAY may not have been folded yet (e.g. for C++,
6073    to preserve location wrappers); checks that require folded arguments
6074    should call fold_for_warn on them.  */
6075
6076 bool
6077 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
6078                           int nargs, tree *argarray, vec<location_t> *arglocs)
6079 {
6080   bool warned_p = false;
6081
6082   /* Check for null being passed in a pointer argument that must be
6083      non-null.  In C++, this includes the this pointer.  We also need
6084      to do this if format checking is enabled.  */
6085   if (warn_nonnull)
6086     {
6087       nonnull_arg_ctx ctx = { loc, fndecl, fntype, false };
6088       warned_p = check_function_nonnull (ctx, nargs, argarray);
6089     }
6090
6091   /* Check for errors in format strings.  */
6092
6093   if (warn_format || warn_suggest_attribute_format)
6094     check_function_format (fndecl ? fndecl : fntype, TYPE_ATTRIBUTES (fntype), nargs,
6095                            argarray, arglocs);
6096
6097   if (warn_format)
6098     check_function_sentinel (fntype, nargs, argarray);
6099
6100   if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
6101     {
6102       switch (DECL_FUNCTION_CODE (fndecl))
6103         {
6104         case BUILT_IN_SPRINTF:
6105         case BUILT_IN_SPRINTF_CHK:
6106         case BUILT_IN_SNPRINTF:
6107         case BUILT_IN_SNPRINTF_CHK:
6108           /* Let the sprintf pass handle these.  */
6109           return warned_p;
6110
6111         default:
6112           break;
6113         }
6114     }
6115
6116   /* check_function_restrict sets the DECL_READ_P for arguments
6117      so it must be called unconditionally.  */
6118   warned_p |= check_function_restrict (fndecl, fntype, nargs, argarray);
6119
6120   return warned_p;
6121 }
6122
6123 /* Generic argument checking recursion routine.  PARAM is the argument to
6124    be checked.  PARAM_NUM is the number of the argument.  CALLBACK is invoked
6125    once the argument is resolved.  CTX is context for the callback.
6126    OPT is the warning for which this is done.  */
6127 void
6128 check_function_arguments_recurse (void (*callback)
6129                                   (void *, tree, unsigned HOST_WIDE_INT),
6130                                   void *ctx, tree param,
6131                                   unsigned HOST_WIDE_INT param_num,
6132                                   opt_code opt)
6133 {
6134   if (opt != OPT_Wformat_ && warning_suppressed_p (param))
6135     return;
6136
6137   if (CONVERT_EXPR_P (param)
6138       && (TYPE_PRECISION (TREE_TYPE (param))
6139           == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
6140     {
6141       /* Strip coercion.  */
6142       check_function_arguments_recurse (callback, ctx,
6143                                         TREE_OPERAND (param, 0), param_num,
6144                                         opt);
6145       return;
6146     }
6147
6148   if (TREE_CODE (param) == CALL_EXPR && CALL_EXPR_FN (param))
6149     {
6150       tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
6151       tree attrs;
6152       bool found_format_arg = false;
6153
6154       /* See if this is a call to a known internationalization function
6155          that modifies a format arg.  Such a function may have multiple
6156          format_arg attributes (for example, ngettext).  */
6157
6158       for (attrs = TYPE_ATTRIBUTES (type);
6159            attrs;
6160            attrs = TREE_CHAIN (attrs))
6161         if (is_attribute_p ("format_arg", get_attribute_name (attrs)))
6162           {
6163             tree inner_arg;
6164             tree format_num_expr;
6165             int format_num;
6166             int i;
6167             call_expr_arg_iterator iter;
6168
6169             /* Extract the argument number, which was previously checked
6170                to be valid.  */
6171             format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
6172
6173             format_num = tree_to_uhwi (format_num_expr);
6174
6175             for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
6176                  inner_arg != NULL_TREE;
6177                  inner_arg = next_call_expr_arg (&iter), i++)
6178               if (i == format_num)
6179                 {
6180                   check_function_arguments_recurse (callback, ctx,
6181                                                     inner_arg, param_num,
6182                                                     opt);
6183                   found_format_arg = true;
6184                   break;
6185                 }
6186           }
6187
6188       /* If we found a format_arg attribute and did a recursive check,
6189          we are done with checking this argument.  Otherwise, we continue
6190          and this will be considered a non-literal.  */
6191       if (found_format_arg)
6192         return;
6193     }
6194
6195   if (TREE_CODE (param) == COND_EXPR)
6196     {
6197       /* Simplify to avoid warning for an impossible case.  */
6198       param = fold_for_warn (param);
6199       if (TREE_CODE (param) == COND_EXPR)
6200         {
6201           /* Check both halves of the conditional expression.  */
6202           check_function_arguments_recurse (callback, ctx,
6203                                             TREE_OPERAND (param, 1),
6204                                             param_num, opt);
6205           check_function_arguments_recurse (callback, ctx,
6206                                             TREE_OPERAND (param, 2),
6207                                             param_num, opt);
6208           return;
6209         }
6210     }
6211
6212   (*callback) (ctx, param, param_num);
6213 }
6214
6215 /* Checks for a builtin function FNDECL that the number of arguments
6216    NARGS against the required number REQUIRED and issues an error if
6217    there is a mismatch.  Returns true if the number of arguments is
6218    correct, otherwise false.  LOC is the location of FNDECL.  */
6219
6220 static bool
6221 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
6222                                  int required)
6223 {
6224   if (nargs < required)
6225     {
6226       error_at (loc, "too few arguments to function %qE", fndecl);
6227       return false;
6228     }
6229   else if (nargs > required)
6230     {
6231       error_at (loc, "too many arguments to function %qE", fndecl);
6232       return false;
6233     }
6234   return true;
6235 }
6236
6237 /* Helper macro for check_builtin_function_arguments.  */
6238 #define ARG_LOCATION(N)                                 \
6239   (arg_loc.is_empty ()                                  \
6240    ? EXPR_LOC_OR_LOC (args[(N)], input_location)        \
6241    : expansion_point_location (arg_loc[(N)]))
6242
6243 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
6244    Returns false if there was an error, otherwise true.  LOC is the
6245    location of the function; ARG_LOC is a vector of locations of the
6246    arguments.  If FNDECL is the result of resolving an overloaded
6247    target built-in, ORIG_FNDECL is the original function decl,
6248    otherwise it is null.  */
6249
6250 bool
6251 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
6252                                   tree fndecl, tree orig_fndecl,
6253                                   int nargs, tree *args)
6254 {
6255   if (!fndecl_built_in_p (fndecl))
6256     return true;
6257
6258   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6259     return (!targetm.check_builtin_call
6260             || targetm.check_builtin_call (loc, arg_loc, fndecl,
6261                                            orig_fndecl, nargs, args));
6262
6263   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_FRONTEND)
6264     return true;
6265
6266   gcc_assert (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL);
6267   switch (DECL_FUNCTION_CODE (fndecl))
6268     {
6269     case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
6270       if (!tree_fits_uhwi_p (args[2]))
6271         {
6272           error_at (ARG_LOCATION (2),
6273                     "third argument to function %qE must be a constant integer",
6274                     fndecl);
6275           return false;
6276         }
6277       /* fall through */
6278
6279     case BUILT_IN_ALLOCA_WITH_ALIGN:
6280       {
6281         /* Get the requested alignment (in bits) if it's a constant
6282            integer expression.  */
6283         unsigned HOST_WIDE_INT align
6284           = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
6285
6286         /* Determine if the requested alignment is a power of 2.  */
6287         if ((align & (align - 1)))
6288           align = 0;
6289
6290         /* The maximum alignment in bits corresponding to the same
6291            maximum in bytes enforced in check_user_alignment().  */
6292         unsigned maxalign = (UINT_MAX >> 1) + 1;
6293
6294         /* Reject invalid alignments.  */
6295         if (align < BITS_PER_UNIT || maxalign < align)
6296           {
6297             error_at (ARG_LOCATION (1),
6298                       "second argument to function %qE must be a constant "
6299                       "integer power of 2 between %qi and %qu bits",
6300                       fndecl, BITS_PER_UNIT, maxalign);
6301             return false;
6302           }
6303         return true;
6304       }
6305
6306     case BUILT_IN_CONSTANT_P:
6307       return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
6308
6309     case BUILT_IN_ISFINITE:
6310     case BUILT_IN_ISINF:
6311     case BUILT_IN_ISINF_SIGN:
6312     case BUILT_IN_ISNAN:
6313     case BUILT_IN_ISNORMAL:
6314     case BUILT_IN_ISSIGNALING:
6315     case BUILT_IN_SIGNBIT:
6316       if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6317         {
6318           if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
6319             {
6320               error_at (ARG_LOCATION (0), "non-floating-point argument in "
6321                         "call to function %qE", fndecl);
6322               return false;
6323             }
6324           return true;
6325         }
6326       return false;
6327
6328     case BUILT_IN_ISGREATER:
6329     case BUILT_IN_ISGREATEREQUAL:
6330     case BUILT_IN_ISLESS:
6331     case BUILT_IN_ISLESSEQUAL:
6332     case BUILT_IN_ISLESSGREATER:
6333     case BUILT_IN_ISUNORDERED:
6334       if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
6335         {
6336           enum tree_code code0, code1;
6337           code0 = TREE_CODE (TREE_TYPE (args[0]));
6338           code1 = TREE_CODE (TREE_TYPE (args[1]));
6339           if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
6340                 || (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
6341                 || (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
6342             {
6343               error_at (loc, "non-floating-point arguments in call to "
6344                         "function %qE", fndecl);
6345               return false;
6346             }
6347           return true;
6348         }
6349       return false;
6350
6351     case BUILT_IN_FPCLASSIFY:
6352       if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
6353         {
6354           for (unsigned int i = 0; i < 5; i++)
6355             if (TREE_CODE (args[i]) != INTEGER_CST)
6356               {
6357                 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
6358                           "call to function %qE", i + 1, fndecl);
6359                 return false;
6360               }
6361
6362           if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
6363             {
6364               error_at (ARG_LOCATION (5), "non-floating-point argument in "
6365                         "call to function %qE", fndecl);
6366               return false;
6367             }
6368           return true;
6369         }
6370       return false;
6371
6372     case BUILT_IN_ASSUME_ALIGNED:
6373       if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
6374         {
6375           if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
6376             {
6377               error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
6378                         "function %qE", fndecl);
6379               return false;
6380             }
6381           return true;
6382         }
6383       return false;
6384
6385     case BUILT_IN_ADD_OVERFLOW:
6386     case BUILT_IN_SUB_OVERFLOW:
6387     case BUILT_IN_MUL_OVERFLOW:
6388       if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6389         {
6390           unsigned i;
6391           for (i = 0; i < 2; i++)
6392             if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6393               {
6394                 error_at (ARG_LOCATION (i), "argument %u in call to function "
6395                           "%qE does not have integral type", i + 1, fndecl);
6396                 return false;
6397               }
6398           if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
6399               || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
6400             {
6401               error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6402                         "does not have pointer to integral type", fndecl);
6403               return false;
6404             }
6405           else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
6406             {
6407               error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6408                         "has pointer to enumerated type", fndecl);
6409               return false;
6410             }
6411           else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
6412             {
6413               error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6414                         "has pointer to boolean type", fndecl);
6415               return false;
6416             }
6417           else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[2]))))
6418             {
6419               error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6420                         "has pointer to %qs type (%qT)", 3, fndecl, "const",
6421                         TREE_TYPE (args[2]));
6422               return false;
6423             }
6424           else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[2]))))
6425             {
6426               error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6427                         "has pointer to %qs type (%qT)", 3, fndecl,
6428                         "_Atomic", TREE_TYPE (args[2]));
6429               return false;
6430             }
6431           return true;
6432         }
6433       return false;
6434
6435     case BUILT_IN_ADD_OVERFLOW_P:
6436     case BUILT_IN_SUB_OVERFLOW_P:
6437     case BUILT_IN_MUL_OVERFLOW_P:
6438       if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6439         {
6440           unsigned i;
6441           for (i = 0; i < 3; i++)
6442             if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6443               {
6444                 error_at (ARG_LOCATION (i), "argument %u in call to function "
6445                           "%qE does not have integral type", i + 1, fndecl);
6446                 return false;
6447               }
6448           if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
6449             {
6450               error_at (ARG_LOCATION (2), "argument 3 in call to function "
6451                         "%qE has enumerated type", fndecl);
6452               return false;
6453             }
6454           else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
6455             {
6456               error_at (ARG_LOCATION (2), "argument 3 in call to function "
6457                         "%qE has boolean type", fndecl);
6458               return false;
6459             }
6460           return true;
6461         }
6462       return false;
6463
6464     case BUILT_IN_CLEAR_PADDING:
6465       if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6466         {
6467           if (!POINTER_TYPE_P (TREE_TYPE (args[0])))
6468             {
6469               error_at (ARG_LOCATION (0), "argument %u in call to function "
6470                         "%qE does not have pointer type", 1, fndecl);
6471               return false;
6472             }
6473           else if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (args[0]))))
6474             {
6475               error_at (ARG_LOCATION (0), "argument %u in call to function "
6476                         "%qE points to incomplete type", 1, fndecl);
6477               return false;
6478             }
6479           else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[0]))))
6480             {
6481               error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6482                         "has pointer to %qs type (%qT)", 1, fndecl, "const",
6483                         TREE_TYPE (args[0]));
6484               return false;
6485             }
6486           else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[0]))))
6487             {
6488               error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6489                         "has pointer to %qs type (%qT)", 1, fndecl,
6490                         "_Atomic", TREE_TYPE (args[0]));
6491               return false;
6492             }
6493           return true;
6494         }
6495       return false;
6496
6497     default:
6498       return true;
6499     }
6500 }
6501
6502 /* Subroutine of c_parse_error.
6503    Return the result of concatenating LHS and RHS. RHS is really
6504    a string literal, its first character is indicated by RHS_START and
6505    RHS_SIZE is its length (including the terminating NUL character).
6506
6507    The caller is responsible for deleting the returned pointer.  */
6508
6509 static char *
6510 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
6511 {
6512   const size_t lhs_size = strlen (lhs);
6513   char *result = XNEWVEC (char, lhs_size + rhs_size);
6514   memcpy (result, lhs, lhs_size);
6515   memcpy (result + lhs_size, rhs_start, rhs_size);
6516   return result;
6517 }
6518
6519 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
6520    before TOKEN, which had the associated VALUE.  */
6521
6522 void
6523 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
6524                tree value, unsigned char token_flags,
6525                rich_location *richloc)
6526 {
6527 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
6528
6529   char *message = NULL;
6530
6531   if (token_type == CPP_EOF)
6532     message = catenate_messages (gmsgid, " at end of input");
6533   else if (token_type == CPP_CHAR
6534            || token_type == CPP_WCHAR
6535            || token_type == CPP_CHAR16
6536            || token_type == CPP_CHAR32
6537            || token_type == CPP_UTF8CHAR)
6538     {
6539       unsigned int val = TREE_INT_CST_LOW (value);
6540       const char *prefix;
6541
6542       switch (token_type)
6543         {
6544         default:
6545           prefix = "";
6546           break;
6547         case CPP_WCHAR:
6548           prefix = "L";
6549           break;
6550         case CPP_CHAR16:
6551           prefix = "u";
6552           break;
6553         case CPP_CHAR32:
6554           prefix = "U";
6555           break;
6556         case CPP_UTF8CHAR:
6557           prefix = "u8";
6558           break;
6559         }
6560
6561       if (val <= UCHAR_MAX && ISGRAPH (val))
6562         message = catenate_messages (gmsgid, " before %s'%c'");
6563       else
6564         message = catenate_messages (gmsgid, " before %s'\\x%x'");
6565
6566       error_at (richloc, message, prefix, val);
6567       free (message);
6568       message = NULL;
6569     }
6570   else if (token_type == CPP_CHAR_USERDEF
6571            || token_type == CPP_WCHAR_USERDEF
6572            || token_type == CPP_CHAR16_USERDEF
6573            || token_type == CPP_CHAR32_USERDEF
6574            || token_type == CPP_UTF8CHAR_USERDEF)
6575     message = catenate_messages (gmsgid,
6576                                  " before user-defined character literal");
6577   else if (token_type == CPP_STRING_USERDEF
6578            || token_type == CPP_WSTRING_USERDEF
6579            || token_type == CPP_STRING16_USERDEF
6580            || token_type == CPP_STRING32_USERDEF
6581            || token_type == CPP_UTF8STRING_USERDEF)
6582     message = catenate_messages (gmsgid, " before user-defined string literal");
6583   else if (token_type == CPP_STRING
6584            || token_type == CPP_WSTRING
6585            || token_type == CPP_STRING16
6586            || token_type == CPP_STRING32
6587            || token_type == CPP_UTF8STRING)
6588     message = catenate_messages (gmsgid, " before string constant");
6589   else if (token_type == CPP_NUMBER)
6590     message = catenate_messages (gmsgid, " before numeric constant");
6591   else if (token_type == CPP_NAME)
6592     {
6593       message = catenate_messages (gmsgid, " before %qE");
6594       error_at (richloc, message, value);
6595       free (message);
6596       message = NULL;
6597     }
6598   else if (token_type == CPP_PRAGMA)
6599     message = catenate_messages (gmsgid, " before %<#pragma%>");
6600   else if (token_type == CPP_PRAGMA_EOL)
6601     message = catenate_messages (gmsgid, " before end of line");
6602   else if (token_type == CPP_DECLTYPE)
6603     message = catenate_messages (gmsgid, " before %<decltype%>");
6604   else if (token_type < N_TTYPES)
6605     {
6606       message = catenate_messages (gmsgid, " before %qs token");
6607       error_at (richloc, message, cpp_type2name (token_type, token_flags));
6608       free (message);
6609       message = NULL;
6610     }
6611   else
6612     error_at (richloc, gmsgid);
6613
6614   if (message)
6615     {
6616       error_at (richloc, message);
6617       free (message);
6618     }
6619 #undef catenate_messages
6620 }
6621
6622 /* Return the gcc option code associated with the reason for a cpp
6623    message, or 0 if none.  */
6624
6625 static int
6626 c_option_controlling_cpp_diagnostic (enum cpp_warning_reason reason)
6627 {
6628   const struct cpp_reason_option_codes_t *entry;
6629
6630   for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6631     {
6632       if (entry->reason == reason)
6633         return entry->option_code;
6634     }
6635   return 0;
6636 }
6637
6638 /* Return TRUE if the given option index corresponds to a diagnostic
6639    issued by libcpp.  Linear search seems fine for now.  */
6640 bool
6641 c_option_is_from_cpp_diagnostics (int option_index)
6642 {
6643   for (auto entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE;
6644        ++entry)
6645     {
6646       if (entry->option_code == option_index)
6647         return true;
6648     }
6649   return false;
6650 }
6651
6652 /* Callback from cpp_diagnostic for PFILE to print diagnostics from the
6653    preprocessor.  The diagnostic is of type LEVEL, with REASON set
6654    to the reason code if LEVEL is represents a warning, at location
6655    RICHLOC unless this is after lexing and the compiler's location
6656    should be used instead; MSG is the translated message and AP
6657    the arguments.  Returns true if a diagnostic was emitted, false
6658    otherwise.  */
6659
6660 bool
6661 c_cpp_diagnostic (cpp_reader *pfile ATTRIBUTE_UNUSED,
6662                   enum cpp_diagnostic_level level,
6663                   enum cpp_warning_reason reason,
6664                   rich_location *richloc,
6665                   const char *msg, va_list *ap)
6666 {
6667   diagnostic_info diagnostic;
6668   diagnostic_t dlevel;
6669   bool save_warn_system_headers = global_dc->dc_warn_system_headers;
6670   bool ret;
6671
6672   switch (level)
6673     {
6674     case CPP_DL_WARNING_SYSHDR:
6675       if (flag_no_output)
6676         return false;
6677       global_dc->dc_warn_system_headers = 1;
6678       /* Fall through.  */
6679     case CPP_DL_WARNING:
6680       if (flag_no_output)
6681         return false;
6682       dlevel = DK_WARNING;
6683       break;
6684     case CPP_DL_PEDWARN:
6685       if (flag_no_output && !flag_pedantic_errors)
6686         return false;
6687       dlevel = DK_PEDWARN;
6688       break;
6689     case CPP_DL_ERROR:
6690       dlevel = DK_ERROR;
6691       break;
6692     case CPP_DL_ICE:
6693       dlevel = DK_ICE;
6694       break;
6695     case CPP_DL_NOTE:
6696       dlevel = DK_NOTE;
6697       break;
6698     case CPP_DL_FATAL:
6699       dlevel = DK_FATAL;
6700       break;
6701     default:
6702       gcc_unreachable ();
6703     }
6704   if (override_libcpp_locations)
6705     richloc->set_range (0, input_location, SHOW_RANGE_WITH_CARET);
6706   diagnostic_set_info_translated (&diagnostic, msg, ap,
6707                                   richloc, dlevel);
6708   diagnostic_override_option_index
6709     (&diagnostic,
6710      c_option_controlling_cpp_diagnostic (reason));
6711   ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6712   if (level == CPP_DL_WARNING_SYSHDR)
6713     global_dc->dc_warn_system_headers = save_warn_system_headers;
6714   return ret;
6715 }
6716
6717 /* Convert a character from the host to the target execution character
6718    set.  cpplib handles this, mostly.  */
6719
6720 HOST_WIDE_INT
6721 c_common_to_target_charset (HOST_WIDE_INT c)
6722 {
6723   /* Character constants in GCC proper are sign-extended under -fsigned-char,
6724      zero-extended under -fno-signed-char.  cpplib insists that characters
6725      and character constants are always unsigned.  Hence we must convert
6726      back and forth.  */
6727   cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6728
6729   uc = cpp_host_to_exec_charset (parse_in, uc);
6730
6731   if (flag_signed_char)
6732     return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6733                                >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6734   else
6735     return uc;
6736 }
6737
6738 /* Fold an offsetof-like expression.  EXPR is a nested sequence of component
6739    references with an INDIRECT_REF of a constant at the bottom; much like the
6740    traditional rendering of offsetof as a macro.  TYPE is the desired type of
6741    the whole expression.  Return the folded result.  */
6742
6743 tree
6744 fold_offsetof (tree expr, tree type, enum tree_code ctx)
6745 {
6746   tree base, off, t;
6747   tree_code code = TREE_CODE (expr);
6748   switch (code)
6749     {
6750     case ERROR_MARK:
6751       return expr;
6752
6753     case VAR_DECL:
6754       error ("cannot apply %<offsetof%> to static data member %qD", expr);
6755       return error_mark_node;
6756
6757     case CALL_EXPR:
6758     case TARGET_EXPR:
6759       error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6760       return error_mark_node;
6761
6762     case NOP_EXPR:
6763     case INDIRECT_REF:
6764       if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6765         {
6766           error ("cannot apply %<offsetof%> to a non constant address");
6767           return error_mark_node;
6768         }
6769       return convert (type, TREE_OPERAND (expr, 0));
6770
6771     case COMPONENT_REF:
6772       base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6773       if (base == error_mark_node)
6774         return base;
6775
6776       t = TREE_OPERAND (expr, 1);
6777       if (DECL_C_BIT_FIELD (t))
6778         {
6779           error ("attempt to take address of bit-field structure "
6780                  "member %qD", t);
6781           return error_mark_node;
6782         }
6783       off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6784                             size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6785                                       / BITS_PER_UNIT));
6786       break;
6787
6788     case ARRAY_REF:
6789       base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6790       if (base == error_mark_node)
6791         return base;
6792
6793       t = TREE_OPERAND (expr, 1);
6794       STRIP_ANY_LOCATION_WRAPPER (t);
6795
6796       /* Check if the offset goes beyond the upper bound of the array.  */
6797       if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6798         {
6799           tree upbound = array_ref_up_bound (expr);
6800           if (upbound != NULL_TREE
6801               && TREE_CODE (upbound) == INTEGER_CST
6802               && !tree_int_cst_equal (upbound,
6803                                       TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6804             {
6805               if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6806                 upbound = size_binop (PLUS_EXPR, upbound,
6807                                       build_int_cst (TREE_TYPE (upbound), 1));
6808               if (tree_int_cst_lt (upbound, t))
6809                 {
6810                   tree v;
6811
6812                   for (v = TREE_OPERAND (expr, 0);
6813                        TREE_CODE (v) == COMPONENT_REF;
6814                        v = TREE_OPERAND (v, 0))
6815                     if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6816                         == RECORD_TYPE)
6817                       {
6818                         tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6819                         for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6820                           if (TREE_CODE (fld_chain) == FIELD_DECL)
6821                             break;
6822
6823                         if (fld_chain)
6824                           break;
6825                       }
6826                   /* Don't warn if the array might be considered a poor
6827                      man's flexible array member with a very permissive
6828                      definition thereof.  */
6829                   if (TREE_CODE (v) == ARRAY_REF
6830                       || TREE_CODE (v) == COMPONENT_REF)
6831                     warning (OPT_Warray_bounds,
6832                              "index %E denotes an offset "
6833                              "greater than size of %qT",
6834                              t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6835                 }
6836             }
6837         }
6838
6839       t = convert (sizetype, t);
6840       off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6841       break;
6842
6843     case COMPOUND_EXPR:
6844       /* Handle static members of volatile structs.  */
6845       t = TREE_OPERAND (expr, 1);
6846       gcc_checking_assert (VAR_P (get_base_address (t)));
6847       return fold_offsetof (t, type);
6848
6849     default:
6850       gcc_unreachable ();
6851     }
6852
6853   if (!POINTER_TYPE_P (type))
6854     return size_binop (PLUS_EXPR, base, convert (type, off));
6855   return fold_build_pointer_plus (base, off);
6856 }
6857 \f
6858 /* *PTYPE is an incomplete array.  Complete it with a domain based on
6859    INITIAL_VALUE.  If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6860    is true.  Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6861    2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty.  */
6862
6863 int
6864 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6865 {
6866   tree maxindex, type, main_type, elt, unqual_elt;
6867   int failure = 0, quals;
6868   bool overflow_p = false;
6869
6870   maxindex = size_zero_node;
6871   if (initial_value)
6872     {
6873       STRIP_ANY_LOCATION_WRAPPER (initial_value);
6874
6875       if (TREE_CODE (initial_value) == STRING_CST)
6876         {
6877           int eltsize
6878             = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6879           maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6880         }
6881       else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6882         {
6883           vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6884
6885           if (vec_safe_is_empty (v))
6886             {
6887               if (pedantic)
6888                 failure = 3;
6889               maxindex = ssize_int (-1);
6890             }
6891           else
6892             {
6893               tree curindex;
6894               unsigned HOST_WIDE_INT cnt;
6895               constructor_elt *ce;
6896               bool fold_p = false;
6897
6898               if ((*v)[0].index)
6899                 maxindex = (*v)[0].index, fold_p = true;
6900
6901               curindex = maxindex;
6902
6903               for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
6904                 {
6905                   bool curfold_p = false;
6906                   if (ce->index)
6907                     curindex = ce->index, curfold_p = true;
6908                   else
6909                     {
6910                       if (fold_p)
6911                         {
6912                           /* Since we treat size types now as ordinary
6913                              unsigned types, we need an explicit overflow
6914                              check.  */
6915                           tree orig = curindex;
6916                           curindex = fold_convert (sizetype, curindex);
6917                           overflow_p |= tree_int_cst_lt (curindex, orig);
6918                         }
6919                       curindex = size_binop (PLUS_EXPR, curindex,
6920                                              size_one_node);
6921                     }
6922                   if (tree_int_cst_lt (maxindex, curindex))
6923                     maxindex = curindex, fold_p = curfold_p;
6924                 }
6925               if (fold_p)
6926                 {
6927                   tree orig = maxindex;
6928                   maxindex = fold_convert (sizetype, maxindex);
6929                   overflow_p |= tree_int_cst_lt (maxindex, orig);
6930                 }
6931             }
6932         }
6933       else
6934         {
6935           /* Make an error message unless that happened already.  */
6936           if (initial_value != error_mark_node)
6937             failure = 1;
6938         }
6939     }
6940   else
6941     {
6942       failure = 2;
6943       if (!do_default)
6944         return failure;
6945     }
6946
6947   type = *ptype;
6948   elt = TREE_TYPE (type);
6949   quals = TYPE_QUALS (strip_array_types (elt));
6950   if (quals == 0)
6951     unqual_elt = elt;
6952   else
6953     unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
6954
6955   /* Using build_distinct_type_copy and modifying things afterward instead
6956      of using build_array_type to create a new type preserves all of the
6957      TYPE_LANG_FLAG_? bits that the front end may have set.  */
6958   main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
6959   TREE_TYPE (main_type) = unqual_elt;
6960   TYPE_DOMAIN (main_type)
6961     = build_range_type (TREE_TYPE (maxindex),
6962                         build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
6963   TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
6964   layout_type (main_type);
6965
6966   /* Make sure we have the canonical MAIN_TYPE. */
6967   hashval_t hashcode = type_hash_canon_hash (main_type);
6968   main_type = type_hash_canon (hashcode, main_type);
6969
6970   /* Fix the canonical type.  */
6971   if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
6972       || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
6973     SET_TYPE_STRUCTURAL_EQUALITY (main_type);
6974   else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
6975            || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
6976                != TYPE_DOMAIN (main_type)))
6977     TYPE_CANONICAL (main_type)
6978       = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
6979                           TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
6980                           TYPE_TYPELESS_STORAGE (main_type));
6981   else
6982     TYPE_CANONICAL (main_type) = main_type;
6983
6984   if (quals == 0)
6985     type = main_type;
6986   else
6987     type = c_build_qualified_type (main_type, quals);
6988
6989   if (COMPLETE_TYPE_P (type)
6990       && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
6991       && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
6992     {
6993       error ("size of array is too large");
6994       /* If we proceed with the array type as it is, we'll eventually
6995          crash in tree_to_[su]hwi().  */
6996       type = error_mark_node;
6997     }
6998
6999   *ptype = type;
7000   return failure;
7001 }
7002
7003 /* INIT is an constructor of a structure with a flexible array member.
7004    Complete the flexible array member with a domain based on it's value.  */
7005 void
7006 complete_flexible_array_elts (tree init)
7007 {
7008   tree elt, type;
7009
7010   if (init == NULL_TREE || TREE_CODE (init) != CONSTRUCTOR)
7011     return;
7012
7013   if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
7014     return;
7015
7016   elt = CONSTRUCTOR_ELTS (init)->last ().value;
7017   type = TREE_TYPE (elt);
7018   if (TREE_CODE (type) == ARRAY_TYPE
7019       && TYPE_SIZE (type) == NULL_TREE)
7020     complete_array_type (&TREE_TYPE (elt), elt, false);
7021   else
7022     complete_flexible_array_elts (elt);
7023 }
7024
7025 /* Like c_mark_addressable but don't check register qualifier.  */
7026 void 
7027 c_common_mark_addressable_vec (tree t)
7028 {   
7029   while (handled_component_p (t) || TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7030     {
7031       if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7032         t = C_MAYBE_CONST_EXPR_EXPR (t);
7033       else
7034         t = TREE_OPERAND (t, 0);
7035     }
7036   if (!VAR_P (t)
7037       && TREE_CODE (t) != PARM_DECL
7038       && TREE_CODE (t) != COMPOUND_LITERAL_EXPR
7039       && TREE_CODE (t) != TARGET_EXPR)
7040     return;
7041   if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
7042     TREE_ADDRESSABLE (t) = 1;
7043   if (TREE_CODE (t) == COMPOUND_LITERAL_EXPR)
7044     TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (t)) = 1;
7045   else if (TREE_CODE (t) == TARGET_EXPR)
7046     TREE_ADDRESSABLE (TARGET_EXPR_SLOT (t)) = 1;
7047 }
7048
7049
7050 \f
7051 /* Used to help initialize the builtin-types.def table.  When a type of
7052    the correct size doesn't exist, use error_mark_node instead of NULL.
7053    The later results in segfaults even when a decl using the type doesn't
7054    get invoked.  */
7055
7056 tree
7057 builtin_type_for_size (int size, bool unsignedp)
7058 {
7059   tree type = c_common_type_for_size (size, unsignedp);
7060   return type ? type : error_mark_node;
7061 }
7062
7063 /* Work out the size of the first argument of a call to
7064    __builtin_speculation_safe_value.  Only pointers and integral types
7065    are permitted.  Return -1 if the argument type is not supported or
7066    the size is too large; 0 if the argument type is a pointer or the
7067    size if it is integral.  */
7068 static enum built_in_function
7069 speculation_safe_value_resolve_call (tree function, vec<tree, va_gc> *params)
7070 {
7071   /* Type of the argument.  */
7072   tree type;
7073   int size;
7074
7075   if (vec_safe_is_empty (params))
7076     {
7077       error ("too few arguments to function %qE", function);
7078       return BUILT_IN_NONE;
7079     }
7080
7081   type = TREE_TYPE ((*params)[0]);
7082   if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7083     {
7084       /* Force array-to-pointer decay for C++.   */
7085       (*params)[0] = default_conversion ((*params)[0]);
7086       type = TREE_TYPE ((*params)[0]);
7087     }
7088
7089   if (POINTER_TYPE_P (type))
7090     return BUILT_IN_SPECULATION_SAFE_VALUE_PTR;
7091
7092   if (!INTEGRAL_TYPE_P (type))
7093     goto incompatible;
7094
7095   if (!COMPLETE_TYPE_P (type))
7096     goto incompatible;
7097
7098   size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7099   if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7100     return ((enum built_in_function)
7101             ((int) BUILT_IN_SPECULATION_SAFE_VALUE_1 + exact_log2 (size)));
7102
7103  incompatible:
7104   /* Issue the diagnostic only if the argument is valid, otherwise
7105      it would be redundant at best and could be misleading.  */
7106   if (type != error_mark_node)
7107     error ("operand type %qT is incompatible with argument %d of %qE",
7108            type, 1, function);
7109
7110   return BUILT_IN_NONE;
7111 }
7112
7113 /* Validate and coerce PARAMS, the arguments to ORIG_FUNCTION to fit
7114    the prototype for FUNCTION.  The first argument is mandatory, a second
7115    argument, if present, must be type compatible with the first.  */
7116 static bool
7117 speculation_safe_value_resolve_params (location_t loc, tree orig_function,
7118                                        vec<tree, va_gc> *params)
7119 {
7120   tree val;
7121
7122   if (params->length () == 0)
7123     {
7124       error_at (loc, "too few arguments to function %qE", orig_function);
7125       return false;
7126     }
7127
7128   else if (params->length () > 2)
7129     {
7130       error_at (loc, "too many arguments to function %qE", orig_function);
7131       return false;
7132     }
7133
7134   val = (*params)[0];
7135   if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE)
7136     val = default_conversion (val);
7137   if (!(TREE_CODE (TREE_TYPE (val)) == POINTER_TYPE
7138         || TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE))
7139     {
7140       error_at (loc,
7141                 "expecting argument of type pointer or of type integer "
7142                 "for argument 1");
7143       return false;
7144     }
7145   (*params)[0] = val;
7146
7147   if (params->length () == 2)
7148     {
7149       tree val2 = (*params)[1];
7150       if (TREE_CODE (TREE_TYPE (val2)) == ARRAY_TYPE)
7151         val2 = default_conversion (val2);
7152       if (error_operand_p (val2))
7153         return false;
7154       if (!(TREE_TYPE (val) == TREE_TYPE (val2)
7155             || useless_type_conversion_p (TREE_TYPE (val), TREE_TYPE (val2))))
7156         {
7157           error_at (loc, "both arguments must be compatible");
7158           return false;
7159         }
7160       (*params)[1] = val2;
7161     }
7162
7163   return true;
7164 }
7165
7166 /* Cast the result of the builtin back to the type of the first argument,
7167    preserving any qualifiers that it might have.  */
7168 static tree
7169 speculation_safe_value_resolve_return (tree first_param, tree result)
7170 {
7171   tree ptype = TREE_TYPE (first_param);
7172   tree rtype = TREE_TYPE (result);
7173   ptype = TYPE_MAIN_VARIANT (ptype);
7174
7175   if (tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7176     return convert (ptype, result);
7177
7178   return result;
7179 }
7180
7181 /* A helper function for resolve_overloaded_builtin in resolving the
7182    overloaded __sync_ builtins.  Returns a positive power of 2 if the
7183    first operand of PARAMS is a pointer to a supported data type.
7184    Returns 0 if an error is encountered.
7185    FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
7186    built-ins.  */
7187
7188 static int
7189 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch)
7190 {
7191   /* Type of the argument.  */
7192   tree argtype;
7193   /* Type the argument points to.  */
7194   tree type;
7195   int size;
7196
7197   if (vec_safe_is_empty (params))
7198     {
7199       error ("too few arguments to function %qE", function);
7200       return 0;
7201     }
7202
7203   argtype = type = TREE_TYPE ((*params)[0]);
7204   if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7205     {
7206       /* Force array-to-pointer decay for C++.  */
7207       (*params)[0] = default_conversion ((*params)[0]);
7208       type = TREE_TYPE ((*params)[0]);
7209     }
7210   if (TREE_CODE (type) != POINTER_TYPE)
7211     goto incompatible;
7212
7213   type = TREE_TYPE (type);
7214   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
7215     goto incompatible;
7216
7217   if (!COMPLETE_TYPE_P (type))
7218     goto incompatible;
7219
7220   if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
7221     goto incompatible;
7222
7223   size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7224   if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7225     return size;
7226
7227  incompatible:
7228   /* Issue the diagnostic only if the argument is valid, otherwise
7229      it would be redundant at best and could be misleading.  */
7230   if (argtype != error_mark_node)
7231     error ("operand type %qT is incompatible with argument %d of %qE",
7232            argtype, 1, function);
7233   return 0;
7234 }
7235
7236 /* A helper function for resolve_overloaded_builtin.  Adds casts to
7237    PARAMS to make arguments match up with those of FUNCTION.  Drops
7238    the variadic arguments at the end.  Returns false if some error
7239    was encountered; true on success.  */
7240
7241 static bool
7242 sync_resolve_params (location_t loc, tree orig_function, tree function,
7243                      vec<tree, va_gc> *params, bool orig_format)
7244 {
7245   function_args_iterator iter;
7246   tree ptype;
7247   unsigned int parmnum;
7248
7249   function_args_iter_init (&iter, TREE_TYPE (function));
7250   /* We've declared the implementation functions to use "volatile void *"
7251      as the pointer parameter, so we shouldn't get any complaints from the
7252      call to check_function_arguments what ever type the user used.  */
7253   function_args_iter_next (&iter);
7254   ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
7255   ptype = TYPE_MAIN_VARIANT (ptype);
7256
7257   /* For the rest of the values, we need to cast these to FTYPE, so that we
7258      don't get warnings for passing pointer types, etc.  */
7259   parmnum = 0;
7260   while (1)
7261     {
7262       tree val, arg_type;
7263
7264       arg_type = function_args_iter_cond (&iter);
7265       /* XXX void_type_node belies the abstraction.  */
7266       if (arg_type == void_type_node)
7267         break;
7268
7269       ++parmnum;
7270       if (params->length () <= parmnum)
7271         {
7272           error_at (loc, "too few arguments to function %qE", orig_function);
7273           return false;
7274         }
7275
7276       /* Only convert parameters if arg_type is unsigned integer type with
7277          new format sync routines, i.e. don't attempt to convert pointer
7278          arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
7279          bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
7280          kinds).  */
7281       if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
7282         {
7283           /* Ideally for the first conversion we'd use convert_for_assignment
7284              so that we get warnings for anything that doesn't match the pointer
7285              type.  This isn't portable across the C and C++ front ends atm.  */
7286           val = (*params)[parmnum];
7287           val = convert (ptype, val);
7288           val = convert (arg_type, val);
7289           (*params)[parmnum] = val;
7290         }
7291
7292       function_args_iter_next (&iter);
7293     }
7294
7295   /* __atomic routines are not variadic.  */
7296   if (!orig_format && params->length () != parmnum + 1)
7297     {
7298       error_at (loc, "too many arguments to function %qE", orig_function);
7299       return false;
7300     }
7301
7302   /* The definition of these primitives is variadic, with the remaining
7303      being "an optional list of variables protected by the memory barrier".
7304      No clue what that's supposed to mean, precisely, but we consider all
7305      call-clobbered variables to be protected so we're safe.  */
7306   params->truncate (parmnum + 1);
7307
7308   return true;
7309 }
7310
7311 /* A helper function for resolve_overloaded_builtin.  Adds a cast to
7312    RESULT to make it match the type of the first pointer argument in
7313    PARAMS.  */
7314
7315 static tree
7316 sync_resolve_return (tree first_param, tree result, bool orig_format)
7317 {
7318   tree ptype = TREE_TYPE (TREE_TYPE (first_param));
7319   tree rtype = TREE_TYPE (result);
7320   ptype = TYPE_MAIN_VARIANT (ptype);
7321
7322   /* New format doesn't require casting unless the types are the same size.  */
7323   if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7324     return convert (ptype, result);
7325   else
7326     return result;
7327 }
7328
7329 /* This function verifies the PARAMS to generic atomic FUNCTION.
7330    It returns the size if all the parameters are the same size, otherwise
7331    0 is returned if the parameters are invalid.  */
7332
7333 static int
7334 get_atomic_generic_size (location_t loc, tree function,
7335                          vec<tree, va_gc> *params)
7336 {
7337   unsigned int n_param;
7338   unsigned int n_model;
7339   unsigned int outputs = 0; // bitset of output parameters
7340   unsigned int x;
7341   int size_0;
7342   tree type_0;
7343
7344   /* Determine the parameter makeup.  */
7345   switch (DECL_FUNCTION_CODE (function))
7346     {
7347     case BUILT_IN_ATOMIC_EXCHANGE:
7348       n_param = 4;
7349       n_model = 1;
7350       outputs = 5;
7351       break;
7352     case BUILT_IN_ATOMIC_LOAD:
7353       n_param = 3;
7354       n_model = 1;
7355       outputs = 2;
7356       break;
7357     case BUILT_IN_ATOMIC_STORE:
7358       n_param = 3;
7359       n_model = 1;
7360       outputs = 1;
7361       break;
7362     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7363       n_param = 6;
7364       n_model = 2;
7365       outputs = 3;
7366       break;
7367     default:
7368       gcc_unreachable ();
7369     }
7370
7371   if (vec_safe_length (params) != n_param)
7372     {
7373       error_at (loc, "incorrect number of arguments to function %qE", function);
7374       return 0;
7375     }
7376
7377   /* Get type of first parameter, and determine its size.  */
7378   type_0 = TREE_TYPE ((*params)[0]);
7379   if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
7380     {
7381       /* Force array-to-pointer decay for C++.  */
7382       (*params)[0] = default_conversion ((*params)[0]);
7383       type_0 = TREE_TYPE ((*params)[0]);
7384     }
7385   if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
7386     {
7387       error_at (loc, "argument 1 of %qE must be a non-void pointer type",
7388                 function);
7389       return 0;
7390     }
7391
7392   if (!COMPLETE_TYPE_P (TREE_TYPE (type_0)))
7393     {
7394       error_at (loc, "argument 1 of %qE must be a pointer to a complete type",
7395                 function);
7396       return 0;
7397     }
7398
7399   /* Types must be compile time constant sizes. */
7400   if (!tree_fits_uhwi_p ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))))
7401     {
7402       error_at (loc, 
7403                 "argument 1 of %qE must be a pointer to a constant size type",
7404                 function);
7405       return 0;
7406     }
7407
7408   size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
7409
7410   /* Zero size objects are not allowed.  */
7411   if (size_0 == 0)
7412     {
7413       error_at (loc, 
7414                 "argument 1 of %qE must be a pointer to a nonzero size object",
7415                 function);
7416       return 0;
7417     }
7418
7419   /* Check each other parameter is a pointer and the same size.  */
7420   for (x = 0; x < n_param - n_model; x++)
7421     {
7422       int size;
7423       tree type = TREE_TYPE ((*params)[x]);
7424       /* __atomic_compare_exchange has a bool in the 4th position, skip it.  */
7425       if (n_param == 6 && x == 3)
7426         continue;
7427       if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7428         {
7429           /* Force array-to-pointer decay for C++.  */
7430           (*params)[x] = default_conversion ((*params)[x]);
7431           type = TREE_TYPE ((*params)[x]);
7432         }
7433       if (!POINTER_TYPE_P (type))
7434         {
7435           error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
7436                     function);
7437           return 0;
7438         }
7439       else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
7440                && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
7441                   != INTEGER_CST)
7442         {
7443           error_at (loc, "argument %d of %qE must be a pointer to a constant "
7444                     "size type", x + 1, function);
7445           return 0;
7446         }
7447       else if (FUNCTION_POINTER_TYPE_P (type))
7448         {
7449           error_at (loc, "argument %d of %qE must not be a pointer to a "
7450                     "function", x + 1, function);
7451           return 0;
7452         }
7453       tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
7454       size = type_size ? tree_to_uhwi (type_size) : 0;
7455       if (size != size_0)
7456         {
7457           error_at (loc, "size mismatch in argument %d of %qE", x + 1,
7458                     function);
7459           return 0;
7460         }
7461
7462       {
7463         auto_diagnostic_group d;
7464         int quals = TYPE_QUALS (TREE_TYPE (type));
7465         /* Must not write to an argument of a const-qualified type.  */
7466         if (outputs & (1 << x) && quals & TYPE_QUAL_CONST)
7467           {
7468             if (c_dialect_cxx ())
7469               {
7470                 error_at (loc, "argument %d of %qE must not be a pointer to "
7471                           "a %<const%> type", x + 1, function);
7472                 return 0;
7473               }
7474             else
7475               pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7476                        "of %qE discards %<const%> qualifier", x + 1,
7477                        function);
7478           }
7479         /* Only the first argument is allowed to be volatile.  */
7480         if (x > 0 && quals & TYPE_QUAL_VOLATILE)
7481           {
7482             if (c_dialect_cxx ())
7483               {
7484                 error_at (loc, "argument %d of %qE must not be a pointer to "
7485                           "a %<volatile%> type", x + 1, function);
7486                 return 0;
7487               }
7488             else
7489               pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7490                        "of %qE discards %<volatile%> qualifier", x + 1,
7491                        function);
7492           }
7493       }
7494     }
7495
7496   /* Check memory model parameters for validity.  */
7497   for (x = n_param - n_model ; x < n_param; x++)
7498     {
7499       tree p = (*params)[x];
7500       if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
7501         {
7502           error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
7503                     function);
7504           return 0;
7505         }
7506       p = fold_for_warn (p);
7507       if (TREE_CODE (p) == INTEGER_CST)
7508         {
7509           /* memmodel_base masks the low 16 bits, thus ignore any bits above
7510              it by using TREE_INT_CST_LOW instead of tree_to_*hwi.  Those high
7511              bits will be checked later during expansion in target specific
7512              way.  */
7513           if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
7514             warning_at (loc, OPT_Winvalid_memory_model,
7515                         "invalid memory model argument %d of %qE", x + 1,
7516                         function);
7517         }
7518     }
7519
7520   return size_0;
7521 }
7522
7523
7524 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
7525    at the beginning of the parameter list PARAMS representing the size of the
7526    objects.  This is to match the library ABI requirement.  LOC is the location
7527    of the function call.  
7528    The new function is returned if it needed rebuilding, otherwise NULL_TREE is
7529    returned to allow the external call to be constructed.  */
7530
7531 static tree
7532 add_atomic_size_parameter (unsigned n, location_t loc, tree function, 
7533                            vec<tree, va_gc> *params)
7534 {
7535   tree size_node;
7536
7537   /* Insert a SIZE_T parameter as the first param.  If there isn't
7538      enough space, allocate a new vector and recursively re-build with that.  */
7539   if (!params->space (1))
7540     {
7541       unsigned int z, len;
7542       vec<tree, va_gc> *v;
7543       tree f;
7544
7545       len = params->length ();
7546       vec_alloc (v, len + 1);
7547       v->quick_push (build_int_cst (size_type_node, n));
7548       for (z = 0; z < len; z++)
7549         v->quick_push ((*params)[z]);
7550       f = build_function_call_vec (loc, vNULL, function, v, NULL);
7551       vec_free (v);
7552       return f;
7553     }
7554
7555   /* Add the size parameter and leave as a function call for processing.  */
7556   size_node = build_int_cst (size_type_node, n);
7557   params->quick_insert (0, size_node);
7558   return NULL_TREE;
7559 }
7560
7561
7562 /* Return whether atomic operations for naturally aligned N-byte
7563    arguments are supported, whether inline or through libatomic.  */
7564 static bool
7565 atomic_size_supported_p (int n)
7566 {
7567   switch (n)
7568     {
7569     case 1:
7570     case 2:
7571     case 4:
7572     case 8:
7573       return true;
7574
7575     case 16:
7576       return targetm.scalar_mode_supported_p (TImode);
7577
7578     default:
7579       return false;
7580     }
7581 }
7582
7583 /* This will process an __atomic_exchange function call, determine whether it
7584    needs to be mapped to the _N variation, or turned into a library call.
7585    LOC is the location of the builtin call.
7586    FUNCTION is the DECL that has been invoked;
7587    PARAMS is the argument list for the call.  The return value is non-null
7588    TRUE is returned if it is translated into the proper format for a call to the
7589    external library, and NEW_RETURN is set the tree for that function.
7590    FALSE is returned if processing for the _N variation is required, and 
7591    NEW_RETURN is set to the return value the result is copied into.  */
7592 static bool
7593 resolve_overloaded_atomic_exchange (location_t loc, tree function, 
7594                                     vec<tree, va_gc> *params, tree *new_return)
7595 {       
7596   tree p0, p1, p2, p3;
7597   tree I_type, I_type_ptr;
7598   int n = get_atomic_generic_size (loc, function, params);
7599
7600   /* Size of 0 is an error condition.  */
7601   if (n == 0)
7602     {
7603       *new_return = error_mark_node;
7604       return true;
7605     }
7606
7607   /* If not a lock-free size, change to the library generic format.  */
7608   if (!atomic_size_supported_p (n))
7609     {
7610       *new_return = add_atomic_size_parameter (n, loc, function, params);
7611       return true;
7612     }
7613
7614   /* Otherwise there is a lockfree match, transform the call from:
7615        void fn(T* mem, T* desired, T* return, model)
7616      into
7617        *return = (T) (fn (In* mem, (In) *desired, model))  */
7618
7619   p0 = (*params)[0];
7620   p1 = (*params)[1];
7621   p2 = (*params)[2];
7622   p3 = (*params)[3];
7623   
7624   /* Create pointer to appropriate size.  */
7625   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7626   I_type_ptr = build_pointer_type (I_type);
7627
7628   /* Convert object pointer to required type.  */
7629   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7630   (*params)[0] = p0; 
7631   /* Convert new value to required type, and dereference it.  */
7632   p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7633   p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7634   (*params)[1] = p1;
7635
7636   /* Move memory model to the 3rd position, and end param list.  */
7637   (*params)[2] = p3;
7638   params->truncate (3);
7639
7640   /* Convert return pointer and dereference it for later assignment.  */
7641   *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7642
7643   return false;
7644 }
7645
7646
7647 /* This will process an __atomic_compare_exchange function call, determine 
7648    whether it needs to be mapped to the _N variation, or turned into a lib call.
7649    LOC is the location of the builtin call.
7650    FUNCTION is the DECL that has been invoked;
7651    PARAMS is the argument list for the call.  The return value is non-null
7652    TRUE is returned if it is translated into the proper format for a call to the
7653    external library, and NEW_RETURN is set the tree for that function.
7654    FALSE is returned if processing for the _N variation is required.  */
7655
7656 static bool
7657 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function, 
7658                                             vec<tree, va_gc> *params, 
7659                                             tree *new_return)
7660 {       
7661   tree p0, p1, p2;
7662   tree I_type, I_type_ptr;
7663   int n = get_atomic_generic_size (loc, function, params);
7664
7665   /* Size of 0 is an error condition.  */
7666   if (n == 0)
7667     {
7668       *new_return = error_mark_node;
7669       return true;
7670     }
7671
7672   /* If not a lock-free size, change to the library generic format.  */
7673   if (!atomic_size_supported_p (n))
7674     {
7675       /* The library generic format does not have the weak parameter, so 
7676          remove it from the param list.  Since a parameter has been removed,
7677          we can be sure that there is room for the SIZE_T parameter, meaning
7678          there will not be a recursive rebuilding of the parameter list, so
7679          there is no danger this will be done twice.  */
7680       if (n > 0)
7681         {
7682           (*params)[3] = (*params)[4];
7683           (*params)[4] = (*params)[5];
7684           params->truncate (5);
7685         }
7686       *new_return = add_atomic_size_parameter (n, loc, function, params);
7687       return true;
7688     }
7689
7690   /* Otherwise, there is a match, so the call needs to be transformed from:
7691        bool fn(T* mem, T* desired, T* return, weak, success, failure)
7692      into
7693        bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail)  */
7694
7695   p0 = (*params)[0];
7696   p1 = (*params)[1];
7697   p2 = (*params)[2];
7698   
7699   /* Create pointer to appropriate size.  */
7700   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7701   I_type_ptr = build_pointer_type (I_type);
7702
7703   /* Convert object pointer to required type.  */
7704   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7705   (*params)[0] = p0;
7706
7707   /* Convert expected pointer to required type.  */
7708   p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
7709   (*params)[1] = p1;
7710
7711   /* Convert desired value to required type, and dereference it.  */
7712   p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7713   p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
7714   (*params)[2] = p2;
7715
7716   /* The rest of the parameters are fine. NULL means no special return value
7717      processing.*/
7718   *new_return = NULL;
7719   return false;
7720 }
7721
7722
7723 /* This will process an __atomic_load function call, determine whether it
7724    needs to be mapped to the _N variation, or turned into a library call.
7725    LOC is the location of the builtin call.
7726    FUNCTION is the DECL that has been invoked;
7727    PARAMS is the argument list for the call.  The return value is non-null
7728    TRUE is returned if it is translated into the proper format for a call to the
7729    external library, and NEW_RETURN is set the tree for that function.
7730    FALSE is returned if processing for the _N variation is required, and 
7731    NEW_RETURN is set to the return value the result is copied into.  */
7732
7733 static bool
7734 resolve_overloaded_atomic_load (location_t loc, tree function, 
7735                                 vec<tree, va_gc> *params, tree *new_return)
7736 {       
7737   tree p0, p1, p2;
7738   tree I_type, I_type_ptr;
7739   int n = get_atomic_generic_size (loc, function, params);
7740
7741   /* Size of 0 is an error condition.  */
7742   if (n == 0)
7743     {
7744       *new_return = error_mark_node;
7745       return true;
7746     }
7747
7748   /* If not a lock-free size, change to the library generic format.  */
7749   if (!atomic_size_supported_p (n))
7750     {
7751       *new_return = add_atomic_size_parameter (n, loc, function, params);
7752       return true;
7753     }
7754
7755   /* Otherwise, there is a match, so the call needs to be transformed from:
7756        void fn(T* mem, T* return, model)
7757      into
7758        *return = (T) (fn ((In *) mem, model))  */
7759
7760   p0 = (*params)[0];
7761   p1 = (*params)[1];
7762   p2 = (*params)[2];
7763   
7764   /* Create pointer to appropriate size.  */
7765   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7766   I_type_ptr = build_pointer_type (I_type);
7767
7768   /* Convert object pointer to required type.  */
7769   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7770   (*params)[0] = p0;
7771
7772   /* Move memory model to the 2nd position, and end param list.  */
7773   (*params)[1] = p2;
7774   params->truncate (2);
7775
7776   /* Convert return pointer and dereference it for later assignment.  */
7777   *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7778
7779   return false;
7780 }
7781
7782
7783 /* This will process an __atomic_store function call, determine whether it
7784    needs to be mapped to the _N variation, or turned into a library call.
7785    LOC is the location of the builtin call.
7786    FUNCTION is the DECL that has been invoked;
7787    PARAMS is the argument list for the call.  The return value is non-null
7788    TRUE is returned if it is translated into the proper format for a call to the
7789    external library, and NEW_RETURN is set the tree for that function.
7790    FALSE is returned if processing for the _N variation is required, and 
7791    NEW_RETURN is set to the return value the result is copied into.  */
7792
7793 static bool
7794 resolve_overloaded_atomic_store (location_t loc, tree function, 
7795                                  vec<tree, va_gc> *params, tree *new_return)
7796 {       
7797   tree p0, p1;
7798   tree I_type, I_type_ptr;
7799   int n = get_atomic_generic_size (loc, function, params);
7800
7801   /* Size of 0 is an error condition.  */
7802   if (n == 0)
7803     {
7804       *new_return = error_mark_node;
7805       return true;
7806     }
7807
7808   /* If not a lock-free size, change to the library generic format.  */
7809   if (!atomic_size_supported_p (n))
7810     {
7811       *new_return = add_atomic_size_parameter (n, loc, function, params);
7812       return true;
7813     }
7814
7815   /* Otherwise, there is a match, so the call needs to be transformed from:
7816        void fn(T* mem, T* value, model)
7817      into
7818        fn ((In *) mem, (In) *value, model)  */
7819
7820   p0 = (*params)[0];
7821   p1 = (*params)[1];
7822   
7823   /* Create pointer to appropriate size.  */
7824   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7825   I_type_ptr = build_pointer_type (I_type);
7826
7827   /* Convert object pointer to required type.  */
7828   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7829   (*params)[0] = p0;
7830
7831   /* Convert new value to required type, and dereference it.  */
7832   p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7833   p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7834   (*params)[1] = p1;
7835   
7836   /* The memory model is in the right spot already. Return is void.  */
7837   *new_return = NULL_TREE;
7838
7839   return false;
7840 }
7841
7842
7843 /* Some builtin functions are placeholders for other expressions.  This
7844    function should be called immediately after parsing the call expression
7845    before surrounding code has committed to the type of the expression.
7846
7847    LOC is the location of the builtin call.
7848
7849    FUNCTION is the DECL that has been invoked; it is known to be a builtin.
7850    PARAMS is the argument list for the call.  The return value is non-null
7851    when expansion is complete, and null if normal processing should
7852    continue.  */
7853
7854 tree
7855 resolve_overloaded_builtin (location_t loc, tree function,
7856                             vec<tree, va_gc> *params)
7857 {
7858   /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
7859      Those are not valid to call with a pointer to _Bool (or C++ bool)
7860      and so must be rejected.  */
7861   bool fetch_op = true;
7862   bool orig_format = true;
7863   tree new_return = NULL_TREE;
7864
7865   switch (DECL_BUILT_IN_CLASS (function))
7866     {
7867     case BUILT_IN_NORMAL:
7868       break;
7869     case BUILT_IN_MD:
7870       if (targetm.resolve_overloaded_builtin)
7871         return targetm.resolve_overloaded_builtin (loc, function, params);
7872       else
7873         return NULL_TREE;
7874     default:
7875       return NULL_TREE;
7876     }
7877
7878   /* Handle BUILT_IN_NORMAL here.  */
7879   enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
7880   switch (orig_code)
7881     {
7882     case BUILT_IN_SPECULATION_SAFE_VALUE_N:
7883       {
7884         tree new_function, first_param, result;
7885         enum built_in_function fncode
7886           = speculation_safe_value_resolve_call (function, params);
7887
7888         if (fncode == BUILT_IN_NONE)
7889           return error_mark_node;
7890
7891         first_param = (*params)[0];
7892         if (!speculation_safe_value_resolve_params (loc, function, params))
7893           return error_mark_node;
7894
7895         if (targetm.have_speculation_safe_value (true))
7896           {
7897             new_function = builtin_decl_explicit (fncode);
7898             result = build_function_call_vec (loc, vNULL, new_function, params,
7899                                               NULL);
7900
7901             if (result == error_mark_node)
7902               return result;
7903
7904             return speculation_safe_value_resolve_return (first_param, result);
7905           }
7906         else
7907           {
7908             /* This target doesn't have, or doesn't need, active mitigation
7909                against incorrect speculative execution.  Simply return the
7910                first parameter to the builtin.  */
7911             if (!targetm.have_speculation_safe_value (false))
7912               /* The user has invoked __builtin_speculation_safe_value
7913                  even though __HAVE_SPECULATION_SAFE_VALUE is not
7914                  defined: emit a warning.  */
7915               warning_at (input_location, 0,
7916                           "this target does not define a speculation barrier; "
7917                           "your program will still execute correctly, "
7918                           "but incorrect speculation may not be "
7919                           "restricted");
7920
7921             /* If the optional second argument is present, handle any side
7922                effects now.  */
7923             if (params->length () == 2
7924                 && TREE_SIDE_EFFECTS ((*params)[1]))
7925               return build2 (COMPOUND_EXPR, TREE_TYPE (first_param),
7926                              (*params)[1], first_param);
7927
7928             return first_param;
7929           }
7930       }
7931
7932     case BUILT_IN_ATOMIC_EXCHANGE:
7933     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7934     case BUILT_IN_ATOMIC_LOAD:
7935     case BUILT_IN_ATOMIC_STORE:
7936       {
7937         /* Handle these 4 together so that they can fall through to the next
7938            case if the call is transformed to an _N variant.  */
7939         switch (orig_code)
7940           {
7941           case BUILT_IN_ATOMIC_EXCHANGE:
7942             {
7943               if (resolve_overloaded_atomic_exchange (loc, function, params,
7944                                                       &new_return))
7945                 return new_return;
7946               /* Change to the _N variant.  */
7947               orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
7948               break;
7949             }
7950
7951           case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7952             {
7953               if (resolve_overloaded_atomic_compare_exchange (loc, function,
7954                                                               params,
7955                                                               &new_return))
7956                 return new_return;
7957               /* Change to the _N variant.  */
7958               orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
7959               break;
7960             }
7961           case BUILT_IN_ATOMIC_LOAD:
7962             {
7963               if (resolve_overloaded_atomic_load (loc, function, params,
7964                                                   &new_return))
7965                 return new_return;
7966               /* Change to the _N variant.  */
7967               orig_code = BUILT_IN_ATOMIC_LOAD_N;
7968               break;
7969             }
7970           case BUILT_IN_ATOMIC_STORE:
7971             {
7972               if (resolve_overloaded_atomic_store (loc, function, params,
7973                                                    &new_return))
7974                 return new_return;
7975               /* Change to the _N variant.  */
7976               orig_code = BUILT_IN_ATOMIC_STORE_N;
7977               break;
7978             }
7979           default:
7980             gcc_unreachable ();
7981           }
7982       }
7983       /* FALLTHRU */
7984     case BUILT_IN_ATOMIC_EXCHANGE_N:
7985     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
7986     case BUILT_IN_ATOMIC_LOAD_N:
7987     case BUILT_IN_ATOMIC_STORE_N:
7988       fetch_op = false;
7989       /* FALLTHRU */
7990     case BUILT_IN_ATOMIC_ADD_FETCH_N:
7991     case BUILT_IN_ATOMIC_SUB_FETCH_N:
7992     case BUILT_IN_ATOMIC_AND_FETCH_N:
7993     case BUILT_IN_ATOMIC_NAND_FETCH_N:
7994     case BUILT_IN_ATOMIC_XOR_FETCH_N:
7995     case BUILT_IN_ATOMIC_OR_FETCH_N:
7996     case BUILT_IN_ATOMIC_FETCH_ADD_N:
7997     case BUILT_IN_ATOMIC_FETCH_SUB_N:
7998     case BUILT_IN_ATOMIC_FETCH_AND_N:
7999     case BUILT_IN_ATOMIC_FETCH_NAND_N:
8000     case BUILT_IN_ATOMIC_FETCH_XOR_N:
8001     case BUILT_IN_ATOMIC_FETCH_OR_N:
8002       orig_format = false;
8003       /* FALLTHRU */
8004     case BUILT_IN_SYNC_FETCH_AND_ADD_N:
8005     case BUILT_IN_SYNC_FETCH_AND_SUB_N:
8006     case BUILT_IN_SYNC_FETCH_AND_OR_N:
8007     case BUILT_IN_SYNC_FETCH_AND_AND_N:
8008     case BUILT_IN_SYNC_FETCH_AND_XOR_N:
8009     case BUILT_IN_SYNC_FETCH_AND_NAND_N:
8010     case BUILT_IN_SYNC_ADD_AND_FETCH_N:
8011     case BUILT_IN_SYNC_SUB_AND_FETCH_N:
8012     case BUILT_IN_SYNC_OR_AND_FETCH_N:
8013     case BUILT_IN_SYNC_AND_AND_FETCH_N:
8014     case BUILT_IN_SYNC_XOR_AND_FETCH_N:
8015     case BUILT_IN_SYNC_NAND_AND_FETCH_N:
8016     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
8017     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
8018     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
8019     case BUILT_IN_SYNC_LOCK_RELEASE_N:
8020       {
8021         /* The following are not _FETCH_OPs and must be accepted with
8022            pointers to _Bool (or C++ bool).  */
8023         if (fetch_op)
8024           fetch_op =
8025             (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8026              && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
8027              && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
8028              && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
8029
8030         int n = sync_resolve_size (function, params, fetch_op);
8031         tree new_function, first_param, result;
8032         enum built_in_function fncode;
8033
8034         if (n == 0)
8035           return error_mark_node;
8036
8037         fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
8038         new_function = builtin_decl_explicit (fncode);
8039         if (!sync_resolve_params (loc, function, new_function, params,
8040                                   orig_format))
8041           return error_mark_node;
8042
8043         first_param = (*params)[0];
8044         result = build_function_call_vec (loc, vNULL, new_function, params,
8045                                           NULL);
8046         if (result == error_mark_node)
8047           return result;
8048         if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8049             && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
8050             && orig_code != BUILT_IN_ATOMIC_STORE_N
8051             && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
8052           result = sync_resolve_return (first_param, result, orig_format);
8053
8054         if (fetch_op)
8055           /* Prevent -Wunused-value warning.  */
8056           TREE_USED (result) = true;
8057
8058         /* If new_return is set, assign function to that expr and cast the
8059            result to void since the generic interface returned void.  */
8060         if (new_return)
8061           {
8062             /* Cast function result from I{1,2,4,8,16} to the required type.  */
8063             result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
8064             result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
8065                              result);
8066             TREE_SIDE_EFFECTS (result) = 1;
8067             protected_set_expr_location (result, loc);
8068             result = convert (void_type_node, result);
8069           }
8070         return result;
8071       }
8072
8073     default:
8074       return NULL_TREE;
8075     }
8076 }
8077
8078 /* vector_types_compatible_elements_p is used in type checks of vectors
8079    values used as operands of binary operators.  Where it returns true, and
8080    the other checks of the caller succeed (being vector types in he first
8081    place, and matching number of elements), we can just treat the types
8082    as essentially the same.
8083    Contrast with vector_targets_convertible_p, which is used for vector
8084    pointer types,  and vector_types_convertible_p, which will allow
8085    language-specific matches under the control of flag_lax_vector_conversions,
8086    and might still require a conversion.  */
8087 /* True if vector types T1 and T2 can be inputs to the same binary
8088    operator without conversion.
8089    We don't check the overall vector size here because some of our callers
8090    want to give different error messages when the vectors are compatible
8091    except for the element count.  */
8092
8093 bool
8094 vector_types_compatible_elements_p (tree t1, tree t2)
8095 {
8096   bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
8097   t1 = TREE_TYPE (t1);
8098   t2 = TREE_TYPE (t2);
8099
8100   enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
8101
8102   gcc_assert ((INTEGRAL_TYPE_P (t1)
8103                || c1 == REAL_TYPE
8104                || c1 == FIXED_POINT_TYPE)
8105               && (INTEGRAL_TYPE_P (t2)
8106                   || c2 == REAL_TYPE
8107                   || c2 == FIXED_POINT_TYPE));
8108
8109   t1 = c_common_signed_type (t1);
8110   t2 = c_common_signed_type (t2);
8111   /* Equality works here because c_common_signed_type uses
8112      TYPE_MAIN_VARIANT.  */
8113   if (t1 == t2)
8114     return true;
8115   if (opaque && c1 == c2
8116       && (INTEGRAL_TYPE_P (t1) || c1 == REAL_TYPE)
8117       && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
8118     return true;
8119   return false;
8120 }
8121
8122 /* Check for missing format attributes on function pointers.  LTYPE is
8123    the new type or left-hand side type.  RTYPE is the old type or
8124    right-hand side type.  Returns TRUE if LTYPE is missing the desired
8125    attribute.  */
8126
8127 bool
8128 check_missing_format_attribute (tree ltype, tree rtype)
8129 {
8130   tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
8131   tree ra;
8132
8133   for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
8134     if (is_attribute_p ("format", get_attribute_name (ra)))
8135       break;
8136   if (ra)
8137     {
8138       tree la;
8139       for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
8140         if (is_attribute_p ("format", get_attribute_name (la)))
8141           break;
8142       return !la;
8143     }
8144   else
8145     return false;
8146 }
8147
8148 /* Setup a TYPE_DECL node as a typedef representation.
8149
8150    X is a TYPE_DECL for a typedef statement.  Create a brand new
8151    ..._TYPE node (which will be just a variant of the existing
8152    ..._TYPE node with identical properties) and then install X
8153    as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
8154
8155    The whole point here is to end up with a situation where each
8156    and every ..._TYPE node the compiler creates will be uniquely
8157    associated with AT MOST one node representing a typedef name.
8158    This way, even though the compiler substitutes corresponding
8159    ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
8160    early on, later parts of the compiler can always do the reverse
8161    translation and get back the corresponding typedef name.  For
8162    example, given:
8163
8164         typedef struct S MY_TYPE;
8165         MY_TYPE object;
8166
8167    Later parts of the compiler might only know that `object' was of
8168    type `struct S' if it were not for code just below.  With this
8169    code however, later parts of the compiler see something like:
8170
8171         struct S' == struct S
8172         typedef struct S' MY_TYPE;
8173         struct S' object;
8174
8175     And they can then deduce (from the node for type struct S') that
8176     the original object declaration was:
8177
8178                 MY_TYPE object;
8179
8180     Being able to do this is important for proper support of protoize,
8181     and also for generating precise symbolic debugging information
8182     which takes full account of the programmer's (typedef) vocabulary.
8183
8184     Obviously, we don't want to generate a duplicate ..._TYPE node if
8185     the TYPE_DECL node that we are now processing really represents a
8186     standard built-in type.  */
8187
8188 void
8189 set_underlying_type (tree x)
8190 {
8191   if (x == error_mark_node || TREE_TYPE (x) == error_mark_node)
8192     return;
8193   if (DECL_IS_UNDECLARED_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
8194     {
8195       if (TYPE_NAME (TREE_TYPE (x)) == 0)
8196         TYPE_NAME (TREE_TYPE (x)) = x;
8197     }
8198   else if (DECL_ORIGINAL_TYPE (x))
8199     gcc_checking_assert (TYPE_NAME (TREE_TYPE (x)) == x);
8200   else
8201     {
8202       tree tt = TREE_TYPE (x);
8203       DECL_ORIGINAL_TYPE (x) = tt;
8204       tt = build_variant_type_copy (tt);
8205       TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
8206       TYPE_NAME (tt) = x;
8207
8208       /* Mark the type as used only when its type decl is decorated
8209          with attribute unused.  */
8210       if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
8211         TREE_USED (tt) = 1;
8212
8213       TREE_TYPE (x) = tt;
8214     }
8215 }
8216
8217 /* Return true if it is worth exposing the DECL_ORIGINAL_TYPE of TYPE to
8218    the user in diagnostics, false if it would be better to use TYPE itself.
8219    TYPE is known to satisfy typedef_variant_p.  */
8220
8221 bool
8222 user_facing_original_type_p (const_tree type)
8223 {
8224   gcc_assert (typedef_variant_p (type));
8225   tree decl = TYPE_NAME (type);
8226
8227   /* Look through any typedef in "user" code.  */
8228   if (!DECL_IN_SYSTEM_HEADER (decl) && !DECL_IS_UNDECLARED_BUILTIN (decl))
8229     return true;
8230
8231   /* If the original type is also named and is in the user namespace,
8232      assume it too is a user-facing type.  */
8233   tree orig_type = DECL_ORIGINAL_TYPE (decl);
8234   if (tree orig_id = TYPE_IDENTIFIER (orig_type))
8235     if (!name_reserved_for_implementation_p (IDENTIFIER_POINTER (orig_id)))
8236       return true;
8237
8238   switch (TREE_CODE (orig_type))
8239     {
8240     /* Don't look through to an anonymous vector type, since the syntax
8241        we use for them in diagnostics isn't real C or C++ syntax.
8242        And if ORIG_TYPE is named but in the implementation namespace,
8243        TYPE is likely to be more meaningful to the user.  */
8244     case VECTOR_TYPE:
8245       return false;
8246
8247     /* Don't expose anonymous tag types that are presumably meant to be
8248        known by their typedef name.  Also don't expose tags that are in
8249        the implementation namespace, such as:
8250
8251          typedef struct __foo foo;  */
8252     case RECORD_TYPE:
8253     case UNION_TYPE:
8254     case ENUMERAL_TYPE:
8255       return false;
8256
8257     /* Look through to anything else.  */
8258     default:
8259       return true;
8260     }
8261 }
8262
8263 /* Record the types used by the current global variable declaration
8264    being parsed, so that we can decide later to emit their debug info.
8265    Those types are in types_used_by_cur_var_decl, and we are going to
8266    store them in the types_used_by_vars_hash hash table.
8267    DECL is the declaration of the global variable that has been parsed.  */
8268
8269 void
8270 record_types_used_by_current_var_decl (tree decl)
8271 {
8272   gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
8273
8274   while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
8275     {
8276       tree type = types_used_by_cur_var_decl->pop ();
8277       types_used_by_var_decl_insert (type, decl);
8278     }
8279 }
8280
8281 /* The C and C++ parsers both use vectors to hold function arguments.
8282    For efficiency, we keep a cache of unused vectors.  This is the
8283    cache.  */
8284
8285 typedef vec<tree, va_gc> *tree_gc_vec;
8286 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
8287
8288 /* Return a new vector from the cache.  If the cache is empty,
8289    allocate a new vector.  These vectors are GC'ed, so it is OK if the
8290    pointer is not released..  */
8291
8292 vec<tree, va_gc> *
8293 make_tree_vector (void)
8294 {
8295   if (tree_vector_cache && !tree_vector_cache->is_empty ())
8296     return tree_vector_cache->pop ();
8297   else
8298     {
8299       /* Passing 0 to vec::alloc returns NULL, and our callers require
8300          that we always return a non-NULL value.  The vector code uses
8301          4 when growing a NULL vector, so we do too.  */
8302       vec<tree, va_gc> *v;
8303       vec_alloc (v, 4);
8304       return v;
8305     }
8306 }
8307
8308 /* Release a vector of trees back to the cache.  */
8309
8310 void
8311 release_tree_vector (vec<tree, va_gc> *vec)
8312 {
8313   if (vec != NULL)
8314     {
8315       if (vec->allocated () >= 16)
8316         /* Don't cache vecs that have expanded more than once.  On a p64
8317            target, vecs double in alloc size with each power of 2 elements, e.g
8318            at 16 elements the alloc increases from 128 to 256 bytes.  */
8319         vec_free (vec);
8320       else
8321         {
8322           vec->truncate (0);
8323           vec_safe_push (tree_vector_cache, vec);
8324         }
8325     }
8326 }
8327
8328 /* Get a new tree vector holding a single tree.  */
8329
8330 vec<tree, va_gc> *
8331 make_tree_vector_single (tree t)
8332 {
8333   vec<tree, va_gc> *ret = make_tree_vector ();
8334   ret->quick_push (t);
8335   return ret;
8336 }
8337
8338 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain.  */
8339
8340 vec<tree, va_gc> *
8341 make_tree_vector_from_list (tree list)
8342 {
8343   vec<tree, va_gc> *ret = make_tree_vector ();
8344   for (; list; list = TREE_CHAIN (list))
8345     vec_safe_push (ret, TREE_VALUE (list));
8346   return ret;
8347 }
8348
8349 /* Get a new tree vector of the values of a CONSTRUCTOR.  */
8350
8351 vec<tree, va_gc> *
8352 make_tree_vector_from_ctor (tree ctor)
8353 {
8354   vec<tree,va_gc> *ret = make_tree_vector ();
8355   vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
8356   for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
8357     ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
8358   return ret;
8359 }
8360
8361 /* Get a new tree vector which is a copy of an existing one.  */
8362
8363 vec<tree, va_gc> *
8364 make_tree_vector_copy (const vec<tree, va_gc> *orig)
8365 {
8366   vec<tree, va_gc> *ret;
8367   unsigned int ix;
8368   tree t;
8369
8370   ret = make_tree_vector ();
8371   vec_safe_reserve (ret, vec_safe_length (orig));
8372   FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
8373     ret->quick_push (t);
8374   return ret;
8375 }
8376
8377 /* Return true if KEYWORD starts a type specifier.  */
8378
8379 bool
8380 keyword_begins_type_specifier (enum rid keyword)
8381 {
8382   switch (keyword)
8383     {
8384     case RID_AUTO_TYPE:
8385     case RID_INT:
8386     case RID_CHAR:
8387     case RID_FLOAT:
8388     case RID_DOUBLE:
8389     case RID_VOID:
8390     case RID_UNSIGNED:
8391     case RID_LONG:
8392     case RID_SHORT:
8393     case RID_SIGNED:
8394     CASE_RID_FLOATN_NX:
8395     case RID_DFLOAT32:
8396     case RID_DFLOAT64:
8397     case RID_DFLOAT128:
8398     case RID_FRACT:
8399     case RID_ACCUM:
8400     case RID_BOOL:
8401     case RID_WCHAR:
8402     case RID_CHAR8:
8403     case RID_CHAR16:
8404     case RID_CHAR32:
8405     case RID_SAT:
8406     case RID_COMPLEX:
8407     case RID_TYPEOF:
8408     case RID_STRUCT:
8409     case RID_CLASS:
8410     case RID_UNION:
8411     case RID_ENUM:
8412       return true;
8413     default:
8414       if (keyword >= RID_FIRST_INT_N
8415           && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
8416           && int_n_enabled_p[keyword-RID_FIRST_INT_N])
8417         return true;
8418       return false;
8419     }
8420 }
8421
8422 /* Return true if KEYWORD names a type qualifier.  */
8423
8424 bool
8425 keyword_is_type_qualifier (enum rid keyword)
8426 {
8427   switch (keyword)
8428     {
8429     case RID_CONST:
8430     case RID_VOLATILE:
8431     case RID_RESTRICT:
8432     case RID_ATOMIC:
8433       return true;
8434     default:
8435       return false;
8436     }
8437 }
8438
8439 /* Return true if KEYWORD names a storage class specifier.
8440
8441    RID_TYPEDEF is not included in this list despite `typedef' being
8442    listed in C99 6.7.1.1.  6.7.1.3 indicates that `typedef' is listed as
8443    such for syntactic convenience only.  */
8444
8445 bool
8446 keyword_is_storage_class_specifier (enum rid keyword)
8447 {
8448   switch (keyword)
8449     {
8450     case RID_STATIC:
8451     case RID_EXTERN:
8452     case RID_REGISTER:
8453     case RID_AUTO:
8454     case RID_MUTABLE:
8455     case RID_THREAD:
8456       return true;
8457     default:
8458       return false;
8459     }
8460 }
8461
8462 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec].  */
8463
8464 static bool
8465 keyword_is_function_specifier (enum rid keyword)
8466 {
8467   switch (keyword)
8468     {
8469     case RID_INLINE:
8470     case RID_NORETURN:
8471     case RID_VIRTUAL:
8472     case RID_EXPLICIT:
8473       return true;
8474     default:
8475       return false;
8476     }
8477 }
8478
8479 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
8480    declaration-specifier (C99 6.7).  */
8481
8482 bool
8483 keyword_is_decl_specifier (enum rid keyword)
8484 {
8485   if (keyword_is_storage_class_specifier (keyword)
8486       || keyword_is_type_qualifier (keyword)
8487       || keyword_is_function_specifier (keyword))
8488     return true;
8489
8490   switch (keyword)
8491     {
8492     case RID_TYPEDEF:
8493     case RID_FRIEND:
8494     case RID_CONSTEXPR:
8495     case RID_CONSTINIT:
8496       return true;
8497     default:
8498       return false;
8499     }
8500 }
8501
8502 /* Initialize language-specific-bits of tree_contains_struct.  */
8503
8504 void
8505 c_common_init_ts (void)
8506 {
8507   MARK_TS_EXP (SIZEOF_EXPR);
8508   MARK_TS_EXP (PAREN_SIZEOF_EXPR);
8509   MARK_TS_EXP (C_MAYBE_CONST_EXPR);
8510   MARK_TS_EXP (EXCESS_PRECISION_EXPR);
8511   MARK_TS_EXP (BREAK_STMT);
8512   MARK_TS_EXP (CONTINUE_STMT);
8513   MARK_TS_EXP (DO_STMT);
8514   MARK_TS_EXP (FOR_STMT);
8515   MARK_TS_EXP (SWITCH_STMT);
8516   MARK_TS_EXP (WHILE_STMT);
8517 }
8518
8519 /* Build a user-defined numeric literal out of an integer constant type VALUE
8520    with identifier SUFFIX.  */
8521
8522 tree
8523 build_userdef_literal (tree suffix_id, tree value,
8524                        enum overflow_type overflow, tree num_string)
8525 {
8526   tree literal = make_node (USERDEF_LITERAL);
8527   USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
8528   USERDEF_LITERAL_VALUE (literal) = value;
8529   USERDEF_LITERAL_OVERFLOW (literal) = overflow;
8530   USERDEF_LITERAL_NUM_STRING (literal) = num_string;
8531   return literal;
8532 }
8533
8534 /* For vector[index], convert the vector to an array of the underlying type.
8535    Return true if the resulting ARRAY_REF should not be an lvalue.  */
8536
8537 bool
8538 convert_vector_to_array_for_subscript (location_t loc,
8539                                        tree *vecp, tree index)
8540 {
8541   bool ret = false;
8542   if (gnu_vector_type_p (TREE_TYPE (*vecp)))
8543     {
8544       tree type = TREE_TYPE (*vecp);
8545
8546       ret = !lvalue_p (*vecp);
8547
8548       index = fold_for_warn (index);
8549       if (TREE_CODE (index) == INTEGER_CST)
8550         if (!tree_fits_uhwi_p (index)
8551             || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
8552           warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
8553
8554       /* We are building an ARRAY_REF so mark the vector as addressable
8555          to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
8556          for function parameters.  */
8557       c_common_mark_addressable_vec (*vecp);
8558
8559       *vecp = build1 (VIEW_CONVERT_EXPR,
8560                       build_array_type_nelts (TREE_TYPE (type),
8561                                               TYPE_VECTOR_SUBPARTS (type)),
8562                       *vecp);
8563     }
8564   return ret;
8565 }
8566
8567 /* Determine which of the operands, if any, is a scalar that needs to be
8568    converted to a vector, for the range of operations.  */
8569 enum stv_conv
8570 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
8571                   bool complain)
8572 {
8573   tree type0 = TREE_TYPE (op0);
8574   tree type1 = TREE_TYPE (op1);
8575   bool integer_only_op = false;
8576   enum stv_conv ret = stv_firstarg;
8577
8578   gcc_assert (gnu_vector_type_p (type0) || gnu_vector_type_p (type1));
8579   switch (code)
8580     {
8581       /* Most GENERIC binary expressions require homogeneous arguments.
8582          LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
8583          argument that is a vector and a second one that is a scalar, so
8584          we never return stv_secondarg for them.  */
8585       case RSHIFT_EXPR:
8586       case LSHIFT_EXPR:
8587         if (TREE_CODE (type0) == INTEGER_TYPE
8588             && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8589           {
8590             if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8591                                      NULL_TREE, false))
8592               {
8593                 if (complain)
8594                   error_at (loc, "conversion of scalar %qT to vector %qT "
8595                             "involves truncation", type0, type1);
8596                 return stv_error;
8597               }
8598             else
8599               return stv_firstarg;
8600           }
8601         break;
8602
8603       case BIT_IOR_EXPR:
8604       case BIT_XOR_EXPR:
8605       case BIT_AND_EXPR:
8606         integer_only_op = true;
8607         /* fall through */
8608
8609       case VEC_COND_EXPR:
8610
8611       case PLUS_EXPR:
8612       case MINUS_EXPR:
8613       case MULT_EXPR:
8614       case TRUNC_DIV_EXPR:
8615       case CEIL_DIV_EXPR:
8616       case FLOOR_DIV_EXPR:
8617       case ROUND_DIV_EXPR:
8618       case EXACT_DIV_EXPR:
8619       case TRUNC_MOD_EXPR:
8620       case FLOOR_MOD_EXPR:
8621       case RDIV_EXPR:
8622       case EQ_EXPR:
8623       case NE_EXPR:
8624       case LE_EXPR:
8625       case GE_EXPR:
8626       case LT_EXPR:
8627       case GT_EXPR:
8628       /* What about UNLT_EXPR?  */
8629         if (gnu_vector_type_p (type0))
8630           {
8631             ret = stv_secondarg;
8632             std::swap (type0, type1);
8633             std::swap (op0, op1);
8634           }
8635
8636         if (TREE_CODE (type0) == INTEGER_TYPE
8637             && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8638           {
8639             if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8640                                      NULL_TREE, false))
8641               {
8642                 if (complain)
8643                   error_at (loc, "conversion of scalar %qT to vector %qT "
8644                             "involves truncation", type0, type1);
8645                 return stv_error;
8646               }
8647             return ret;
8648           }
8649         else if (!integer_only_op
8650                     /* Allow integer --> real conversion if safe.  */
8651                  && (TREE_CODE (type0) == REAL_TYPE
8652                      || TREE_CODE (type0) == INTEGER_TYPE)
8653                  && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
8654           {
8655             if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8656                                      NULL_TREE, false))
8657               {
8658                 if (complain)
8659                   error_at (loc, "conversion of scalar %qT to vector %qT "
8660                             "involves truncation", type0, type1);
8661                 return stv_error;
8662               }
8663             return ret;
8664           }
8665       default:
8666         break;
8667     }
8668
8669   return stv_nothing;
8670 }
8671
8672 /* Return the alignment of std::max_align_t.
8673
8674    [support.types.layout] The type max_align_t is a POD type whose alignment
8675    requirement is at least as great as that of every scalar type, and whose
8676    alignment requirement is supported in every context.  */
8677
8678 unsigned
8679 max_align_t_align ()
8680 {
8681   unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
8682                                 TYPE_ALIGN (long_double_type_node));
8683   if (float128_type_node != NULL_TREE)
8684     max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
8685   return max_align;
8686 }
8687
8688 /* Return true iff ALIGN is an integral constant that is a fundamental
8689    alignment, as defined by [basic.align] in the c++-11
8690    specifications.
8691
8692    That is:
8693
8694        [A fundamental alignment is represented by an alignment less than or
8695         equal to the greatest alignment supported by the implementation
8696         in all contexts, which is equal to alignof(max_align_t)].  */
8697
8698 bool
8699 cxx_fundamental_alignment_p (unsigned align)
8700 {
8701   return (align <= max_align_t_align ());
8702 }
8703
8704 /* Return true if T is a pointer to a zero-sized aggregate.  */
8705
8706 bool
8707 pointer_to_zero_sized_aggr_p (tree t)
8708 {
8709   if (!POINTER_TYPE_P (t))
8710     return false;
8711   t = TREE_TYPE (t);
8712   return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
8713 }
8714
8715 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
8716    with no library fallback or for an ADDR_EXPR whose operand is such type
8717    issues an error pointing to the location LOC.
8718    Returns true when the expression has been diagnosed and false
8719    otherwise.  */
8720
8721 bool
8722 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
8723 {
8724   if (TREE_CODE (expr) == ADDR_EXPR)
8725     expr = TREE_OPERAND (expr, 0);
8726
8727   STRIP_ANY_LOCATION_WRAPPER (expr);
8728
8729   if (TREE_TYPE (expr)
8730       && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
8731       && TREE_CODE (expr) == FUNCTION_DECL
8732       /* The intersection of DECL_BUILT_IN and DECL_IS_UNDECLARED_BUILTIN avoids
8733          false positives for user-declared built-ins such as abs or
8734          strlen, and for C++ operators new and delete.
8735          The c_decl_implicit() test avoids false positives for implicitly
8736          declared built-ins with library fallbacks (such as abs).  */
8737       && fndecl_built_in_p (expr)
8738       && DECL_IS_UNDECLARED_BUILTIN (expr)
8739       && !c_decl_implicit (expr)
8740       && !DECL_ASSEMBLER_NAME_SET_P (expr))
8741     {
8742       if (loc == UNKNOWN_LOCATION)
8743         loc = EXPR_LOC_OR_LOC (expr, input_location);
8744
8745       /* Reject arguments that are built-in functions with
8746          no library fallback.  */
8747       error_at (loc, "built-in function %qE must be directly called", expr);
8748
8749       return true;
8750     }
8751
8752   return false;
8753 }
8754
8755 /* Issue an ERROR for an invalid SIZE of array NAME which is null
8756    for unnamed arrays.  */
8757
8758 void
8759 invalid_array_size_error (location_t loc, cst_size_error error,
8760                           const_tree size, const_tree name)
8761 {
8762   tree maxsize = max_object_size ();
8763   switch (error)
8764     {
8765     case cst_size_not_constant:
8766       if (name)
8767         error_at (loc, "size of array %qE is not a constant expression",
8768                   name);
8769       else
8770         error_at (loc, "size of array is not a constant expression");
8771       break;
8772     case cst_size_negative:
8773       if (name)
8774         error_at (loc, "size %qE of array %qE is negative",
8775                   size, name);
8776       else
8777         error_at (loc, "size %qE of array is negative",
8778                   size);
8779       break;
8780     case cst_size_too_big:
8781       if (name)
8782         error_at (loc, "size %qE of array %qE exceeds maximum "
8783                   "object size %qE", size, name, maxsize);
8784       else
8785         error_at (loc, "size %qE of array exceeds maximum "
8786                   "object size %qE", size, maxsize);
8787       break;
8788     case cst_size_overflow:
8789       if (name)
8790         error_at (loc, "size of array %qE exceeds maximum "
8791                   "object size %qE", name, maxsize);
8792       else
8793         error_at (loc, "size of array exceeds maximum "
8794                   "object size %qE", maxsize);
8795       break;
8796     default:
8797       gcc_unreachable ();
8798     }
8799 }
8800
8801 /* Check if array size calculations overflow or if the array covers more
8802    than half of the address space.  Return true if the size of the array
8803    is valid, false otherwise.  T is either the type of the array or its
8804    size, and NAME is the name of the array, or null for unnamed arrays.  */
8805
8806 bool
8807 valid_array_size_p (location_t loc, const_tree t, tree name, bool complain)
8808 {
8809   if (t == error_mark_node)
8810     return true;
8811
8812   const_tree size;
8813   if (TYPE_P (t))
8814     {
8815       if (!COMPLETE_TYPE_P (t))
8816         return true;
8817       size = TYPE_SIZE_UNIT (t);
8818     }
8819   else
8820     size = t;
8821
8822   if (TREE_CODE (size) != INTEGER_CST)
8823     return true;
8824
8825   cst_size_error error;
8826   if (valid_constant_size_p (size, &error))
8827     return true;
8828
8829   if (!complain)
8830     return false;
8831
8832   if (TREE_CODE (TREE_TYPE (size)) == ENUMERAL_TYPE)
8833     /* Show the value of the enumerator rather than its name.  */
8834     size = convert (ssizetype, const_cast<tree> (size));
8835
8836   invalid_array_size_error (loc, error, size, name);
8837   return false;
8838 }
8839
8840 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
8841    timestamp to replace embedded current dates to get reproducible
8842    results.  Returns -1 if SOURCE_DATE_EPOCH is not defined.  */
8843
8844 time_t
8845 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
8846 {
8847   char *source_date_epoch;
8848   int64_t epoch;
8849   char *endptr;
8850
8851   source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
8852   if (!source_date_epoch)
8853     return (time_t) -1;
8854
8855   errno = 0;
8856 #if defined(INT64_T_IS_LONG)
8857   epoch = strtol (source_date_epoch, &endptr, 10);
8858 #else
8859   epoch = strtoll (source_date_epoch, &endptr, 10);
8860 #endif
8861   if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
8862       || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
8863     {
8864       error_at (input_location, "environment variable %qs must "
8865                 "expand to a non-negative integer less than or equal to %wd",
8866                 "SOURCE_DATE_EPOCH", MAX_SOURCE_DATE_EPOCH);
8867       return (time_t) -1;
8868     }
8869
8870   return (time_t) epoch;
8871 }
8872
8873 /* Callback for libcpp for offering spelling suggestions for misspelled
8874    directives.  GOAL is an unrecognized string; CANDIDATES is a
8875    NULL-terminated array of candidate strings.  Return the closest
8876    match to GOAL within CANDIDATES, or NULL if none are good
8877    suggestions.  */
8878
8879 const char *
8880 cb_get_suggestion (cpp_reader *, const char *goal,
8881                    const char *const *candidates)
8882 {
8883   best_match<const char *, const char *> bm (goal);
8884   while (*candidates)
8885     bm.consider (*candidates++);
8886   return bm.get_best_meaningful_candidate ();
8887 }
8888
8889 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
8890    modes X, Y.  This isn't just  >, as the FLT_EVAL_METHOD values added
8891    by C TS 18661-3 for interchange  types that are computed in their
8892    native precision are larger than the C11 values for evaluating in the
8893    precision of float/double/long double.  If either mode is
8894    FLT_EVAL_METHOD_UNPREDICTABLE, return that.  */
8895
8896 enum flt_eval_method
8897 excess_precision_mode_join (enum flt_eval_method x,
8898                             enum flt_eval_method y)
8899 {
8900   if (x == FLT_EVAL_METHOD_UNPREDICTABLE
8901       || y == FLT_EVAL_METHOD_UNPREDICTABLE)
8902     return FLT_EVAL_METHOD_UNPREDICTABLE;
8903
8904   /* GCC only supports one interchange type right now, _Float16.  If
8905      we're evaluating _Float16 in 16-bit precision, then flt_eval_method
8906      will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16.  */
8907   if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
8908     return y;
8909   if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
8910     return x;
8911
8912   /* Other values for flt_eval_method are directly comparable, and we want
8913      the maximum.  */
8914   return MAX (x, y);
8915 }
8916
8917 /* Return the value that should be set for FLT_EVAL_METHOD in the
8918    context of ISO/IEC TS 18861-3.
8919
8920    This relates to the effective excess precision seen by the user,
8921    which is the join point of the precision the target requests for
8922    -fexcess-precision={standard,fast,16} and the implicit excess precision
8923    the target uses.  */
8924
8925 static enum flt_eval_method
8926 c_ts18661_flt_eval_method (void)
8927 {
8928   enum flt_eval_method implicit
8929     = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
8930
8931   enum excess_precision_type flag_type
8932     = (flag_excess_precision == EXCESS_PRECISION_STANDARD
8933        ? EXCESS_PRECISION_TYPE_STANDARD
8934        : (flag_excess_precision == EXCESS_PRECISION_FLOAT16
8935           ? EXCESS_PRECISION_TYPE_FLOAT16
8936           : EXCESS_PRECISION_TYPE_FAST));
8937
8938   enum flt_eval_method requested
8939     = targetm.c.excess_precision (flag_type);
8940
8941   return excess_precision_mode_join (implicit, requested);
8942 }
8943
8944 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
8945    those that were permitted by C11.  That is to say, eliminates
8946    FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16.  */
8947
8948 static enum flt_eval_method
8949 c_c11_flt_eval_method (void)
8950 {
8951   return excess_precision_mode_join (c_ts18661_flt_eval_method (),
8952                                      FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
8953 }
8954
8955 /* Return the value that should be set for FLT_EVAL_METHOD.
8956    MAYBE_C11_ONLY_P is TRUE if we should check
8957    FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
8958    values we can return to those from C99/C11, and FALSE otherwise.
8959    See the comments on c_ts18661_flt_eval_method for what value we choose
8960    to set here.  */
8961
8962 int
8963 c_flt_eval_method (bool maybe_c11_only_p)
8964 {
8965   if (maybe_c11_only_p
8966       && flag_permitted_flt_eval_methods
8967           == PERMITTED_FLT_EVAL_METHODS_C11)
8968     return c_c11_flt_eval_method ();
8969   else
8970     return c_ts18661_flt_eval_method ();
8971 }
8972
8973 /* An enum for get_missing_token_insertion_kind for describing the best
8974    place to insert a missing token, if there is one.  */
8975
8976 enum missing_token_insertion_kind
8977 {
8978   MTIK_IMPOSSIBLE,
8979   MTIK_INSERT_BEFORE_NEXT,
8980   MTIK_INSERT_AFTER_PREV
8981 };
8982
8983 /* Given a missing token of TYPE, determine if it is reasonable to
8984    emit a fix-it hint suggesting the insertion of the token, and,
8985    if so, where the token should be inserted relative to other tokens.
8986
8987    It only makes sense to do this for values of TYPE that are symbols.
8988
8989    Some symbols should go before the next token, e.g. in:
8990      if flag)
8991    we want to insert the missing '(' immediately before "flag",
8992    giving:
8993      if (flag)
8994    rather than:
8995      if( flag)
8996    These use MTIK_INSERT_BEFORE_NEXT.
8997
8998    Other symbols should go after the previous token, e.g. in:
8999      if (flag
9000        do_something ();
9001    we want to insert the missing ')' immediately after the "flag",
9002    giving:
9003      if (flag)
9004        do_something ();
9005    rather than:
9006      if (flag
9007        )do_something ();
9008    These use MTIK_INSERT_AFTER_PREV.  */
9009
9010 static enum missing_token_insertion_kind
9011 get_missing_token_insertion_kind (enum cpp_ttype type)
9012 {
9013   switch (type)
9014     {
9015       /* Insert missing "opening" brackets immediately
9016          before the next token.  */
9017     case CPP_OPEN_SQUARE:
9018     case CPP_OPEN_PAREN:
9019       return MTIK_INSERT_BEFORE_NEXT;
9020
9021       /* Insert other missing symbols immediately after
9022          the previous token.  */
9023     case CPP_CLOSE_PAREN:
9024     case CPP_CLOSE_SQUARE:
9025     case CPP_SEMICOLON:
9026     case CPP_COMMA:
9027     case CPP_COLON:
9028       return MTIK_INSERT_AFTER_PREV;
9029
9030       /* Other kinds of token don't get fix-it hints.  */
9031     default:
9032       return MTIK_IMPOSSIBLE;
9033     }
9034 }
9035
9036 /* Given RICHLOC, a location for a diagnostic describing a missing token
9037    of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
9038    insertion of the token.
9039
9040    The location of the attempted fix-it hint depends on TOKEN_TYPE:
9041    it will either be:
9042      (a) immediately after PREV_TOKEN_LOC, or
9043
9044      (b) immediately before the primary location within RICHLOC (taken to
9045          be that of the token following where the token was expected).
9046
9047    If we manage to add a fix-it hint, then the location of the
9048    fix-it hint is likely to be more useful as the primary location
9049    of the diagnostic than that of the following token, so we swap
9050    these locations.
9051
9052    For example, given this bogus code:
9053        123456789012345678901234567890
9054    1 | int missing_semicolon (void)
9055    2 | {
9056    3 |   return 42
9057    4 | }
9058
9059    we will emit:
9060
9061      "expected ';' before '}'"
9062
9063    RICHLOC's primary location is at the closing brace, so before "swapping"
9064    we would emit the error at line 4 column 1:
9065
9066        123456789012345678901234567890
9067    3 |   return 42  |< fix-it hint emitted for this line
9068      |            ; |
9069    4 | }            |< "expected ';' before '}'" emitted at this line
9070      | ^            |
9071
9072    It's more useful for the location of the diagnostic to be at the
9073    fix-it hint, so we swap the locations, so the primary location
9074    is at the fix-it hint, with the old primary location inserted
9075    as a secondary location, giving this, with the error at line 3
9076    column 12:
9077
9078        123456789012345678901234567890
9079    3 |   return 42   |< "expected ';' before '}'" emitted at this line,
9080      |            ^  |   with fix-it hint
9081    4 |            ;  |
9082      | }             |< secondary range emitted here
9083      | ~             |.  */
9084
9085 void
9086 maybe_suggest_missing_token_insertion (rich_location *richloc,
9087                                        enum cpp_ttype token_type,
9088                                        location_t prev_token_loc)
9089 {
9090   gcc_assert (richloc);
9091
9092   enum missing_token_insertion_kind mtik
9093     = get_missing_token_insertion_kind (token_type);
9094
9095   switch (mtik)
9096     {
9097     default:
9098       gcc_unreachable ();
9099       break;
9100
9101     case MTIK_IMPOSSIBLE:
9102       return;
9103
9104     case MTIK_INSERT_BEFORE_NEXT:
9105       /* Attempt to add the fix-it hint before the primary location
9106          of RICHLOC.  */
9107       richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
9108       break;
9109
9110     case MTIK_INSERT_AFTER_PREV:
9111       /* Attempt to add the fix-it hint after PREV_TOKEN_LOC.  */
9112       richloc->add_fixit_insert_after (prev_token_loc,
9113                                        cpp_type2name (token_type, 0));
9114       break;
9115     }
9116
9117   /* If we were successful, use the fix-it hint's location as the
9118      primary location within RICHLOC, adding the old primary location
9119      back as a secondary location.  */
9120   if (!richloc->seen_impossible_fixit_p ())
9121     {
9122       fixit_hint *hint = richloc->get_last_fixit_hint ();
9123       location_t hint_loc = hint->get_start_loc ();
9124       location_t old_loc = richloc->get_loc ();
9125
9126       richloc->set_range (0, hint_loc, SHOW_RANGE_WITH_CARET);
9127       richloc->add_range (old_loc);
9128     }
9129 }
9130
9131 #if CHECKING_P
9132
9133 namespace selftest {
9134
9135 /* Verify that fold_for_warn on error_mark_node is safe.  */
9136
9137 static void
9138 test_fold_for_warn ()
9139 {
9140   ASSERT_EQ (error_mark_node, fold_for_warn (error_mark_node));
9141 }
9142
9143 /* Run all of the selftests within this file.  */
9144
9145 static void
9146 c_common_cc_tests ()
9147 {
9148   test_fold_for_warn ();
9149 }
9150
9151 /* Run all of the tests within c-family.  */
9152
9153 void
9154 c_family_tests (void)
9155 {
9156   c_common_cc_tests ();
9157   c_format_cc_tests ();
9158   c_indentation_cc_tests ();
9159   c_pretty_print_cc_tests ();
9160   c_spellcheck_cc_tests ();
9161   c_diagnostic_cc_tests ();
9162   c_opt_problem_cc_tests ();
9163 }
9164
9165 } // namespace selftest
9166
9167 #endif /* #if CHECKING_P */
9168
9169 /* Attempt to locate a suitable location within FILE for a
9170    #include directive to be inserted before.  
9171    LOC is the location of the relevant diagnostic.
9172
9173    Attempt to return the location within FILE immediately
9174    after the last #include within that file, or the start of
9175    that file if it has no #include directives.
9176
9177    Return UNKNOWN_LOCATION if no suitable location is found,
9178    or if an error occurs.  */
9179
9180 static location_t
9181 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
9182 {
9183   /* Locate the last ordinary map within FILE that ended with a #include.  */
9184   const line_map_ordinary *last_include_ord_map = NULL;
9185
9186   /* ...and the next ordinary map within FILE after that one.  */
9187   const line_map_ordinary *last_ord_map_after_include = NULL;
9188
9189   /* ...and the first ordinary map within FILE.  */
9190   const line_map_ordinary *first_ord_map_in_file = NULL;
9191
9192   /*  Get ordinary map containing LOC (or its expansion).  */
9193   const line_map_ordinary *ord_map_for_loc = NULL;
9194   linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
9195                             &ord_map_for_loc);
9196   gcc_assert (ord_map_for_loc);
9197
9198   for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
9199     {
9200       const line_map_ordinary *ord_map
9201         = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
9202
9203       if (const line_map_ordinary *from
9204           = linemap_included_from_linemap (line_table, ord_map))
9205         /* We cannot use pointer equality, because with preprocessed
9206            input all filename strings are unique.  */
9207         if (0 == strcmp (from->to_file, file))
9208           {
9209             last_include_ord_map = from;
9210             last_ord_map_after_include = NULL;
9211           }
9212
9213       /* Likewise, use strcmp, and reject any line-zero introductory
9214          map.  */
9215       if (ord_map->to_line && 0 == strcmp (ord_map->to_file, file))
9216         {
9217           if (!first_ord_map_in_file)
9218             first_ord_map_in_file = ord_map;
9219           if (last_include_ord_map && !last_ord_map_after_include)
9220             last_ord_map_after_include = ord_map;
9221         }
9222
9223       /* Stop searching when reaching the ord_map containing LOC,
9224          as it makes no sense to provide fix-it hints that appear
9225          after the diagnostic in question.  */
9226       if (ord_map == ord_map_for_loc)
9227         break;
9228     }
9229
9230   /* Determine where to insert the #include.  */
9231   const line_map_ordinary *ord_map_for_insertion;
9232
9233   /* We want the next ordmap in the file after the last one that's a
9234      #include, but failing that, the start of the file.  */
9235   if (last_ord_map_after_include)
9236     ord_map_for_insertion = last_ord_map_after_include;
9237   else
9238     ord_map_for_insertion = first_ord_map_in_file;
9239
9240   if (!ord_map_for_insertion)
9241     return UNKNOWN_LOCATION;
9242
9243   /* The "start_location" is column 0, meaning "the whole line".
9244      rich_location and edit_context can't cope with this, so use
9245      column 1 instead.  */
9246   location_t col_0 = ord_map_for_insertion->start_location;
9247   return linemap_position_for_loc_and_offset (line_table, col_0, 1);
9248 }
9249
9250 /* A map from filenames to sets of headers added to them, for
9251    ensuring idempotency within maybe_add_include_fixit.  */
9252
9253 /* The values within the map.  We need string comparison as there's
9254    no guarantee that two different diagnostics that are recommending
9255    adding e.g. "<stdio.h>" are using the same buffer.  */
9256
9257 typedef hash_set <const char *, false, nofree_string_hash> per_file_includes_t;
9258
9259 /* The map itself.  We don't need string comparison for the filename keys,
9260    as they come from libcpp.  */
9261
9262 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
9263 static added_includes_t *added_includes;
9264
9265 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
9266    in a suitable location within the file of RICHLOC's primary
9267    location.
9268
9269    This function is idempotent: a header will be added at most once to
9270    any given file.
9271
9272    If OVERRIDE_LOCATION is true, then if a fix-it is added and will be
9273    printed, then RICHLOC's primary location will be replaced by that of
9274    the fix-it hint (for use by "inform" notes where the location of the
9275    issue has already been reported).  */
9276
9277 void
9278 maybe_add_include_fixit (rich_location *richloc, const char *header,
9279                          bool override_location)
9280 {
9281   location_t loc = richloc->get_loc ();
9282   const char *file = LOCATION_FILE (loc);
9283   if (!file)
9284     return;
9285
9286   /* Idempotency: don't add the same header more than once to a given file.  */
9287   if (!added_includes)
9288     added_includes = new added_includes_t ();
9289   per_file_includes_t *&set = added_includes->get_or_insert (file);
9290   if (set)
9291     if (set->contains (header))
9292       /* ...then we've already added HEADER to that file.  */
9293       return;
9294   if (!set)
9295     set = new per_file_includes_t ();
9296   set->add (header);
9297
9298   /* Attempt to locate a suitable place for the new directive.  */
9299   location_t include_insert_loc
9300     = try_to_locate_new_include_insertion_point (file, loc);
9301   if (include_insert_loc == UNKNOWN_LOCATION)
9302     return;
9303
9304   char *text = xasprintf ("#include %s\n", header);
9305   richloc->add_fixit_insert_before (include_insert_loc, text);
9306   free (text);
9307
9308   if (override_location && global_dc->show_caret)
9309     {
9310       /* Replace the primary location with that of the insertion point for the
9311          fix-it hint.
9312
9313          We use SHOW_LINES_WITHOUT_RANGE so that we don't meaningless print a
9314          caret for the insertion point (or colorize it).
9315
9316          Hence we print e.g.:
9317
9318          ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9319           73 | # include <debug/vector>
9320          +++ |+#include <vector>
9321           74 | #endif
9322
9323          rather than:
9324
9325          ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9326           73 | # include <debug/vector>
9327          +++ |+#include <vector>
9328           74 | #endif
9329              | ^
9330
9331          avoiding the caret on the first column of line 74.  */
9332       richloc->set_range (0, include_insert_loc, SHOW_LINES_WITHOUT_RANGE);
9333     }
9334 }
9335
9336 /* Attempt to convert a braced array initializer list CTOR for array
9337    TYPE into a STRING_CST for convenience and efficiency.  Return
9338    the converted string on success or the original ctor on failure.  */
9339
9340 static tree
9341 braced_list_to_string (tree type, tree ctor, bool member)
9342 {
9343   /* Ignore non-members with unknown size like arrays with unspecified
9344      bound.  */
9345   tree typesize = TYPE_SIZE_UNIT (type);
9346   if (!member && !tree_fits_uhwi_p (typesize))
9347     return ctor;
9348
9349   /* If the target char size differs from the host char size, we'd risk
9350      loosing data and getting object sizes wrong by converting to
9351      host chars.  */
9352   if (TYPE_PRECISION (char_type_node) != CHAR_BIT)
9353     return ctor;
9354
9355   /* STRING_CST doesn't support wide characters.  */
9356   gcc_checking_assert (TYPE_PRECISION (TREE_TYPE (type)) == CHAR_BIT);
9357
9358   /* If the array has an explicit bound, use it to constrain the size
9359      of the string.  If it doesn't, be sure to create a string that's
9360      as long as implied by the index of the last zero specified via
9361      a designator, as in:
9362        const char a[] = { [7] = 0 };  */
9363   unsigned HOST_WIDE_INT maxelts;
9364   if (typesize)
9365     {
9366       maxelts = tree_to_uhwi (typesize);
9367       maxelts /= tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type)));
9368     }
9369   else
9370     maxelts = HOST_WIDE_INT_M1U;
9371
9372   /* Avoid converting initializers for zero-length arrays (but do
9373      create them for flexible array members).  */
9374   if (!maxelts)
9375     return ctor;
9376
9377   unsigned HOST_WIDE_INT nelts = CONSTRUCTOR_NELTS (ctor);
9378
9379   auto_vec<char> str;
9380   str.reserve (nelts + 1);
9381
9382   unsigned HOST_WIDE_INT i;
9383   tree index, value;
9384
9385   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, index, value)
9386     {
9387       unsigned HOST_WIDE_INT idx = i;
9388       if (index)
9389         {
9390           if (!tree_fits_uhwi_p (index))
9391             return ctor;
9392           idx = tree_to_uhwi (index);
9393         }
9394
9395       /* auto_vec is limited to UINT_MAX elements.  */
9396       if (idx > UINT_MAX)
9397         return ctor;
9398
9399      /* Avoid non-constant initializers.  */
9400      if (!tree_fits_shwi_p (value))
9401         return ctor;
9402
9403       /* Skip over embedded nuls except the last one (initializer
9404          elements are in ascending order of indices).  */
9405       HOST_WIDE_INT val = tree_to_shwi (value);
9406       if (!val && i + 1 < nelts)
9407         continue;
9408
9409       if (idx < str.length())
9410         return ctor;
9411
9412       /* Bail if the CTOR has a block of more than 256 embedded nuls
9413          due to implicitly initialized elements.  */
9414       unsigned nchars = (idx - str.length ()) + 1;
9415       if (nchars > 256)
9416         return ctor;
9417
9418       if (nchars > 1)
9419         {
9420           str.reserve (idx);
9421           str.quick_grow_cleared (idx);
9422         }
9423
9424       if (idx >= maxelts)
9425         return ctor;
9426
9427       str.safe_insert (idx, val);
9428     }
9429
9430   /* Append a nul string termination.  */
9431   if (maxelts != HOST_WIDE_INT_M1U && str.length () < maxelts)
9432     str.safe_push (0);
9433
9434   /* Build a STRING_CST with the same type as the array.  */
9435   tree res = build_string (str.length (), str.begin ());
9436   TREE_TYPE (res) = type;
9437   return res;
9438 }
9439
9440 /* Implementation of the two-argument braced_lists_to_string withe
9441    the same arguments plus MEMBER which is set for struct members
9442    to allow initializers for flexible member arrays.  */
9443
9444 static tree
9445 braced_lists_to_strings (tree type, tree ctor, bool member)
9446 {
9447   if (TREE_CODE (ctor) != CONSTRUCTOR)
9448     return ctor;
9449
9450   tree_code code = TREE_CODE (type);
9451
9452   tree ttp;
9453   if (code == ARRAY_TYPE)
9454     ttp = TREE_TYPE (type);
9455   else if (code == RECORD_TYPE)
9456     {
9457       ttp = TREE_TYPE (ctor);
9458       if (TREE_CODE (ttp) == ARRAY_TYPE)
9459         {
9460           type = ttp;
9461           ttp = TREE_TYPE (ttp);
9462         }
9463     }
9464   else
9465     return ctor;
9466
9467   if ((TREE_CODE (ttp) == ARRAY_TYPE || TREE_CODE (ttp) == INTEGER_TYPE)
9468       && TYPE_STRING_FLAG (ttp))
9469     return braced_list_to_string (type, ctor, member);
9470
9471   code = TREE_CODE (ttp);
9472   if (code == ARRAY_TYPE || RECORD_OR_UNION_TYPE_P (ttp))
9473     {
9474       bool rec = RECORD_OR_UNION_TYPE_P (ttp);
9475
9476       /* Handle array of arrays or struct member initializers.  */
9477       tree val;
9478       unsigned HOST_WIDE_INT idx;
9479       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, val)
9480         {
9481           val = braced_lists_to_strings (ttp, val, rec);
9482           CONSTRUCTOR_ELT (ctor, idx)->value = val;
9483         }
9484     }
9485
9486   return ctor;
9487 }
9488
9489 /* Attempt to convert a CTOR containing braced array initializer lists
9490    for array TYPE into one containing STRING_CSTs, for convenience and
9491    efficiency.  Recurse for arrays of arrays and member initializers.
9492    Return the converted CTOR or STRING_CST on success or the original
9493    CTOR otherwise.  */
9494
9495 tree
9496 braced_lists_to_strings (tree type, tree ctor)
9497 {
9498   return braced_lists_to_strings (type, ctor, false);
9499 }
9500
9501
9502 /* Emit debug for functions before finalizing early debug.  */
9503
9504 void
9505 c_common_finalize_early_debug (void)
9506 {
9507   /* Emit early debug for reachable functions, and by consequence,
9508      locally scoped symbols.  Also emit debug for extern declared
9509      functions that are still reachable at this point.  */
9510   struct cgraph_node *cnode;
9511   FOR_EACH_FUNCTION (cnode)
9512     if (!cnode->alias && !cnode->thunk
9513         && (cnode->has_gimple_body_p ()
9514             || !DECL_IS_UNDECLARED_BUILTIN (cnode->decl)))
9515       (*debug_hooks->early_global_decl) (cnode->decl);
9516 }
9517
9518 #include "gt-c-family-c-common.h"