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