* doc/generic.texi (ANNOTATE_EXPR): Document 3rd operand.
[official-gcc.git] / gcc / c-family / c-common.c
blob9970e611c7c05d12fef69b4121d185328583b50f
1 /* Subroutines shared by all languages that are variants of C.
2 Copyright (C) 1992-2017 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #define GCC_C_COMMON_C
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"
52 cpp_reader *parse_in; /* Declared in c-pragma.h. */
54 /* Mode used to build pointers (VOIDmode means ptr_mode). */
56 machine_mode c_default_pointer_mode = VOIDmode;
58 /* The following symbols are subsumed in the c_global_trees array, and
59 listed here individually for documentation purposes.
61 INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
63 tree short_integer_type_node;
64 tree long_integer_type_node;
65 tree long_long_integer_type_node;
67 tree short_unsigned_type_node;
68 tree long_unsigned_type_node;
69 tree long_long_unsigned_type_node;
71 tree truthvalue_type_node;
72 tree truthvalue_false_node;
73 tree truthvalue_true_node;
75 tree ptrdiff_type_node;
77 tree unsigned_char_type_node;
78 tree signed_char_type_node;
79 tree wchar_type_node;
81 tree char16_type_node;
82 tree char32_type_node;
84 tree float_type_node;
85 tree double_type_node;
86 tree long_double_type_node;
88 tree complex_integer_type_node;
89 tree complex_float_type_node;
90 tree complex_double_type_node;
91 tree complex_long_double_type_node;
93 tree dfloat32_type_node;
94 tree dfloat64_type_node;
95 tree_dfloat128_type_node;
97 tree intQI_type_node;
98 tree intHI_type_node;
99 tree intSI_type_node;
100 tree intDI_type_node;
101 tree intTI_type_node;
103 tree unsigned_intQI_type_node;
104 tree unsigned_intHI_type_node;
105 tree unsigned_intSI_type_node;
106 tree unsigned_intDI_type_node;
107 tree unsigned_intTI_type_node;
109 tree widest_integer_literal_type_node;
110 tree widest_unsigned_literal_type_node;
112 Nodes for types `void *' and `const void *'.
114 tree ptr_type_node, const_ptr_type_node;
116 Nodes for types `char *' and `const char *'.
118 tree string_type_node, const_string_type_node;
120 Type `char[SOMENUMBER]'.
121 Used when an array of char is needed and the size is irrelevant.
123 tree char_array_type_node;
125 Type `wchar_t[SOMENUMBER]' or something like it.
126 Used when a wide string literal is created.
128 tree wchar_array_type_node;
130 Type `char16_t[SOMENUMBER]' or something like it.
131 Used when a UTF-16 string literal is created.
133 tree char16_array_type_node;
135 Type `char32_t[SOMENUMBER]' or something like it.
136 Used when a UTF-32 string literal is created.
138 tree char32_array_type_node;
140 Type `int ()' -- used for implicit declaration of functions.
142 tree default_function_type;
144 A VOID_TYPE node, packaged in a TREE_LIST.
146 tree void_list_node;
148 The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
149 and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
150 VAR_DECLS, but C++ does.)
152 tree function_name_decl_node;
153 tree pretty_function_name_decl_node;
154 tree c99_function_name_decl_node;
156 Stack of nested function name VAR_DECLs.
158 tree saved_function_name_decls;
162 tree c_global_trees[CTI_MAX];
164 /* Switches common to the C front ends. */
166 /* Nonzero means don't output line number information. */
168 char flag_no_line_commands;
170 /* Nonzero causes -E output not to be done, but directives such as
171 #define that have side effects are still obeyed. */
173 char flag_no_output;
175 /* Nonzero means dump macros in some fashion. */
177 char flag_dump_macros;
179 /* Nonzero means pass #include lines through to the output. */
181 char flag_dump_includes;
183 /* Nonzero means process PCH files while preprocessing. */
185 bool flag_pch_preprocess;
187 /* The file name to which we should write a precompiled header, or
188 NULL if no header will be written in this compile. */
190 const char *pch_file;
192 /* Nonzero if an ISO standard was selected. It rejects macros in the
193 user's namespace. */
194 int flag_iso;
196 /* C/ObjC language option variables. */
199 /* Nonzero means allow type mismatches in conditional expressions;
200 just make their values `void'. */
202 int flag_cond_mismatch;
204 /* Nonzero means enable C89 Amendment 1 features. */
206 int flag_isoc94;
208 /* Nonzero means use the ISO C99 (or C11) dialect of C. */
210 int flag_isoc99;
212 /* Nonzero means use the ISO C11 dialect of C. */
214 int flag_isoc11;
216 /* Nonzero means that we have builtin functions, and main is an int. */
218 int flag_hosted = 1;
221 /* ObjC language option variables. */
224 /* Tells the compiler that this is a special run. Do not perform any
225 compiling, instead we are to test some platform dependent features
226 and output a C header file with appropriate definitions. */
228 int print_struct_values;
230 /* Tells the compiler what is the constant string class for ObjC. */
232 const char *constant_string_class_name;
235 /* C++ language option variables. */
237 /* The reference version of the ABI for -Wabi. */
239 int warn_abi_version = -1;
241 /* Nonzero means generate separate instantiation control files and
242 juggle them at link time. */
244 int flag_use_repository;
246 /* The C++ dialect being used. Default set in c_common_post_options. */
248 enum cxx_dialect cxx_dialect = cxx_unset;
250 /* Maximum template instantiation depth. This limit exists to limit the
251 time it takes to notice excessively recursive template instantiations.
253 The default is lower than the 1024 recommended by the C++0x standard
254 because G++ runs out of stack before 1024 with highly recursive template
255 argument deduction substitution (g++.dg/cpp0x/enum11.C). */
257 int max_tinst_depth = 900;
259 /* The elements of `ridpointers' are identifier nodes for the reserved
260 type names and storage classes. It is indexed by a RID_... value. */
261 tree *ridpointers;
263 tree (*make_fname_decl) (location_t, tree, int);
265 /* Nonzero means don't warn about problems that occur when the code is
266 executed. */
267 int c_inhibit_evaluation_warnings;
269 /* Whether we are building a boolean conversion inside
270 convert_for_assignment, or some other late binary operation. If
271 build_binary_op is called for C (from code shared by C and C++) in
272 this case, then the operands have already been folded and the
273 result will not be folded again, so C_MAYBE_CONST_EXPR should not
274 be generated. */
275 bool in_late_binary_op;
277 /* Whether lexing has been completed, so subsequent preprocessor
278 errors should use the compiler's input_location. */
279 bool done_lexing = false;
281 /* Information about how a function name is generated. */
282 struct fname_var_t
284 tree *const decl; /* pointer to the VAR_DECL. */
285 const unsigned rid; /* RID number for the identifier. */
286 const int pretty; /* How pretty is it? */
289 /* The three ways of getting then name of the current function. */
291 const struct fname_var_t fname_vars[] =
293 /* C99 compliant __func__, must be first. */
294 {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
295 /* GCC __FUNCTION__ compliant. */
296 {&function_name_decl_node, RID_FUNCTION_NAME, 0},
297 /* GCC __PRETTY_FUNCTION__ compliant. */
298 {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
299 {NULL, 0, 0},
302 /* Global visibility options. */
303 struct visibility_flags visibility_options;
305 static tree check_case_value (location_t, tree);
306 static bool check_case_bounds (location_t, tree, tree, tree *, tree *,
307 bool *);
310 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
311 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
313 /* Reserved words. The third field is a mask: keywords are disabled
314 if they match the mask.
316 Masks for languages:
317 C --std=c89: D_C99 | D_CXXONLY | D_OBJC | D_CXX_OBJC
318 C --std=c99: D_CXXONLY | D_OBJC
319 ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
320 C++ --std=c++98: D_CONLY | D_CXX11 | D_OBJC
321 C++ --std=c++11: D_CONLY | D_OBJC
322 ObjC++ is like C++ except that D_OBJC is not set
324 If -fno-asm is used, D_ASM is added to the mask. If
325 -fno-gnu-keywords is used, D_EXT is added. If -fno-asm and C in
326 C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
327 In C with -Wc++-compat, we warn if D_CXXWARN is set.
329 Note the complication of the D_CXX_OBJC keywords. These are
330 reserved words such as 'class'. In C++, 'class' is a reserved
331 word. In Objective-C++ it is too. In Objective-C, it is a
332 reserved word too, but only if it follows an '@' sign.
334 const struct c_common_resword c_common_reswords[] =
336 { "_Alignas", RID_ALIGNAS, D_CONLY },
337 { "_Alignof", RID_ALIGNOF, D_CONLY },
338 { "_Atomic", RID_ATOMIC, D_CONLY },
339 { "_Bool", RID_BOOL, D_CONLY },
340 { "_Complex", RID_COMPLEX, 0 },
341 { "_Cilk_spawn", RID_CILK_SPAWN, 0 },
342 { "_Cilk_sync", RID_CILK_SYNC, 0 },
343 { "_Cilk_for", RID_CILK_FOR, 0 },
344 { "_Imaginary", RID_IMAGINARY, D_CONLY },
345 { "_Float16", RID_FLOAT16, D_CONLY },
346 { "_Float32", RID_FLOAT32, D_CONLY },
347 { "_Float64", RID_FLOAT64, D_CONLY },
348 { "_Float128", RID_FLOAT128, D_CONLY },
349 { "_Float32x", RID_FLOAT32X, D_CONLY },
350 { "_Float64x", RID_FLOAT64X, D_CONLY },
351 { "_Float128x", RID_FLOAT128X, D_CONLY },
352 { "_Decimal32", RID_DFLOAT32, D_CONLY | D_EXT },
353 { "_Decimal64", RID_DFLOAT64, D_CONLY | D_EXT },
354 { "_Decimal128", RID_DFLOAT128, D_CONLY | D_EXT },
355 { "_Fract", RID_FRACT, D_CONLY | D_EXT },
356 { "_Accum", RID_ACCUM, D_CONLY | D_EXT },
357 { "_Sat", RID_SAT, D_CONLY | D_EXT },
358 { "_Static_assert", RID_STATIC_ASSERT, D_CONLY },
359 { "_Noreturn", RID_NORETURN, D_CONLY },
360 { "_Generic", RID_GENERIC, D_CONLY },
361 { "_Thread_local", RID_THREAD, D_CONLY },
362 { "__FUNCTION__", RID_FUNCTION_NAME, 0 },
363 { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
364 { "__alignof", RID_ALIGNOF, 0 },
365 { "__alignof__", RID_ALIGNOF, 0 },
366 { "__asm", RID_ASM, 0 },
367 { "__asm__", RID_ASM, 0 },
368 { "__attribute", RID_ATTRIBUTE, 0 },
369 { "__attribute__", RID_ATTRIBUTE, 0 },
370 { "__auto_type", RID_AUTO_TYPE, D_CONLY },
371 { "__bases", RID_BASES, D_CXXONLY },
372 { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
373 { "__builtin_call_with_static_chain",
374 RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
375 { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
376 { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
377 { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
378 { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
379 { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
380 { "__builtin_offsetof", RID_OFFSETOF, 0 },
381 { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
382 { "__builtin_va_arg", RID_VA_ARG, 0 },
383 { "__complex", RID_COMPLEX, 0 },
384 { "__complex__", RID_COMPLEX, 0 },
385 { "__const", RID_CONST, 0 },
386 { "__const__", RID_CONST, 0 },
387 { "__decltype", RID_DECLTYPE, D_CXXONLY },
388 { "__direct_bases", RID_DIRECT_BASES, D_CXXONLY },
389 { "__extension__", RID_EXTENSION, 0 },
390 { "__func__", RID_C99_FUNCTION_NAME, 0 },
391 { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
392 { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
393 { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
394 { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
395 { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
396 { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
397 { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
398 { "__has_unique_object_representations", RID_HAS_UNIQUE_OBJ_REPRESENTATIONS,
399 D_CXXONLY },
400 { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
401 { "__imag", RID_IMAGPART, 0 },
402 { "__imag__", RID_IMAGPART, 0 },
403 { "__inline", RID_INLINE, 0 },
404 { "__inline__", RID_INLINE, 0 },
405 { "__is_abstract", RID_IS_ABSTRACT, D_CXXONLY },
406 { "__is_aggregate", RID_IS_AGGREGATE, D_CXXONLY },
407 { "__is_base_of", RID_IS_BASE_OF, D_CXXONLY },
408 { "__is_class", RID_IS_CLASS, D_CXXONLY },
409 { "__is_empty", RID_IS_EMPTY, D_CXXONLY },
410 { "__is_enum", RID_IS_ENUM, D_CXXONLY },
411 { "__is_final", RID_IS_FINAL, D_CXXONLY },
412 { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
413 { "__is_pod", RID_IS_POD, D_CXXONLY },
414 { "__is_polymorphic", RID_IS_POLYMORPHIC, D_CXXONLY },
415 { "__is_same_as", RID_IS_SAME_AS, D_CXXONLY },
416 { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
417 { "__is_trivial", RID_IS_TRIVIAL, D_CXXONLY },
418 { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
419 { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
420 { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
421 { "__is_union", RID_IS_UNION, D_CXXONLY },
422 { "__label__", RID_LABEL, 0 },
423 { "__null", RID_NULL, 0 },
424 { "__real", RID_REALPART, 0 },
425 { "__real__", RID_REALPART, 0 },
426 { "__restrict", RID_RESTRICT, 0 },
427 { "__restrict__", RID_RESTRICT, 0 },
428 { "__signed", RID_SIGNED, 0 },
429 { "__signed__", RID_SIGNED, 0 },
430 { "__thread", RID_THREAD, 0 },
431 { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
432 { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
433 { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
434 { "__typeof", RID_TYPEOF, 0 },
435 { "__typeof__", RID_TYPEOF, 0 },
436 { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
437 { "__volatile", RID_VOLATILE, 0 },
438 { "__volatile__", RID_VOLATILE, 0 },
439 { "__GIMPLE", RID_GIMPLE, D_CONLY },
440 { "__PHI", RID_PHI, D_CONLY },
441 { "__RTL", RID_RTL, D_CONLY },
442 { "alignas", RID_ALIGNAS, D_CXXONLY | D_CXX11 | D_CXXWARN },
443 { "alignof", RID_ALIGNOF, D_CXXONLY | D_CXX11 | D_CXXWARN },
444 { "asm", RID_ASM, D_ASM },
445 { "auto", RID_AUTO, 0 },
446 { "bool", RID_BOOL, D_CXXONLY | D_CXXWARN },
447 { "break", RID_BREAK, 0 },
448 { "case", RID_CASE, 0 },
449 { "catch", RID_CATCH, D_CXX_OBJC | D_CXXWARN },
450 { "char", RID_CHAR, 0 },
451 { "char16_t", RID_CHAR16, D_CXXONLY | D_CXX11 | D_CXXWARN },
452 { "char32_t", RID_CHAR32, D_CXXONLY | D_CXX11 | D_CXXWARN },
453 { "class", RID_CLASS, D_CXX_OBJC | D_CXXWARN },
454 { "const", RID_CONST, 0 },
455 { "constexpr", RID_CONSTEXPR, D_CXXONLY | D_CXX11 | D_CXXWARN },
456 { "const_cast", RID_CONSTCAST, D_CXXONLY | D_CXXWARN },
457 { "continue", RID_CONTINUE, 0 },
458 { "decltype", RID_DECLTYPE, D_CXXONLY | D_CXX11 | D_CXXWARN },
459 { "default", RID_DEFAULT, 0 },
460 { "delete", RID_DELETE, D_CXXONLY | D_CXXWARN },
461 { "do", RID_DO, 0 },
462 { "double", RID_DOUBLE, 0 },
463 { "dynamic_cast", RID_DYNCAST, D_CXXONLY | D_CXXWARN },
464 { "else", RID_ELSE, 0 },
465 { "enum", RID_ENUM, 0 },
466 { "explicit", RID_EXPLICIT, D_CXXONLY | D_CXXWARN },
467 { "export", RID_EXPORT, D_CXXONLY | D_CXXWARN },
468 { "extern", RID_EXTERN, 0 },
469 { "false", RID_FALSE, D_CXXONLY | D_CXXWARN },
470 { "float", RID_FLOAT, 0 },
471 { "for", RID_FOR, 0 },
472 { "friend", RID_FRIEND, D_CXXONLY | D_CXXWARN },
473 { "goto", RID_GOTO, 0 },
474 { "if", RID_IF, 0 },
475 { "inline", RID_INLINE, D_EXT89 },
476 { "int", RID_INT, 0 },
477 { "long", RID_LONG, 0 },
478 { "mutable", RID_MUTABLE, D_CXXONLY | D_CXXWARN },
479 { "namespace", RID_NAMESPACE, D_CXXONLY | D_CXXWARN },
480 { "new", RID_NEW, D_CXXONLY | D_CXXWARN },
481 { "noexcept", RID_NOEXCEPT, D_CXXONLY | D_CXX11 | D_CXXWARN },
482 { "nullptr", RID_NULLPTR, D_CXXONLY | D_CXX11 | D_CXXWARN },
483 { "operator", RID_OPERATOR, D_CXXONLY | D_CXXWARN },
484 { "private", RID_PRIVATE, D_CXX_OBJC | D_CXXWARN },
485 { "protected", RID_PROTECTED, D_CXX_OBJC | D_CXXWARN },
486 { "public", RID_PUBLIC, D_CXX_OBJC | D_CXXWARN },
487 { "register", RID_REGISTER, 0 },
488 { "reinterpret_cast", RID_REINTCAST, D_CXXONLY | D_CXXWARN },
489 { "restrict", RID_RESTRICT, D_CONLY | D_C99 },
490 { "return", RID_RETURN, 0 },
491 { "short", RID_SHORT, 0 },
492 { "signed", RID_SIGNED, 0 },
493 { "sizeof", RID_SIZEOF, 0 },
494 { "static", RID_STATIC, 0 },
495 { "static_assert", RID_STATIC_ASSERT, D_CXXONLY | D_CXX11 | D_CXXWARN },
496 { "static_cast", RID_STATCAST, D_CXXONLY | D_CXXWARN },
497 { "struct", RID_STRUCT, 0 },
498 { "switch", RID_SWITCH, 0 },
499 { "template", RID_TEMPLATE, D_CXXONLY | D_CXXWARN },
500 { "this", RID_THIS, D_CXXONLY | D_CXXWARN },
501 { "thread_local", RID_THREAD, D_CXXONLY | D_CXX11 | D_CXXWARN },
502 { "throw", RID_THROW, D_CXX_OBJC | D_CXXWARN },
503 { "true", RID_TRUE, D_CXXONLY | D_CXXWARN },
504 { "try", RID_TRY, D_CXX_OBJC | D_CXXWARN },
505 { "typedef", RID_TYPEDEF, 0 },
506 { "typename", RID_TYPENAME, D_CXXONLY | D_CXXWARN },
507 { "typeid", RID_TYPEID, D_CXXONLY | D_CXXWARN },
508 { "typeof", RID_TYPEOF, D_ASM | D_EXT },
509 { "union", RID_UNION, 0 },
510 { "unsigned", RID_UNSIGNED, 0 },
511 { "using", RID_USING, D_CXXONLY | D_CXXWARN },
512 { "virtual", RID_VIRTUAL, D_CXXONLY | D_CXXWARN },
513 { "void", RID_VOID, 0 },
514 { "volatile", RID_VOLATILE, 0 },
515 { "wchar_t", RID_WCHAR, D_CXXONLY },
516 { "while", RID_WHILE, 0 },
517 { "__is_assignable", RID_IS_ASSIGNABLE, D_CXXONLY },
518 { "__is_constructible", RID_IS_CONSTRUCTIBLE, D_CXXONLY },
520 /* C++ transactional memory. */
521 { "synchronized", RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
522 { "atomic_noexcept", RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
523 { "atomic_cancel", RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
524 { "atomic_commit", RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
526 /* Concepts-related keywords */
527 { "concept", RID_CONCEPT, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
528 { "requires", RID_REQUIRES, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
530 /* These Objective-C keywords are recognized only immediately after
531 an '@'. */
532 { "compatibility_alias", RID_AT_ALIAS, D_OBJC },
533 { "defs", RID_AT_DEFS, D_OBJC },
534 { "encode", RID_AT_ENCODE, D_OBJC },
535 { "end", RID_AT_END, D_OBJC },
536 { "implementation", RID_AT_IMPLEMENTATION, D_OBJC },
537 { "interface", RID_AT_INTERFACE, D_OBJC },
538 { "protocol", RID_AT_PROTOCOL, D_OBJC },
539 { "selector", RID_AT_SELECTOR, D_OBJC },
540 { "finally", RID_AT_FINALLY, D_OBJC },
541 { "optional", RID_AT_OPTIONAL, D_OBJC },
542 { "required", RID_AT_REQUIRED, D_OBJC },
543 { "property", RID_AT_PROPERTY, D_OBJC },
544 { "package", RID_AT_PACKAGE, D_OBJC },
545 { "synthesize", RID_AT_SYNTHESIZE, D_OBJC },
546 { "dynamic", RID_AT_DYNAMIC, D_OBJC },
547 /* These are recognized only in protocol-qualifier context
548 (see above) */
549 { "bycopy", RID_BYCOPY, D_OBJC },
550 { "byref", RID_BYREF, D_OBJC },
551 { "in", RID_IN, D_OBJC },
552 { "inout", RID_INOUT, D_OBJC },
553 { "oneway", RID_ONEWAY, D_OBJC },
554 { "out", RID_OUT, D_OBJC },
555 /* These are recognized inside a property attribute list */
556 { "assign", RID_ASSIGN, D_OBJC },
557 { "copy", RID_COPY, D_OBJC },
558 { "getter", RID_GETTER, D_OBJC },
559 { "nonatomic", RID_NONATOMIC, D_OBJC },
560 { "readonly", RID_READONLY, D_OBJC },
561 { "readwrite", RID_READWRITE, D_OBJC },
562 { "retain", RID_RETAIN, D_OBJC },
563 { "setter", RID_SETTER, D_OBJC },
566 const unsigned int num_c_common_reswords =
567 sizeof c_common_reswords / sizeof (struct c_common_resword);
569 /* Return identifier for address space AS. */
571 const char *
572 c_addr_space_name (addr_space_t as)
574 int rid = RID_FIRST_ADDR_SPACE + as;
575 gcc_assert (ridpointers [rid]);
576 return IDENTIFIER_POINTER (ridpointers [rid]);
579 /* Push current bindings for the function name VAR_DECLS. */
581 void
582 start_fname_decls (void)
584 unsigned ix;
585 tree saved = NULL_TREE;
587 for (ix = 0; fname_vars[ix].decl; ix++)
589 tree decl = *fname_vars[ix].decl;
591 if (decl)
593 saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
594 saved);
595 *fname_vars[ix].decl = NULL_TREE;
598 if (saved || saved_function_name_decls)
599 /* Normally they'll have been NULL, so only push if we've got a
600 stack, or they are non-NULL. */
601 saved_function_name_decls = tree_cons (saved, NULL_TREE,
602 saved_function_name_decls);
605 /* Finish up the current bindings, adding them into the current function's
606 statement tree. This must be done _before_ finish_stmt_tree is called.
607 If there is no current function, we must be at file scope and no statements
608 are involved. Pop the previous bindings. */
610 void
611 finish_fname_decls (void)
613 unsigned ix;
614 tree stmts = NULL_TREE;
615 tree stack = saved_function_name_decls;
617 for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
618 append_to_statement_list (TREE_VALUE (stack), &stmts);
620 if (stmts)
622 tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
624 if (TREE_CODE (*bodyp) == BIND_EXPR)
625 bodyp = &BIND_EXPR_BODY (*bodyp);
627 append_to_statement_list_force (*bodyp, &stmts);
628 *bodyp = stmts;
631 for (ix = 0; fname_vars[ix].decl; ix++)
632 *fname_vars[ix].decl = NULL_TREE;
634 if (stack)
636 /* We had saved values, restore them. */
637 tree saved;
639 for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
641 tree decl = TREE_PURPOSE (saved);
642 unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
644 *fname_vars[ix].decl = decl;
646 stack = TREE_CHAIN (stack);
648 saved_function_name_decls = stack;
651 /* Return the text name of the current function, suitably prettified
652 by PRETTY_P. Return string must be freed by caller. */
654 const char *
655 fname_as_string (int pretty_p)
657 const char *name = "top level";
658 char *namep;
659 int vrb = 2, len;
660 cpp_string cstr = { 0, 0 }, strname;
662 if (!pretty_p)
664 name = "";
665 vrb = 0;
668 if (current_function_decl)
669 name = lang_hooks.decl_printable_name (current_function_decl, vrb);
671 len = strlen (name) + 3; /* Two for '"'s. One for NULL. */
673 namep = XNEWVEC (char, len);
674 snprintf (namep, len, "\"%s\"", name);
675 strname.text = (unsigned char *) namep;
676 strname.len = len - 1;
678 if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
680 XDELETEVEC (namep);
681 return (const char *) cstr.text;
684 return namep;
687 /* Return the VAR_DECL for a const char array naming the current
688 function. If the VAR_DECL has not yet been created, create it
689 now. RID indicates how it should be formatted and IDENTIFIER_NODE
690 ID is its name (unfortunately C and C++ hold the RID values of
691 keywords in different places, so we can't derive RID from ID in
692 this language independent code. LOC is the location of the
693 function. */
695 tree
696 fname_decl (location_t loc, unsigned int rid, tree id)
698 unsigned ix;
699 tree decl = NULL_TREE;
701 for (ix = 0; fname_vars[ix].decl; ix++)
702 if (fname_vars[ix].rid == rid)
703 break;
705 decl = *fname_vars[ix].decl;
706 if (!decl)
708 /* If a tree is built here, it would normally have the lineno of
709 the current statement. Later this tree will be moved to the
710 beginning of the function and this line number will be wrong.
711 To avoid this problem set the lineno to 0 here; that prevents
712 it from appearing in the RTL. */
713 tree stmts;
714 location_t saved_location = input_location;
715 input_location = UNKNOWN_LOCATION;
717 stmts = push_stmt_list ();
718 decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
719 stmts = pop_stmt_list (stmts);
720 if (!IS_EMPTY_STMT (stmts))
721 saved_function_name_decls
722 = tree_cons (decl, stmts, saved_function_name_decls);
723 *fname_vars[ix].decl = decl;
724 input_location = saved_location;
726 if (!ix && !current_function_decl)
727 pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
729 return decl;
732 /* Given a STRING_CST, give it a suitable array-of-chars data type. */
734 tree
735 fix_string_type (tree value)
737 int length = TREE_STRING_LENGTH (value);
738 int nchars;
739 tree e_type, i_type, a_type;
741 /* Compute the number of elements, for the array type. */
742 if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
744 nchars = length;
745 e_type = char_type_node;
747 else if (TREE_TYPE (value) == char16_array_type_node)
749 nchars = length / (TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT);
750 e_type = char16_type_node;
752 else if (TREE_TYPE (value) == char32_array_type_node)
754 nchars = length / (TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT);
755 e_type = char32_type_node;
757 else
759 nchars = length / (TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT);
760 e_type = wchar_type_node;
763 /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits). The analogous
764 limit in C++98 Annex B is very large (65536) and is not normative,
765 so we do not diagnose it (warn_overlength_strings is forced off
766 in c_common_post_options). */
767 if (warn_overlength_strings)
769 const int nchars_max = flag_isoc99 ? 4095 : 509;
770 const int relevant_std = flag_isoc99 ? 99 : 90;
771 if (nchars - 1 > nchars_max)
772 /* Translators: The %d after 'ISO C' will be 90 or 99. Do not
773 separate the %d from the 'C'. 'ISO' should not be
774 translated, but it may be moved after 'C%d' in languages
775 where modifiers follow nouns. */
776 pedwarn (input_location, OPT_Woverlength_strings,
777 "string length %qd is greater than the length %qd "
778 "ISO C%d compilers are required to support",
779 nchars - 1, nchars_max, relevant_std);
782 /* Create the array type for the string constant. The ISO C++
783 standard says that a string literal has type `const char[N]' or
784 `const wchar_t[N]'. We use the same logic when invoked as a C
785 front-end with -Wwrite-strings.
786 ??? We should change the type of an expression depending on the
787 state of a warning flag. We should just be warning -- see how
788 this is handled in the C++ front-end for the deprecated implicit
789 conversion from string literals to `char*' or `wchar_t*'.
791 The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
792 array type being the unqualified version of that type.
793 Therefore, if we are constructing an array of const char, we must
794 construct the matching unqualified array type first. The C front
795 end does not require this, but it does no harm, so we do it
796 unconditionally. */
797 i_type = build_index_type (size_int (nchars - 1));
798 a_type = build_array_type (e_type, i_type);
799 if (c_dialect_cxx() || warn_write_strings)
800 a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
802 TREE_TYPE (value) = a_type;
803 TREE_CONSTANT (value) = 1;
804 TREE_READONLY (value) = 1;
805 TREE_STATIC (value) = 1;
806 return value;
809 /* Given a string of type STRING_TYPE, determine what kind of string
810 token would give an equivalent execution encoding: CPP_STRING,
811 CPP_STRING16, or CPP_STRING32. Return CPP_OTHER in case of error.
812 This may not be exactly the string token type that initially created
813 the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
814 string type at this point.
816 This effectively reverses part of the logic in lex_string and
817 fix_string_type. */
819 static enum cpp_ttype
820 get_cpp_ttype_from_string_type (tree string_type)
822 gcc_assert (string_type);
823 if (TREE_CODE (string_type) == POINTER_TYPE)
824 string_type = TREE_TYPE (string_type);
826 if (TREE_CODE (string_type) != ARRAY_TYPE)
827 return CPP_OTHER;
829 tree element_type = TREE_TYPE (string_type);
830 if (TREE_CODE (element_type) != INTEGER_TYPE)
831 return CPP_OTHER;
833 int bits_per_character = TYPE_PRECISION (element_type);
834 switch (bits_per_character)
836 case 8:
837 return CPP_STRING; /* It could have also been CPP_UTF8STRING. */
838 case 16:
839 return CPP_STRING16;
840 case 32:
841 return CPP_STRING32;
844 return CPP_OTHER;
847 /* The global record of string concatentations, for use in
848 extracting locations within string literals. */
850 GTY(()) string_concat_db *g_string_concat_db;
852 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION. */
854 const char *
855 c_get_substring_location (const substring_loc &substr_loc,
856 location_t *out_loc)
858 enum cpp_ttype tok_type
859 = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
860 if (tok_type == CPP_OTHER)
861 return "unrecognized string type";
863 return get_source_location_for_substring (parse_in, g_string_concat_db,
864 substr_loc.get_fmt_string_loc (),
865 tok_type,
866 substr_loc.get_caret_idx (),
867 substr_loc.get_start_idx (),
868 substr_loc.get_end_idx (),
869 out_loc);
873 /* Fold X for consideration by one of the warning functions when checking
874 whether an expression has a constant value. */
876 tree
877 fold_for_warn (tree x)
879 if (c_dialect_cxx ())
880 return c_fully_fold (x, /*for_init*/false, /*maybe_constp*/NULL);
881 else
882 /* The C front-end has already folded X appropriately. */
883 return x;
886 /* Return true iff T is a boolean promoted to int. */
888 bool
889 bool_promoted_to_int_p (tree t)
891 return (CONVERT_EXPR_P (t)
892 && TREE_TYPE (t) == integer_type_node
893 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
896 /* vector_targets_convertible_p is used for vector pointer types. The
897 callers perform various checks that the qualifiers are satisfactory,
898 while OTOH vector_targets_convertible_p ignores the number of elements
899 in the vectors. That's fine with vector pointers as we can consider,
900 say, a vector of 8 elements as two consecutive vectors of 4 elements,
901 and that does not require and conversion of the pointer values.
902 In contrast, vector_types_convertible_p and
903 vector_types_compatible_elements_p are used for vector value types. */
904 /* True if pointers to distinct types T1 and T2 can be converted to
905 each other without an explicit cast. Only returns true for opaque
906 vector types. */
907 bool
908 vector_targets_convertible_p (const_tree t1, const_tree t2)
910 if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
911 && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
912 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
913 return true;
915 return false;
918 /* vector_types_convertible_p is used for vector value types.
919 It could in principle call vector_targets_convertible_p as a subroutine,
920 but then the check for vector type would be duplicated with its callers,
921 and also the purpose of vector_targets_convertible_p would become
922 muddled.
923 Where vector_types_convertible_p returns true, a conversion might still be
924 needed to make the types match.
925 In contrast, vector_targets_convertible_p is used for vector pointer
926 values, and vector_types_compatible_elements_p is used specifically
927 in the context for binary operators, as a check if use is possible without
928 conversion. */
929 /* True if vector types T1 and T2 can be converted to each other
930 without an explicit cast. If EMIT_LAX_NOTE is true, and T1 and T2
931 can only be converted with -flax-vector-conversions yet that is not
932 in effect, emit a note telling the user about that option if such
933 a note has not previously been emitted. */
934 bool
935 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
937 static bool emitted_lax_note = false;
938 bool convertible_lax;
940 if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
941 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
942 return true;
944 convertible_lax =
945 (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
946 && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE ||
947 TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2))
948 && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
949 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
951 if (!convertible_lax || flag_lax_vector_conversions)
952 return convertible_lax;
954 if (TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2)
955 && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
956 return true;
958 if (emit_lax_note && !emitted_lax_note)
960 emitted_lax_note = true;
961 inform (input_location, "use -flax-vector-conversions to permit "
962 "conversions between vectors with differing "
963 "element types or numbers of subparts");
966 return false;
969 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
970 and have vector types, V0 has the same type as V1, and the number of
971 elements of V0, V1, MASK is the same.
973 In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
974 called with two arguments. In this case implementation passes the
975 first argument twice in order to share the same tree code. This fact
976 could enable the mask-values being twice the vector length. This is
977 an implementation accident and this semantics is not guaranteed to
978 the user. */
979 tree
980 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
981 bool complain)
983 tree ret;
984 bool wrap = true;
985 bool maybe_const = false;
986 bool two_arguments = false;
988 if (v1 == NULL_TREE)
990 two_arguments = true;
991 v1 = v0;
994 if (v0 == error_mark_node || v1 == error_mark_node
995 || mask == error_mark_node)
996 return error_mark_node;
998 if (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
1000 if (complain)
1001 error_at (loc, "__builtin_shuffle last argument must "
1002 "be an integer vector");
1003 return error_mark_node;
1006 if (!VECTOR_TYPE_P (TREE_TYPE (v0))
1007 || !VECTOR_TYPE_P (TREE_TYPE (v1)))
1009 if (complain)
1010 error_at (loc, "__builtin_shuffle arguments must be vectors");
1011 return error_mark_node;
1014 if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1016 if (complain)
1017 error_at (loc, "__builtin_shuffle argument vectors must be of "
1018 "the same type");
1019 return error_mark_node;
1022 if (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0))
1023 != TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))
1024 && TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1))
1025 != TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1027 if (complain)
1028 error_at (loc, "__builtin_shuffle number of elements of the "
1029 "argument vector(s) and the mask vector should "
1030 "be the same");
1031 return error_mark_node;
1034 if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1035 != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1037 if (complain)
1038 error_at (loc, "__builtin_shuffle argument vector(s) inner type "
1039 "must have the same size as inner type of the mask");
1040 return error_mark_node;
1043 if (!c_dialect_cxx ())
1045 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1046 v0 = c_fully_fold (v0, false, &maybe_const);
1047 wrap &= maybe_const;
1049 if (two_arguments)
1050 v1 = v0 = save_expr (v0);
1051 else
1053 v1 = c_fully_fold (v1, false, &maybe_const);
1054 wrap &= maybe_const;
1057 mask = c_fully_fold (mask, false, &maybe_const);
1058 wrap &= maybe_const;
1060 else if (two_arguments)
1061 v1 = v0 = save_expr (v0);
1063 ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1065 if (!c_dialect_cxx () && !wrap)
1066 ret = c_wrap_maybe_const (ret, true);
1068 return ret;
1071 /* Like tree.c:get_narrower, but retain conversion from C++0x scoped enum
1072 to integral type. */
1074 tree
1075 c_common_get_narrower (tree op, int *unsignedp_ptr)
1077 op = get_narrower (op, unsignedp_ptr);
1079 if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1080 && ENUM_IS_SCOPED (TREE_TYPE (op)))
1082 /* C++0x scoped enumerations don't implicitly convert to integral
1083 type; if we stripped an explicit conversion to a larger type we
1084 need to replace it so common_type will still work. */
1085 tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1086 TYPE_UNSIGNED (TREE_TYPE (op)));
1087 op = fold_convert (type, op);
1089 return op;
1092 /* This is a helper function of build_binary_op.
1094 For certain operations if both args were extended from the same
1095 smaller type, do the arithmetic in that type and then extend.
1097 BITWISE indicates a bitwise operation.
1098 For them, this optimization is safe only if
1099 both args are zero-extended or both are sign-extended.
1100 Otherwise, we might change the result.
1101 Eg, (short)-1 | (unsigned short)-1 is (int)-1
1102 but calculated in (unsigned short) it would be (unsigned short)-1.
1104 tree
1105 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1107 int unsigned0, unsigned1;
1108 tree arg0, arg1;
1109 int uns;
1110 tree type;
1112 /* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
1113 excessive narrowing when we call get_narrower below. For
1114 example, suppose that OP0 is of unsigned int extended
1115 from signed char and that RESULT_TYPE is long long int.
1116 If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1117 like
1119 (long long int) (unsigned int) signed_char
1121 which get_narrower would narrow down to
1123 (unsigned int) signed char
1125 If we do not cast OP0 first, get_narrower would return
1126 signed_char, which is inconsistent with the case of the
1127 explicit cast. */
1128 op0 = convert (result_type, op0);
1129 op1 = convert (result_type, op1);
1131 arg0 = c_common_get_narrower (op0, &unsigned0);
1132 arg1 = c_common_get_narrower (op1, &unsigned1);
1134 /* UNS is 1 if the operation to be done is an unsigned one. */
1135 uns = TYPE_UNSIGNED (result_type);
1137 /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1138 but it *requires* conversion to FINAL_TYPE. */
1140 if ((TYPE_PRECISION (TREE_TYPE (op0))
1141 == TYPE_PRECISION (TREE_TYPE (arg0)))
1142 && TREE_TYPE (op0) != result_type)
1143 unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1144 if ((TYPE_PRECISION (TREE_TYPE (op1))
1145 == TYPE_PRECISION (TREE_TYPE (arg1)))
1146 && TREE_TYPE (op1) != result_type)
1147 unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1149 /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
1151 /* For bitwise operations, signedness of nominal type
1152 does not matter. Consider only how operands were extended. */
1153 if (bitwise)
1154 uns = unsigned0;
1156 /* Note that in all three cases below we refrain from optimizing
1157 an unsigned operation on sign-extended args.
1158 That would not be valid. */
1160 /* Both args variable: if both extended in same way
1161 from same width, do it in that width.
1162 Do it unsigned if args were zero-extended. */
1163 if ((TYPE_PRECISION (TREE_TYPE (arg0))
1164 < TYPE_PRECISION (result_type))
1165 && (TYPE_PRECISION (TREE_TYPE (arg1))
1166 == TYPE_PRECISION (TREE_TYPE (arg0)))
1167 && unsigned0 == unsigned1
1168 && (unsigned0 || !uns))
1169 return c_common_signed_or_unsigned_type
1170 (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
1172 else if (TREE_CODE (arg0) == INTEGER_CST
1173 && (unsigned1 || !uns)
1174 && (TYPE_PRECISION (TREE_TYPE (arg1))
1175 < TYPE_PRECISION (result_type))
1176 && (type
1177 = c_common_signed_or_unsigned_type (unsigned1,
1178 TREE_TYPE (arg1)))
1179 && !POINTER_TYPE_P (type)
1180 && int_fits_type_p (arg0, type))
1181 return type;
1183 else if (TREE_CODE (arg1) == INTEGER_CST
1184 && (unsigned0 || !uns)
1185 && (TYPE_PRECISION (TREE_TYPE (arg0))
1186 < TYPE_PRECISION (result_type))
1187 && (type
1188 = c_common_signed_or_unsigned_type (unsigned0,
1189 TREE_TYPE (arg0)))
1190 && !POINTER_TYPE_P (type)
1191 && int_fits_type_p (arg1, type))
1192 return type;
1194 return result_type;
1197 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1198 real of type TO_TYPE. This is a helper function for unsafe_conversion_p. */
1200 static bool
1201 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1203 tree type_low_bound = TYPE_MIN_VALUE (from_type);
1204 tree type_high_bound = TYPE_MAX_VALUE (from_type);
1205 REAL_VALUE_TYPE real_low_bound =
1206 real_value_from_int_cst (0, type_low_bound);
1207 REAL_VALUE_TYPE real_high_bound =
1208 real_value_from_int_cst (0, type_high_bound);
1210 return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1211 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1214 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1215 to the complex/real/integer type TYPE. Function returns non-zero when:
1216 * EXPR is a constant which cannot be exactly converted to TYPE.
1217 * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1218 for EXPR type and TYPE being both integers or both real, or both
1219 complex.
1220 * EXPR is not a constant of complex type and TYPE is a real or
1221 an integer.
1222 * EXPR is not a constant of real type and TYPE is an integer.
1223 * EXPR is not a constant of integer type which cannot be
1224 exactly converted to real type.
1226 Function allows conversions between types of different signedness and
1227 can return SAFE_CONVERSION (zero) in that case. Function can produce
1228 signedness warnings if PRODUCE_WARNS is true.
1230 RESULT, when non-null is the result of the conversion. When constant
1231 it is included in the text of diagnostics.
1233 Function allows conversions from complex constants to non-complex types,
1234 provided that imaginary part is zero and real part can be safely converted
1235 to TYPE. */
1237 enum conversion_safety
1238 unsafe_conversion_p (location_t loc, tree type, tree expr, tree result,
1239 bool produce_warns)
1241 enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1242 tree expr_type = TREE_TYPE (expr);
1244 bool cstresult = (result
1245 && TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant);
1247 loc = expansion_point_location_if_in_system_header (loc);
1249 if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1251 /* If type is complex, we are interested in compatibility with
1252 underlying type. */
1253 if (TREE_CODE (type) == COMPLEX_TYPE)
1254 type = TREE_TYPE (type);
1256 /* Warn for real constant that is not an exact integer converted
1257 to integer type. */
1258 if (TREE_CODE (expr_type) == REAL_TYPE
1259 && TREE_CODE (type) == INTEGER_TYPE)
1261 if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1262 give_warning = UNSAFE_REAL;
1264 /* Warn for an integer constant that does not fit into integer type. */
1265 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1266 && TREE_CODE (type) == INTEGER_TYPE
1267 && !int_fits_type_p (expr, type))
1269 if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1270 && tree_int_cst_sgn (expr) < 0)
1272 if (produce_warns)
1274 if (cstresult)
1275 warning_at (loc, OPT_Wsign_conversion,
1276 "unsigned conversion from %qT to %qT "
1277 "changes value from %qE to %qE",
1278 expr_type, type, expr, result);
1279 else
1280 warning_at (loc, OPT_Wsign_conversion,
1281 "unsigned conversion from %qT to %qT "
1282 "changes the value of %qE",
1283 expr_type, type, expr);
1286 else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1288 if (cstresult)
1289 warning_at (loc, OPT_Wsign_conversion,
1290 "signed conversion from %qT to %qT changes "
1291 "value from %qE to %qE",
1292 expr_type, type, expr, result);
1293 else
1294 warning_at (loc, OPT_Wsign_conversion,
1295 "signed conversion from %qT to %qT changes "
1296 "the value of %qE",
1297 expr_type, type, expr);
1299 else
1300 give_warning = UNSAFE_OTHER;
1302 else if (TREE_CODE (type) == REAL_TYPE)
1304 /* Warn for an integer constant that does not fit into real type. */
1305 if (TREE_CODE (expr_type) == INTEGER_TYPE)
1307 REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1308 if (!exact_real_truncate (TYPE_MODE (type), &a))
1309 give_warning = UNSAFE_REAL;
1311 /* Warn for a real constant that does not fit into a smaller
1312 real type. */
1313 else if (TREE_CODE (expr_type) == REAL_TYPE
1314 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1316 REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1317 if (!exact_real_truncate (TYPE_MODE (type), &a))
1318 give_warning = UNSAFE_REAL;
1323 else if (TREE_CODE (expr) == COMPLEX_CST)
1325 tree imag_part = TREE_IMAGPART (expr);
1326 /* Conversion from complex constant with zero imaginary part,
1327 perform check for conversion of real part. */
1328 if ((TREE_CODE (imag_part) == REAL_CST
1329 && real_zerop (imag_part))
1330 || (TREE_CODE (imag_part) == INTEGER_CST
1331 && integer_zerop (imag_part)))
1332 /* Note: in this branch we use recursive call to unsafe_conversion_p
1333 with different type of EXPR, but it is still safe, because when EXPR
1334 is a constant, it's type is not used in text of generated warnings
1335 (otherwise they could sound misleading). */
1336 return unsafe_conversion_p (loc, type, TREE_REALPART (expr), result,
1337 produce_warns);
1338 /* Conversion from complex constant with non-zero imaginary part. */
1339 else
1341 /* Conversion to complex type.
1342 Perform checks for both real and imaginary parts. */
1343 if (TREE_CODE (type) == COMPLEX_TYPE)
1345 /* Unfortunately, produce_warns must be false in two subsequent
1346 calls of unsafe_conversion_p, because otherwise we could
1347 produce strange "double" warnings, if both real and imaginary
1348 parts have conversion problems related to signedness.
1350 For example:
1351 int32_t _Complex a = 0x80000000 + 0x80000000i;
1353 Possible solution: add a separate function for checking
1354 constants and combine result of two calls appropriately. */
1355 enum conversion_safety re_safety =
1356 unsafe_conversion_p (loc, type, TREE_REALPART (expr),
1357 result, false);
1358 enum conversion_safety im_safety =
1359 unsafe_conversion_p (loc, type, imag_part, result, false);
1361 /* Merge the results into appropriate single warning. */
1363 /* Note: this case includes SAFE_CONVERSION, i.e. success. */
1364 if (re_safety == im_safety)
1365 give_warning = re_safety;
1366 else if (!re_safety && im_safety)
1367 give_warning = im_safety;
1368 else if (re_safety && !im_safety)
1369 give_warning = re_safety;
1370 else
1371 give_warning = UNSAFE_OTHER;
1373 /* Warn about conversion from complex to real or integer type. */
1374 else
1375 give_warning = UNSAFE_IMAGINARY;
1379 /* Checks for remaining case: EXPR is not constant. */
1380 else
1382 /* Warn for real types converted to integer types. */
1383 if (TREE_CODE (expr_type) == REAL_TYPE
1384 && TREE_CODE (type) == INTEGER_TYPE)
1385 give_warning = UNSAFE_REAL;
1387 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1388 && TREE_CODE (type) == INTEGER_TYPE)
1390 /* Don't warn about unsigned char y = 0xff, x = (int) y; */
1391 expr = get_unwidened (expr, 0);
1392 expr_type = TREE_TYPE (expr);
1394 /* Don't warn for short y; short x = ((int)y & 0xff); */
1395 if (TREE_CODE (expr) == BIT_AND_EXPR
1396 || TREE_CODE (expr) == BIT_IOR_EXPR
1397 || TREE_CODE (expr) == BIT_XOR_EXPR)
1399 /* If both args were extended from a shortest type,
1400 use that type if that is safe. */
1401 expr_type = shorten_binary_op (expr_type,
1402 TREE_OPERAND (expr, 0),
1403 TREE_OPERAND (expr, 1),
1404 /* bitwise */1);
1406 if (TREE_CODE (expr) == BIT_AND_EXPR)
1408 tree op0 = TREE_OPERAND (expr, 0);
1409 tree op1 = TREE_OPERAND (expr, 1);
1410 bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1411 bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1413 /* If one of the operands is a non-negative constant
1414 that fits in the target type, then the type of the
1415 other operand does not matter. */
1416 if ((TREE_CODE (op0) == INTEGER_CST
1417 && int_fits_type_p (op0, c_common_signed_type (type))
1418 && int_fits_type_p (op0, c_common_unsigned_type (type)))
1419 || (TREE_CODE (op1) == INTEGER_CST
1420 && int_fits_type_p (op1, c_common_signed_type (type))
1421 && int_fits_type_p (op1,
1422 c_common_unsigned_type (type))))
1423 return SAFE_CONVERSION;
1424 /* If constant is unsigned and fits in the target
1425 type, then the result will also fit. */
1426 else if ((TREE_CODE (op0) == INTEGER_CST
1427 && unsigned0
1428 && int_fits_type_p (op0, type))
1429 || (TREE_CODE (op1) == INTEGER_CST
1430 && unsigned1
1431 && int_fits_type_p (op1, type)))
1432 return SAFE_CONVERSION;
1435 /* Warn for integer types converted to smaller integer types. */
1436 if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1437 give_warning = UNSAFE_OTHER;
1439 /* When they are the same width but different signedness,
1440 then the value may change. */
1441 else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1442 && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1443 /* Even when converted to a bigger type, if the type is
1444 unsigned but expr is signed, then negative values
1445 will be changed. */
1446 || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1447 && produce_warns)
1448 warning_at (loc, OPT_Wsign_conversion, "conversion to %qT from %qT "
1449 "may change the sign of the result",
1450 type, expr_type);
1453 /* Warn for integer types converted to real types if and only if
1454 all the range of values of the integer type cannot be
1455 represented by the real type. */
1456 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1457 && TREE_CODE (type) == REAL_TYPE)
1459 /* Don't warn about char y = 0xff; float x = (int) y; */
1460 expr = get_unwidened (expr, 0);
1461 expr_type = TREE_TYPE (expr);
1463 if (!int_safely_convertible_to_real_p (expr_type, type))
1464 give_warning = UNSAFE_OTHER;
1467 /* Warn for real types converted to smaller real types. */
1468 else if (TREE_CODE (expr_type) == REAL_TYPE
1469 && TREE_CODE (type) == REAL_TYPE
1470 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1471 give_warning = UNSAFE_REAL;
1473 /* Check conversion between two complex types. */
1474 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1475 && TREE_CODE (type) == COMPLEX_TYPE)
1477 /* Extract underlying types (i.e., type of real and imaginary
1478 parts) of expr_type and type. */
1479 tree from_type = TREE_TYPE (expr_type);
1480 tree to_type = TREE_TYPE (type);
1482 /* Warn for real types converted to integer types. */
1483 if (TREE_CODE (from_type) == REAL_TYPE
1484 && TREE_CODE (to_type) == INTEGER_TYPE)
1485 give_warning = UNSAFE_REAL;
1487 /* Warn for real types converted to smaller real types. */
1488 else if (TREE_CODE (from_type) == REAL_TYPE
1489 && TREE_CODE (to_type) == REAL_TYPE
1490 && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1491 give_warning = UNSAFE_REAL;
1493 /* Check conversion for complex integer types. Here implementation
1494 is simpler than for real-domain integers because it does not
1495 involve sophisticated cases, such as bitmasks, casts, etc. */
1496 else if (TREE_CODE (from_type) == INTEGER_TYPE
1497 && TREE_CODE (to_type) == INTEGER_TYPE)
1499 /* Warn for integer types converted to smaller integer types. */
1500 if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1501 give_warning = UNSAFE_OTHER;
1503 /* Check for different signedness, see case for real-domain
1504 integers (above) for a more detailed comment. */
1505 else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1506 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1507 || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1508 && produce_warns)
1509 warning_at (loc, OPT_Wsign_conversion,
1510 "conversion to %qT from %qT "
1511 "may change the sign of the result",
1512 type, expr_type);
1514 else if (TREE_CODE (from_type) == INTEGER_TYPE
1515 && TREE_CODE (to_type) == REAL_TYPE
1516 && !int_safely_convertible_to_real_p (from_type, to_type))
1517 give_warning = UNSAFE_OTHER;
1520 /* Warn for complex types converted to real or integer types. */
1521 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1522 && TREE_CODE (type) != COMPLEX_TYPE)
1523 give_warning = UNSAFE_IMAGINARY;
1526 return give_warning;
1530 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1531 Invoke this function on every expression that is converted implicitly,
1532 i.e. because of language rules and not because of an explicit cast. */
1534 tree
1535 convert_and_check (location_t loc, tree type, tree expr)
1537 tree result;
1538 tree expr_for_warning;
1540 /* Convert from a value with possible excess precision rather than
1541 via the semantic type, but do not warn about values not fitting
1542 exactly in the semantic type. */
1543 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1545 tree orig_type = TREE_TYPE (expr);
1546 expr = TREE_OPERAND (expr, 0);
1547 expr_for_warning = convert (orig_type, expr);
1548 if (orig_type == type)
1549 return expr_for_warning;
1551 else
1552 expr_for_warning = expr;
1554 if (TREE_TYPE (expr) == type)
1555 return expr;
1557 result = convert (type, expr);
1559 if (c_inhibit_evaluation_warnings == 0
1560 && !TREE_OVERFLOW_P (expr)
1561 && result != error_mark_node)
1562 warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1564 return result;
1567 /* A node in a list that describes references to variables (EXPR), which are
1568 either read accesses if WRITER is zero, or write accesses, in which case
1569 WRITER is the parent of EXPR. */
1570 struct tlist
1572 struct tlist *next;
1573 tree expr, writer;
1576 /* Used to implement a cache the results of a call to verify_tree. We only
1577 use this for SAVE_EXPRs. */
1578 struct tlist_cache
1580 struct tlist_cache *next;
1581 struct tlist *cache_before_sp;
1582 struct tlist *cache_after_sp;
1583 tree expr;
1586 /* Obstack to use when allocating tlist structures, and corresponding
1587 firstobj. */
1588 static struct obstack tlist_obstack;
1589 static char *tlist_firstobj = 0;
1591 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1592 warnings. */
1593 static struct tlist *warned_ids;
1594 /* SAVE_EXPRs need special treatment. We process them only once and then
1595 cache the results. */
1596 static struct tlist_cache *save_expr_cache;
1598 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1599 static void merge_tlist (struct tlist **, struct tlist *, int);
1600 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1601 static bool warning_candidate_p (tree);
1602 static bool candidate_equal_p (const_tree, const_tree);
1603 static void warn_for_collisions (struct tlist *);
1604 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1605 static struct tlist *new_tlist (struct tlist *, tree, tree);
1607 /* Create a new struct tlist and fill in its fields. */
1608 static struct tlist *
1609 new_tlist (struct tlist *next, tree t, tree writer)
1611 struct tlist *l;
1612 l = XOBNEW (&tlist_obstack, struct tlist);
1613 l->next = next;
1614 l->expr = t;
1615 l->writer = writer;
1616 return l;
1619 /* Add duplicates of the nodes found in ADD to the list *TO. If EXCLUDE_WRITER
1620 is nonnull, we ignore any node we find which has a writer equal to it. */
1622 static void
1623 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1625 while (add)
1627 struct tlist *next = add->next;
1628 if (!copy)
1629 add->next = *to;
1630 if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1631 *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1632 add = next;
1636 /* Merge the nodes of ADD into TO. This merging process is done so that for
1637 each variable that already exists in TO, no new node is added; however if
1638 there is a write access recorded in ADD, and an occurrence on TO is only
1639 a read access, then the occurrence in TO will be modified to record the
1640 write. */
1642 static void
1643 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1645 struct tlist **end = to;
1647 while (*end)
1648 end = &(*end)->next;
1650 while (add)
1652 int found = 0;
1653 struct tlist *tmp2;
1654 struct tlist *next = add->next;
1656 for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1657 if (candidate_equal_p (tmp2->expr, add->expr))
1659 found = 1;
1660 if (!tmp2->writer)
1661 tmp2->writer = add->writer;
1663 if (!found)
1665 *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1666 end = &(*end)->next;
1667 *end = 0;
1669 add = next;
1673 /* WRITTEN is a variable, WRITER is its parent. Warn if any of the variable
1674 references in list LIST conflict with it, excluding reads if ONLY writers
1675 is nonzero. */
1677 static void
1678 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1679 int only_writes)
1681 struct tlist *tmp;
1683 /* Avoid duplicate warnings. */
1684 for (tmp = warned_ids; tmp; tmp = tmp->next)
1685 if (candidate_equal_p (tmp->expr, written))
1686 return;
1688 while (list)
1690 if (candidate_equal_p (list->expr, written)
1691 && !candidate_equal_p (list->writer, writer)
1692 && (!only_writes || list->writer))
1694 warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1695 warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1696 OPT_Wsequence_point, "operation on %qE may be undefined",
1697 list->expr);
1699 list = list->next;
1703 /* Given a list LIST of references to variables, find whether any of these
1704 can cause conflicts due to missing sequence points. */
1706 static void
1707 warn_for_collisions (struct tlist *list)
1709 struct tlist *tmp;
1711 for (tmp = list; tmp; tmp = tmp->next)
1713 if (tmp->writer)
1714 warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1718 /* Return nonzero if X is a tree that can be verified by the sequence point
1719 warnings. */
1721 static bool
1722 warning_candidate_p (tree x)
1724 if (DECL_P (x) && DECL_ARTIFICIAL (x))
1725 return false;
1727 if (TREE_CODE (x) == BLOCK)
1728 return false;
1730 /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.c
1731 (lvalue_p) crash on TRY/CATCH. */
1732 if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1733 return false;
1735 if (!lvalue_p (x))
1736 return false;
1738 /* No point to track non-const calls, they will never satisfy
1739 operand_equal_p. */
1740 if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1741 return false;
1743 if (TREE_CODE (x) == STRING_CST)
1744 return false;
1746 return true;
1749 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1750 static bool
1751 candidate_equal_p (const_tree x, const_tree y)
1753 return (x == y) || (x && y && operand_equal_p (x, y, 0));
1756 /* Walk the tree X, and record accesses to variables. If X is written by the
1757 parent tree, WRITER is the parent.
1758 We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP. If this
1759 expression or its only operand forces a sequence point, then everything up
1760 to the sequence point is stored in PBEFORE_SP. Everything else gets stored
1761 in PNO_SP.
1762 Once we return, we will have emitted warnings if any subexpression before
1763 such a sequence point could be undefined. On a higher level, however, the
1764 sequence point may not be relevant, and we'll merge the two lists.
1766 Example: (b++, a) + b;
1767 The call that processes the COMPOUND_EXPR will store the increment of B
1768 in PBEFORE_SP, and the use of A in PNO_SP. The higher-level call that
1769 processes the PLUS_EXPR will need to merge the two lists so that
1770 eventually, all accesses end up on the same list (and we'll warn about the
1771 unordered subexpressions b++ and b.
1773 A note on merging. If we modify the former example so that our expression
1774 becomes
1775 (b++, b) + a
1776 care must be taken not simply to add all three expressions into the final
1777 PNO_SP list. The function merge_tlist takes care of that by merging the
1778 before-SP list of the COMPOUND_EXPR into its after-SP list in a special
1779 way, so that no more than one access to B is recorded. */
1781 static void
1782 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
1783 tree writer)
1785 struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
1786 enum tree_code code;
1787 enum tree_code_class cl;
1789 /* X may be NULL if it is the operand of an empty statement expression
1790 ({ }). */
1791 if (x == NULL)
1792 return;
1794 restart:
1795 code = TREE_CODE (x);
1796 cl = TREE_CODE_CLASS (code);
1798 if (warning_candidate_p (x))
1799 *pno_sp = new_tlist (*pno_sp, x, writer);
1801 switch (code)
1803 case CONSTRUCTOR:
1804 case SIZEOF_EXPR:
1805 return;
1807 case COMPOUND_EXPR:
1808 case TRUTH_ANDIF_EXPR:
1809 case TRUTH_ORIF_EXPR:
1810 tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
1811 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1812 warn_for_collisions (tmp_nosp);
1813 merge_tlist (pbefore_sp, tmp_before, 0);
1814 merge_tlist (pbefore_sp, tmp_nosp, 0);
1815 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
1816 warn_for_collisions (tmp_list2);
1817 merge_tlist (pbefore_sp, tmp_list3, 0);
1818 merge_tlist (pno_sp, tmp_list2, 0);
1819 return;
1821 case COND_EXPR:
1822 tmp_before = tmp_list2 = 0;
1823 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
1824 warn_for_collisions (tmp_list2);
1825 merge_tlist (pbefore_sp, tmp_before, 0);
1826 merge_tlist (pbefore_sp, tmp_list2, 0);
1828 tmp_list3 = tmp_nosp = 0;
1829 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
1830 warn_for_collisions (tmp_nosp);
1831 merge_tlist (pbefore_sp, tmp_list3, 0);
1833 tmp_list3 = tmp_list2 = 0;
1834 verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
1835 warn_for_collisions (tmp_list2);
1836 merge_tlist (pbefore_sp, tmp_list3, 0);
1837 /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
1838 two first, to avoid warning for (a ? b++ : b++). */
1839 merge_tlist (&tmp_nosp, tmp_list2, 0);
1840 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1841 return;
1843 case PREDECREMENT_EXPR:
1844 case PREINCREMENT_EXPR:
1845 case POSTDECREMENT_EXPR:
1846 case POSTINCREMENT_EXPR:
1847 verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
1848 return;
1850 case MODIFY_EXPR:
1851 tmp_before = tmp_nosp = tmp_list3 = 0;
1852 verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
1853 verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
1854 /* Expressions inside the LHS are not ordered wrt. the sequence points
1855 in the RHS. Example:
1856 *a = (a++, 2)
1857 Despite the fact that the modification of "a" is in the before_sp
1858 list (tmp_before), it conflicts with the use of "a" in the LHS.
1859 We can handle this by adding the contents of tmp_list3
1860 to those of tmp_before, and redoing the collision warnings for that
1861 list. */
1862 add_tlist (&tmp_before, tmp_list3, x, 1);
1863 warn_for_collisions (tmp_before);
1864 /* Exclude the LHS itself here; we first have to merge it into the
1865 tmp_nosp list. This is done to avoid warning for "a = a"; if we
1866 didn't exclude the LHS, we'd get it twice, once as a read and once
1867 as a write. */
1868 add_tlist (pno_sp, tmp_list3, x, 0);
1869 warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
1871 merge_tlist (pbefore_sp, tmp_before, 0);
1872 if (warning_candidate_p (TREE_OPERAND (x, 0)))
1873 merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
1874 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
1875 return;
1877 case CALL_EXPR:
1878 /* We need to warn about conflicts among arguments and conflicts between
1879 args and the function address. Side effects of the function address,
1880 however, are not ordered by the sequence point of the call. */
1882 call_expr_arg_iterator iter;
1883 tree arg;
1884 tmp_before = tmp_nosp = 0;
1885 verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
1886 FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
1888 tmp_list2 = tmp_list3 = 0;
1889 verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
1890 merge_tlist (&tmp_list3, tmp_list2, 0);
1891 add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
1893 add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
1894 warn_for_collisions (tmp_before);
1895 add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
1896 return;
1899 case TREE_LIST:
1900 /* Scan all the list, e.g. indices of multi dimensional array. */
1901 while (x)
1903 tmp_before = tmp_nosp = 0;
1904 verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
1905 merge_tlist (&tmp_nosp, tmp_before, 0);
1906 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1907 x = TREE_CHAIN (x);
1909 return;
1911 case SAVE_EXPR:
1913 struct tlist_cache *t;
1914 for (t = save_expr_cache; t; t = t->next)
1915 if (candidate_equal_p (t->expr, x))
1916 break;
1918 if (!t)
1920 t = XOBNEW (&tlist_obstack, struct tlist_cache);
1921 t->next = save_expr_cache;
1922 t->expr = x;
1923 save_expr_cache = t;
1925 tmp_before = tmp_nosp = 0;
1926 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1927 warn_for_collisions (tmp_nosp);
1929 tmp_list3 = 0;
1930 merge_tlist (&tmp_list3, tmp_nosp, 0);
1931 t->cache_before_sp = tmp_before;
1932 t->cache_after_sp = tmp_list3;
1934 merge_tlist (pbefore_sp, t->cache_before_sp, 1);
1935 add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
1936 return;
1939 case ADDR_EXPR:
1940 x = TREE_OPERAND (x, 0);
1941 if (DECL_P (x))
1942 return;
1943 writer = 0;
1944 goto restart;
1946 default:
1947 /* For other expressions, simply recurse on their operands.
1948 Manual tail recursion for unary expressions.
1949 Other non-expressions need not be processed. */
1950 if (cl == tcc_unary)
1952 x = TREE_OPERAND (x, 0);
1953 writer = 0;
1954 goto restart;
1956 else if (IS_EXPR_CODE_CLASS (cl))
1958 int lp;
1959 int max = TREE_OPERAND_LENGTH (x);
1960 for (lp = 0; lp < max; lp++)
1962 tmp_before = tmp_nosp = 0;
1963 verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
1964 merge_tlist (&tmp_nosp, tmp_before, 0);
1965 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1968 return;
1972 /* Try to warn for undefined behavior in EXPR due to missing sequence
1973 points. */
1975 DEBUG_FUNCTION void
1976 verify_sequence_points (tree expr)
1978 struct tlist *before_sp = 0, *after_sp = 0;
1980 warned_ids = 0;
1981 save_expr_cache = 0;
1982 if (tlist_firstobj == 0)
1984 gcc_obstack_init (&tlist_obstack);
1985 tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
1988 verify_tree (expr, &before_sp, &after_sp, 0);
1989 warn_for_collisions (after_sp);
1990 obstack_free (&tlist_obstack, tlist_firstobj);
1993 /* Validate the expression after `case' and apply default promotions. */
1995 static tree
1996 check_case_value (location_t loc, tree value)
1998 if (value == NULL_TREE)
1999 return value;
2001 if (TREE_CODE (value) == INTEGER_CST)
2002 /* Promote char or short to int. */
2003 value = perform_integral_promotions (value);
2004 else if (value != error_mark_node)
2006 error_at (loc, "case label does not reduce to an integer constant");
2007 value = error_mark_node;
2010 constant_expression_warning (value);
2012 return value;
2015 /* See if the case values LOW and HIGH are in the range of the original
2016 type (i.e. before the default conversion to int) of the switch testing
2017 expression.
2018 TYPE is the promoted type of the testing expression, and ORIG_TYPE is
2019 the type before promoting it. CASE_LOW_P is a pointer to the lower
2020 bound of the case label, and CASE_HIGH_P is the upper bound or NULL
2021 if the case is not a case range.
2022 The caller has to make sure that we are not called with NULL for
2023 CASE_LOW_P (i.e. the default case). OUTSIDE_RANGE_P says whether there
2024 was a case value that doesn't fit into the range of the ORIG_TYPE.
2025 Returns true if the case label is in range of ORIG_TYPE (saturated or
2026 untouched) or false if the label is out of range. */
2028 static bool
2029 check_case_bounds (location_t loc, tree type, tree orig_type,
2030 tree *case_low_p, tree *case_high_p,
2031 bool *outside_range_p)
2033 tree min_value, max_value;
2034 tree case_low = *case_low_p;
2035 tree case_high = case_high_p ? *case_high_p : case_low;
2037 /* If there was a problem with the original type, do nothing. */
2038 if (orig_type == error_mark_node)
2039 return true;
2041 min_value = TYPE_MIN_VALUE (orig_type);
2042 max_value = TYPE_MAX_VALUE (orig_type);
2044 /* We'll really need integer constants here. */
2045 case_low = fold (case_low);
2046 case_high = fold (case_high);
2048 /* Case label is less than minimum for type. */
2049 if (tree_int_cst_compare (case_low, min_value) < 0
2050 && tree_int_cst_compare (case_high, min_value) < 0)
2052 warning_at (loc, 0, "case label value is less than minimum value "
2053 "for type");
2054 *outside_range_p = true;
2055 return false;
2058 /* Case value is greater than maximum for type. */
2059 if (tree_int_cst_compare (case_low, max_value) > 0
2060 && tree_int_cst_compare (case_high, max_value) > 0)
2062 warning_at (loc, 0, "case label value exceeds maximum value for type");
2063 *outside_range_p = true;
2064 return false;
2067 /* Saturate lower case label value to minimum. */
2068 if (tree_int_cst_compare (case_high, min_value) >= 0
2069 && tree_int_cst_compare (case_low, min_value) < 0)
2071 warning_at (loc, 0, "lower value in case label range"
2072 " less than minimum value for type");
2073 *outside_range_p = true;
2074 case_low = min_value;
2077 /* Saturate upper case label value to maximum. */
2078 if (tree_int_cst_compare (case_low, max_value) <= 0
2079 && tree_int_cst_compare (case_high, max_value) > 0)
2081 warning_at (loc, 0, "upper value in case label range"
2082 " exceeds maximum value for type");
2083 *outside_range_p = true;
2084 case_high = max_value;
2087 if (*case_low_p != case_low)
2088 *case_low_p = convert (type, case_low);
2089 if (case_high_p && *case_high_p != case_high)
2090 *case_high_p = convert (type, case_high);
2092 return true;
2095 /* Return an integer type with BITS bits of precision,
2096 that is unsigned if UNSIGNEDP is nonzero, otherwise signed. */
2098 tree
2099 c_common_type_for_size (unsigned int bits, int unsignedp)
2101 int i;
2103 if (bits == TYPE_PRECISION (integer_type_node))
2104 return unsignedp ? unsigned_type_node : integer_type_node;
2106 if (bits == TYPE_PRECISION (signed_char_type_node))
2107 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2109 if (bits == TYPE_PRECISION (short_integer_type_node))
2110 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2112 if (bits == TYPE_PRECISION (long_integer_type_node))
2113 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2115 if (bits == TYPE_PRECISION (long_long_integer_type_node))
2116 return (unsignedp ? long_long_unsigned_type_node
2117 : long_long_integer_type_node);
2119 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2120 if (int_n_enabled_p[i]
2121 && bits == int_n_data[i].bitsize)
2122 return (unsignedp ? int_n_trees[i].unsigned_type
2123 : int_n_trees[i].signed_type);
2125 if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2126 return (unsignedp ? widest_unsigned_literal_type_node
2127 : widest_integer_literal_type_node);
2129 if (bits <= TYPE_PRECISION (intQI_type_node))
2130 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2132 if (bits <= TYPE_PRECISION (intHI_type_node))
2133 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2135 if (bits <= TYPE_PRECISION (intSI_type_node))
2136 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2138 if (bits <= TYPE_PRECISION (intDI_type_node))
2139 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2141 return NULL_TREE;
2144 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2145 that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2146 and saturating if SATP is nonzero, otherwise not saturating. */
2148 tree
2149 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2150 int unsignedp, int satp)
2152 enum mode_class mclass;
2153 if (ibit == 0)
2154 mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2155 else
2156 mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2158 opt_scalar_mode opt_mode;
2159 scalar_mode mode;
2160 FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2162 mode = opt_mode.require ();
2163 if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2164 break;
2167 if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2169 sorry ("GCC cannot support operators with integer types and "
2170 "fixed-point types that have too many integral and "
2171 "fractional bits together");
2172 return NULL_TREE;
2175 return c_common_type_for_mode (mode, satp);
2178 /* Used for communication between c_common_type_for_mode and
2179 c_register_builtin_type. */
2180 tree registered_builtin_types;
2182 /* Return a data type that has machine mode MODE.
2183 If the mode is an integer,
2184 then UNSIGNEDP selects between signed and unsigned types.
2185 If the mode is a fixed-point mode,
2186 then UNSIGNEDP selects between saturating and nonsaturating types. */
2188 tree
2189 c_common_type_for_mode (machine_mode mode, int unsignedp)
2191 tree t;
2192 int i;
2194 if (mode == TYPE_MODE (integer_type_node))
2195 return unsignedp ? unsigned_type_node : integer_type_node;
2197 if (mode == TYPE_MODE (signed_char_type_node))
2198 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2200 if (mode == TYPE_MODE (short_integer_type_node))
2201 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2203 if (mode == TYPE_MODE (long_integer_type_node))
2204 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2206 if (mode == TYPE_MODE (long_long_integer_type_node))
2207 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2209 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2210 if (int_n_enabled_p[i]
2211 && mode == int_n_data[i].m)
2212 return (unsignedp ? int_n_trees[i].unsigned_type
2213 : int_n_trees[i].signed_type);
2215 if (mode == QImode)
2216 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2218 if (mode == HImode)
2219 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2221 if (mode == SImode)
2222 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2224 if (mode == DImode)
2225 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2227 #if HOST_BITS_PER_WIDE_INT >= 64
2228 if (mode == TYPE_MODE (intTI_type_node))
2229 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2230 #endif
2232 if (mode == TYPE_MODE (float_type_node))
2233 return float_type_node;
2235 if (mode == TYPE_MODE (double_type_node))
2236 return double_type_node;
2238 if (mode == TYPE_MODE (long_double_type_node))
2239 return long_double_type_node;
2241 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2242 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2243 && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2244 return FLOATN_NX_TYPE_NODE (i);
2246 if (mode == TYPE_MODE (void_type_node))
2247 return void_type_node;
2249 if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2250 || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2252 unsigned int precision
2253 = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2254 return (unsignedp
2255 ? make_unsigned_type (precision)
2256 : make_signed_type (precision));
2259 if (COMPLEX_MODE_P (mode))
2261 machine_mode inner_mode;
2262 tree inner_type;
2264 if (mode == TYPE_MODE (complex_float_type_node))
2265 return complex_float_type_node;
2266 if (mode == TYPE_MODE (complex_double_type_node))
2267 return complex_double_type_node;
2268 if (mode == TYPE_MODE (complex_long_double_type_node))
2269 return complex_long_double_type_node;
2271 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2272 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2273 && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2274 return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2276 if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2277 return complex_integer_type_node;
2279 inner_mode = GET_MODE_INNER (mode);
2280 inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2281 if (inner_type != NULL_TREE)
2282 return build_complex_type (inner_type);
2284 else if (VECTOR_MODE_P (mode))
2286 machine_mode inner_mode = GET_MODE_INNER (mode);
2287 tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2288 if (inner_type != NULL_TREE)
2289 return build_vector_type_for_mode (inner_type, mode);
2292 if (mode == TYPE_MODE (dfloat32_type_node))
2293 return dfloat32_type_node;
2294 if (mode == TYPE_MODE (dfloat64_type_node))
2295 return dfloat64_type_node;
2296 if (mode == TYPE_MODE (dfloat128_type_node))
2297 return dfloat128_type_node;
2299 if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2301 if (mode == TYPE_MODE (short_fract_type_node))
2302 return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2303 if (mode == TYPE_MODE (fract_type_node))
2304 return unsignedp ? sat_fract_type_node : fract_type_node;
2305 if (mode == TYPE_MODE (long_fract_type_node))
2306 return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2307 if (mode == TYPE_MODE (long_long_fract_type_node))
2308 return unsignedp ? sat_long_long_fract_type_node
2309 : long_long_fract_type_node;
2311 if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2312 return unsignedp ? sat_unsigned_short_fract_type_node
2313 : unsigned_short_fract_type_node;
2314 if (mode == TYPE_MODE (unsigned_fract_type_node))
2315 return unsignedp ? sat_unsigned_fract_type_node
2316 : unsigned_fract_type_node;
2317 if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2318 return unsignedp ? sat_unsigned_long_fract_type_node
2319 : unsigned_long_fract_type_node;
2320 if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2321 return unsignedp ? sat_unsigned_long_long_fract_type_node
2322 : unsigned_long_long_fract_type_node;
2324 if (mode == TYPE_MODE (short_accum_type_node))
2325 return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2326 if (mode == TYPE_MODE (accum_type_node))
2327 return unsignedp ? sat_accum_type_node : accum_type_node;
2328 if (mode == TYPE_MODE (long_accum_type_node))
2329 return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2330 if (mode == TYPE_MODE (long_long_accum_type_node))
2331 return unsignedp ? sat_long_long_accum_type_node
2332 : long_long_accum_type_node;
2334 if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2335 return unsignedp ? sat_unsigned_short_accum_type_node
2336 : unsigned_short_accum_type_node;
2337 if (mode == TYPE_MODE (unsigned_accum_type_node))
2338 return unsignedp ? sat_unsigned_accum_type_node
2339 : unsigned_accum_type_node;
2340 if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2341 return unsignedp ? sat_unsigned_long_accum_type_node
2342 : unsigned_long_accum_type_node;
2343 if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2344 return unsignedp ? sat_unsigned_long_long_accum_type_node
2345 : unsigned_long_long_accum_type_node;
2347 if (mode == QQmode)
2348 return unsignedp ? sat_qq_type_node : qq_type_node;
2349 if (mode == HQmode)
2350 return unsignedp ? sat_hq_type_node : hq_type_node;
2351 if (mode == SQmode)
2352 return unsignedp ? sat_sq_type_node : sq_type_node;
2353 if (mode == DQmode)
2354 return unsignedp ? sat_dq_type_node : dq_type_node;
2355 if (mode == TQmode)
2356 return unsignedp ? sat_tq_type_node : tq_type_node;
2358 if (mode == UQQmode)
2359 return unsignedp ? sat_uqq_type_node : uqq_type_node;
2360 if (mode == UHQmode)
2361 return unsignedp ? sat_uhq_type_node : uhq_type_node;
2362 if (mode == USQmode)
2363 return unsignedp ? sat_usq_type_node : usq_type_node;
2364 if (mode == UDQmode)
2365 return unsignedp ? sat_udq_type_node : udq_type_node;
2366 if (mode == UTQmode)
2367 return unsignedp ? sat_utq_type_node : utq_type_node;
2369 if (mode == HAmode)
2370 return unsignedp ? sat_ha_type_node : ha_type_node;
2371 if (mode == SAmode)
2372 return unsignedp ? sat_sa_type_node : sa_type_node;
2373 if (mode == DAmode)
2374 return unsignedp ? sat_da_type_node : da_type_node;
2375 if (mode == TAmode)
2376 return unsignedp ? sat_ta_type_node : ta_type_node;
2378 if (mode == UHAmode)
2379 return unsignedp ? sat_uha_type_node : uha_type_node;
2380 if (mode == USAmode)
2381 return unsignedp ? sat_usa_type_node : usa_type_node;
2382 if (mode == UDAmode)
2383 return unsignedp ? sat_uda_type_node : uda_type_node;
2384 if (mode == UTAmode)
2385 return unsignedp ? sat_uta_type_node : uta_type_node;
2388 for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2389 if (TYPE_MODE (TREE_VALUE (t)) == mode
2390 && !!unsignedp == !!TYPE_UNSIGNED (TREE_VALUE (t)))
2391 return TREE_VALUE (t);
2393 return NULL_TREE;
2396 tree
2397 c_common_unsigned_type (tree type)
2399 return c_common_signed_or_unsigned_type (1, type);
2402 /* Return a signed type the same as TYPE in other respects. */
2404 tree
2405 c_common_signed_type (tree type)
2407 return c_common_signed_or_unsigned_type (0, type);
2410 /* Return a type the same as TYPE except unsigned or
2411 signed according to UNSIGNEDP. */
2413 tree
2414 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2416 tree type1;
2417 int i;
2419 /* This block of code emulates the behavior of the old
2420 c_common_unsigned_type. In particular, it returns
2421 long_unsigned_type_node if passed a long, even when a int would
2422 have the same size. This is necessary for warnings to work
2423 correctly in archs where sizeof(int) == sizeof(long) */
2425 type1 = TYPE_MAIN_VARIANT (type);
2426 if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2427 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2428 if (type1 == integer_type_node || type1 == unsigned_type_node)
2429 return unsignedp ? unsigned_type_node : integer_type_node;
2430 if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2431 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2432 if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2433 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2434 if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2435 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2437 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2438 if (int_n_enabled_p[i]
2439 && (type1 == int_n_trees[i].unsigned_type
2440 || type1 == int_n_trees[i].signed_type))
2441 return (unsignedp ? int_n_trees[i].unsigned_type
2442 : int_n_trees[i].signed_type);
2444 #if HOST_BITS_PER_WIDE_INT >= 64
2445 if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2446 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2447 #endif
2448 if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2449 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2450 if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2451 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2452 if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2453 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2454 if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2455 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2457 #define C_COMMON_FIXED_TYPES(NAME) \
2458 if (type1 == short_ ## NAME ## _type_node \
2459 || type1 == unsigned_short_ ## NAME ## _type_node) \
2460 return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2461 : short_ ## NAME ## _type_node; \
2462 if (type1 == NAME ## _type_node \
2463 || type1 == unsigned_ ## NAME ## _type_node) \
2464 return unsignedp ? unsigned_ ## NAME ## _type_node \
2465 : NAME ## _type_node; \
2466 if (type1 == long_ ## NAME ## _type_node \
2467 || type1 == unsigned_long_ ## NAME ## _type_node) \
2468 return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2469 : long_ ## NAME ## _type_node; \
2470 if (type1 == long_long_ ## NAME ## _type_node \
2471 || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2472 return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2473 : long_long_ ## NAME ## _type_node;
2475 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2476 if (type1 == NAME ## _type_node \
2477 || type1 == u ## NAME ## _type_node) \
2478 return unsignedp ? u ## NAME ## _type_node \
2479 : NAME ## _type_node;
2481 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2482 if (type1 == sat_ ## short_ ## NAME ## _type_node \
2483 || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2484 return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2485 : sat_ ## short_ ## NAME ## _type_node; \
2486 if (type1 == sat_ ## NAME ## _type_node \
2487 || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2488 return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2489 : sat_ ## NAME ## _type_node; \
2490 if (type1 == sat_ ## long_ ## NAME ## _type_node \
2491 || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2492 return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2493 : sat_ ## long_ ## NAME ## _type_node; \
2494 if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2495 || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2496 return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2497 : sat_ ## long_long_ ## NAME ## _type_node;
2499 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME) \
2500 if (type1 == sat_ ## NAME ## _type_node \
2501 || type1 == sat_ ## u ## NAME ## _type_node) \
2502 return unsignedp ? sat_ ## u ## NAME ## _type_node \
2503 : sat_ ## NAME ## _type_node;
2505 C_COMMON_FIXED_TYPES (fract);
2506 C_COMMON_FIXED_TYPES_SAT (fract);
2507 C_COMMON_FIXED_TYPES (accum);
2508 C_COMMON_FIXED_TYPES_SAT (accum);
2510 C_COMMON_FIXED_MODE_TYPES (qq);
2511 C_COMMON_FIXED_MODE_TYPES (hq);
2512 C_COMMON_FIXED_MODE_TYPES (sq);
2513 C_COMMON_FIXED_MODE_TYPES (dq);
2514 C_COMMON_FIXED_MODE_TYPES (tq);
2515 C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2516 C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2517 C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2518 C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2519 C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2520 C_COMMON_FIXED_MODE_TYPES (ha);
2521 C_COMMON_FIXED_MODE_TYPES (sa);
2522 C_COMMON_FIXED_MODE_TYPES (da);
2523 C_COMMON_FIXED_MODE_TYPES (ta);
2524 C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2525 C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2526 C_COMMON_FIXED_MODE_TYPES_SAT (da);
2527 C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2529 /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2530 the precision; they have precision set to match their range, but
2531 may use a wider mode to match an ABI. If we change modes, we may
2532 wind up with bad conversions. For INTEGER_TYPEs in C, must check
2533 the precision as well, so as to yield correct results for
2534 bit-field types. C++ does not have these separate bit-field
2535 types, and producing a signed or unsigned variant of an
2536 ENUMERAL_TYPE may cause other problems as well. */
2538 if (!INTEGRAL_TYPE_P (type)
2539 || TYPE_UNSIGNED (type) == unsignedp)
2540 return type;
2542 #define TYPE_OK(node) \
2543 (TYPE_MODE (type) == TYPE_MODE (node) \
2544 && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2545 if (TYPE_OK (signed_char_type_node))
2546 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2547 if (TYPE_OK (integer_type_node))
2548 return unsignedp ? unsigned_type_node : integer_type_node;
2549 if (TYPE_OK (short_integer_type_node))
2550 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2551 if (TYPE_OK (long_integer_type_node))
2552 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2553 if (TYPE_OK (long_long_integer_type_node))
2554 return (unsignedp ? long_long_unsigned_type_node
2555 : long_long_integer_type_node);
2557 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2558 if (int_n_enabled_p[i]
2559 && TYPE_MODE (type) == int_n_data[i].m
2560 && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2561 return (unsignedp ? int_n_trees[i].unsigned_type
2562 : int_n_trees[i].signed_type);
2564 #if HOST_BITS_PER_WIDE_INT >= 64
2565 if (TYPE_OK (intTI_type_node))
2566 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2567 #endif
2568 if (TYPE_OK (intDI_type_node))
2569 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2570 if (TYPE_OK (intSI_type_node))
2571 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2572 if (TYPE_OK (intHI_type_node))
2573 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2574 if (TYPE_OK (intQI_type_node))
2575 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2576 #undef TYPE_OK
2578 return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2581 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP. */
2583 tree
2584 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2586 int i;
2588 /* Extended integer types of the same width as a standard type have
2589 lesser rank, so those of the same width as int promote to int or
2590 unsigned int and are valid for printf formats expecting int or
2591 unsigned int. To avoid such special cases, avoid creating
2592 extended integer types for bit-fields if a standard integer type
2593 is available. */
2594 if (width == TYPE_PRECISION (integer_type_node))
2595 return unsignedp ? unsigned_type_node : integer_type_node;
2596 if (width == TYPE_PRECISION (signed_char_type_node))
2597 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2598 if (width == TYPE_PRECISION (short_integer_type_node))
2599 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2600 if (width == TYPE_PRECISION (long_integer_type_node))
2601 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2602 if (width == TYPE_PRECISION (long_long_integer_type_node))
2603 return (unsignedp ? long_long_unsigned_type_node
2604 : long_long_integer_type_node);
2605 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2606 if (int_n_enabled_p[i]
2607 && width == int_n_data[i].bitsize)
2608 return (unsignedp ? int_n_trees[i].unsigned_type
2609 : int_n_trees[i].signed_type);
2610 return build_nonstandard_integer_type (width, unsignedp);
2613 /* The C version of the register_builtin_type langhook. */
2615 void
2616 c_register_builtin_type (tree type, const char* name)
2618 tree decl;
2620 decl = build_decl (UNKNOWN_LOCATION,
2621 TYPE_DECL, get_identifier (name), type);
2622 DECL_ARTIFICIAL (decl) = 1;
2623 if (!TYPE_NAME (type))
2624 TYPE_NAME (type) = decl;
2625 lang_hooks.decls.pushdecl (decl);
2627 registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2630 /* Print an error message for invalid operands to arith operation
2631 CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2632 RICHLOC is a rich location for the message, containing either
2633 three separate locations for each of the operator and operands
2635 lhs op rhs
2636 ~~~ ^~ ~~~
2638 (C FE), or one location ranging over all over them
2640 lhs op rhs
2641 ~~~~^~~~~~
2643 (C++ FE). */
2645 void
2646 binary_op_error (rich_location *richloc, enum tree_code code,
2647 tree type0, tree type1)
2649 const char *opname;
2651 switch (code)
2653 case PLUS_EXPR:
2654 opname = "+"; break;
2655 case MINUS_EXPR:
2656 opname = "-"; break;
2657 case MULT_EXPR:
2658 opname = "*"; break;
2659 case MAX_EXPR:
2660 opname = "max"; break;
2661 case MIN_EXPR:
2662 opname = "min"; break;
2663 case EQ_EXPR:
2664 opname = "=="; break;
2665 case NE_EXPR:
2666 opname = "!="; break;
2667 case LE_EXPR:
2668 opname = "<="; break;
2669 case GE_EXPR:
2670 opname = ">="; break;
2671 case LT_EXPR:
2672 opname = "<"; break;
2673 case GT_EXPR:
2674 opname = ">"; break;
2675 case LSHIFT_EXPR:
2676 opname = "<<"; break;
2677 case RSHIFT_EXPR:
2678 opname = ">>"; break;
2679 case TRUNC_MOD_EXPR:
2680 case FLOOR_MOD_EXPR:
2681 opname = "%"; break;
2682 case TRUNC_DIV_EXPR:
2683 case FLOOR_DIV_EXPR:
2684 opname = "/"; break;
2685 case BIT_AND_EXPR:
2686 opname = "&"; break;
2687 case BIT_IOR_EXPR:
2688 opname = "|"; break;
2689 case TRUTH_ANDIF_EXPR:
2690 opname = "&&"; break;
2691 case TRUTH_ORIF_EXPR:
2692 opname = "||"; break;
2693 case BIT_XOR_EXPR:
2694 opname = "^"; break;
2695 default:
2696 gcc_unreachable ();
2698 error_at (richloc,
2699 "invalid operands to binary %s (have %qT and %qT)",
2700 opname, type0, type1);
2703 /* Given an expression as a tree, return its original type. Do this
2704 by stripping any conversion that preserves the sign and precision. */
2705 static tree
2706 expr_original_type (tree expr)
2708 STRIP_SIGN_NOPS (expr);
2709 return TREE_TYPE (expr);
2712 /* Subroutine of build_binary_op, used for comparison operations.
2713 See if the operands have both been converted from subword integer types
2714 and, if so, perhaps change them both back to their original type.
2715 This function is also responsible for converting the two operands
2716 to the proper common type for comparison.
2718 The arguments of this function are all pointers to local variables
2719 of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2720 RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2722 LOC is the location of the comparison.
2724 If this function returns non-NULL_TREE, it means that the comparison has
2725 a constant value. What this function returns is an expression for
2726 that value. */
2728 tree
2729 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2730 tree *restype_ptr, enum tree_code *rescode_ptr)
2732 tree type;
2733 tree op0 = *op0_ptr;
2734 tree op1 = *op1_ptr;
2735 int unsignedp0, unsignedp1;
2736 int real1, real2;
2737 tree primop0, primop1;
2738 enum tree_code code = *rescode_ptr;
2740 /* Throw away any conversions to wider types
2741 already present in the operands. */
2743 primop0 = c_common_get_narrower (op0, &unsignedp0);
2744 primop1 = c_common_get_narrower (op1, &unsignedp1);
2746 /* If primopN is first sign-extended from primopN's precision to opN's
2747 precision, then zero-extended from opN's precision to
2748 *restype_ptr precision, shortenings might be invalid. */
2749 if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2750 && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2751 && !unsignedp0
2752 && TYPE_UNSIGNED (TREE_TYPE (op0)))
2753 primop0 = op0;
2754 if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2755 && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2756 && !unsignedp1
2757 && TYPE_UNSIGNED (TREE_TYPE (op1)))
2758 primop1 = op1;
2760 /* Handle the case that OP0 does not *contain* a conversion
2761 but it *requires* conversion to FINAL_TYPE. */
2763 if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2764 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2765 if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2766 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2768 /* If one of the operands must be floated, we cannot optimize. */
2769 real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
2770 real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
2772 /* If first arg is constant, swap the args (changing operation
2773 so value is preserved), for canonicalization. Don't do this if
2774 the second arg is 0. */
2776 if (TREE_CONSTANT (primop0)
2777 && !integer_zerop (primop1) && !real_zerop (primop1)
2778 && !fixed_zerop (primop1))
2780 std::swap (primop0, primop1);
2781 std::swap (op0, op1);
2782 *op0_ptr = op0;
2783 *op1_ptr = op1;
2784 std::swap (unsignedp0, unsignedp1);
2785 std::swap (real1, real2);
2787 switch (code)
2789 case LT_EXPR:
2790 code = GT_EXPR;
2791 break;
2792 case GT_EXPR:
2793 code = LT_EXPR;
2794 break;
2795 case LE_EXPR:
2796 code = GE_EXPR;
2797 break;
2798 case GE_EXPR:
2799 code = LE_EXPR;
2800 break;
2801 default:
2802 break;
2804 *rescode_ptr = code;
2807 /* If comparing an integer against a constant more bits wide,
2808 maybe we can deduce a value of 1 or 0 independent of the data.
2809 Or else truncate the constant now
2810 rather than extend the variable at run time.
2812 This is only interesting if the constant is the wider arg.
2813 Also, it is not safe if the constant is unsigned and the
2814 variable arg is signed, since in this case the variable
2815 would be sign-extended and then regarded as unsigned.
2816 Our technique fails in this case because the lowest/highest
2817 possible unsigned results don't follow naturally from the
2818 lowest/highest possible values of the variable operand.
2819 For just EQ_EXPR and NE_EXPR there is another technique that
2820 could be used: see if the constant can be faithfully represented
2821 in the other operand's type, by truncating it and reextending it
2822 and see if that preserves the constant's value. */
2824 if (!real1 && !real2
2825 && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
2826 && TREE_CODE (primop1) == INTEGER_CST
2827 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
2829 int min_gt, max_gt, min_lt, max_lt;
2830 tree maxval, minval;
2831 /* 1 if comparison is nominally unsigned. */
2832 int unsignedp = TYPE_UNSIGNED (*restype_ptr);
2833 tree val;
2835 type = c_common_signed_or_unsigned_type (unsignedp0,
2836 TREE_TYPE (primop0));
2838 maxval = TYPE_MAX_VALUE (type);
2839 minval = TYPE_MIN_VALUE (type);
2841 if (unsignedp && !unsignedp0)
2842 *restype_ptr = c_common_signed_type (*restype_ptr);
2844 if (TREE_TYPE (primop1) != *restype_ptr)
2846 /* Convert primop1 to target type, but do not introduce
2847 additional overflow. We know primop1 is an int_cst. */
2848 primop1 = force_fit_type (*restype_ptr,
2849 wi::to_wide
2850 (primop1,
2851 TYPE_PRECISION (*restype_ptr)),
2852 0, TREE_OVERFLOW (primop1));
2854 if (type != *restype_ptr)
2856 minval = convert (*restype_ptr, minval);
2857 maxval = convert (*restype_ptr, maxval);
2860 min_gt = tree_int_cst_lt (primop1, minval);
2861 max_gt = tree_int_cst_lt (primop1, maxval);
2862 min_lt = tree_int_cst_lt (minval, primop1);
2863 max_lt = tree_int_cst_lt (maxval, primop1);
2865 val = 0;
2866 /* This used to be a switch, but Genix compiler can't handle that. */
2867 if (code == NE_EXPR)
2869 if (max_lt || min_gt)
2870 val = truthvalue_true_node;
2872 else if (code == EQ_EXPR)
2874 if (max_lt || min_gt)
2875 val = truthvalue_false_node;
2877 else if (code == LT_EXPR)
2879 if (max_lt)
2880 val = truthvalue_true_node;
2881 if (!min_lt)
2882 val = truthvalue_false_node;
2884 else if (code == GT_EXPR)
2886 if (min_gt)
2887 val = truthvalue_true_node;
2888 if (!max_gt)
2889 val = truthvalue_false_node;
2891 else if (code == LE_EXPR)
2893 if (!max_gt)
2894 val = truthvalue_true_node;
2895 if (min_gt)
2896 val = truthvalue_false_node;
2898 else if (code == GE_EXPR)
2900 if (!min_lt)
2901 val = truthvalue_true_node;
2902 if (max_lt)
2903 val = truthvalue_false_node;
2906 /* If primop0 was sign-extended and unsigned comparison specd,
2907 we did a signed comparison above using the signed type bounds.
2908 But the comparison we output must be unsigned.
2910 Also, for inequalities, VAL is no good; but if the signed
2911 comparison had *any* fixed result, it follows that the
2912 unsigned comparison just tests the sign in reverse
2913 (positive values are LE, negative ones GE).
2914 So we can generate an unsigned comparison
2915 against an extreme value of the signed type. */
2917 if (unsignedp && !unsignedp0)
2919 if (val != 0)
2920 switch (code)
2922 case LT_EXPR:
2923 case GE_EXPR:
2924 primop1 = TYPE_MIN_VALUE (type);
2925 val = 0;
2926 break;
2928 case LE_EXPR:
2929 case GT_EXPR:
2930 primop1 = TYPE_MAX_VALUE (type);
2931 val = 0;
2932 break;
2934 default:
2935 break;
2937 type = c_common_unsigned_type (type);
2940 if (TREE_CODE (primop0) != INTEGER_CST
2941 /* Don't warn if it's from a (non-system) macro. */
2942 && !(from_macro_expansion_at
2943 (expansion_point_location_if_in_system_header
2944 (EXPR_LOCATION (primop0)))))
2946 if (val == truthvalue_false_node)
2947 warning_at (loc, OPT_Wtype_limits,
2948 "comparison is always false due to limited range of data type");
2949 if (val == truthvalue_true_node)
2950 warning_at (loc, OPT_Wtype_limits,
2951 "comparison is always true due to limited range of data type");
2954 if (val != 0)
2956 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
2957 if (TREE_SIDE_EFFECTS (primop0))
2958 return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
2959 return val;
2962 /* Value is not predetermined, but do the comparison
2963 in the type of the operand that is not constant.
2964 TYPE is already properly set. */
2967 /* If either arg is decimal float and the other is float, find the
2968 proper common type to use for comparison. */
2969 else if (real1 && real2
2970 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2971 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
2972 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
2974 /* If either arg is decimal float and the other is float, fail. */
2975 else if (real1 && real2
2976 && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2977 || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
2978 return NULL_TREE;
2980 else if (real1 && real2
2981 && (TYPE_PRECISION (TREE_TYPE (primop0))
2982 == TYPE_PRECISION (TREE_TYPE (primop1))))
2983 type = TREE_TYPE (primop0);
2985 /* If args' natural types are both narrower than nominal type
2986 and both extend in the same manner, compare them
2987 in the type of the wider arg.
2988 Otherwise must actually extend both to the nominal
2989 common type lest different ways of extending
2990 alter the result.
2991 (eg, (short)-1 == (unsigned short)-1 should be 0.) */
2993 else if (unsignedp0 == unsignedp1 && real1 == real2
2994 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
2995 && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
2997 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
2998 type = c_common_signed_or_unsigned_type (unsignedp0
2999 || TYPE_UNSIGNED (*restype_ptr),
3000 type);
3001 /* Make sure shorter operand is extended the right way
3002 to match the longer operand. */
3003 primop0
3004 = convert (c_common_signed_or_unsigned_type (unsignedp0,
3005 TREE_TYPE (primop0)),
3006 primop0);
3007 primop1
3008 = convert (c_common_signed_or_unsigned_type (unsignedp1,
3009 TREE_TYPE (primop1)),
3010 primop1);
3012 else
3014 /* Here we must do the comparison on the nominal type
3015 using the args exactly as we received them. */
3016 type = *restype_ptr;
3017 primop0 = op0;
3018 primop1 = op1;
3020 if (!real1 && !real2 && integer_zerop (primop1)
3021 && TYPE_UNSIGNED (*restype_ptr))
3023 tree value = NULL_TREE;
3024 /* All unsigned values are >= 0, so we warn. However,
3025 if OP0 is a constant that is >= 0, the signedness of
3026 the comparison isn't an issue, so suppress the
3027 warning. */
3028 bool warn =
3029 warn_type_limits && !in_system_header_at (loc)
3030 && !(TREE_CODE (primop0) == INTEGER_CST
3031 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3032 primop0)))
3033 /* Do not warn for enumeration types. */
3034 && (TREE_CODE (expr_original_type (primop0)) != ENUMERAL_TYPE);
3036 switch (code)
3038 case GE_EXPR:
3039 if (warn)
3040 warning_at (loc, OPT_Wtype_limits,
3041 "comparison of unsigned expression >= 0 is always true");
3042 value = truthvalue_true_node;
3043 break;
3045 case LT_EXPR:
3046 if (warn)
3047 warning_at (loc, OPT_Wtype_limits,
3048 "comparison of unsigned expression < 0 is always false");
3049 value = truthvalue_false_node;
3050 break;
3052 default:
3053 break;
3056 if (value != NULL_TREE)
3058 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3059 if (TREE_SIDE_EFFECTS (primop0))
3060 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3061 primop0, value);
3062 return value;
3067 *op0_ptr = convert (type, primop0);
3068 *op1_ptr = convert (type, primop1);
3070 *restype_ptr = truthvalue_type_node;
3072 return NULL_TREE;
3075 /* Return a tree for the sum or difference (RESULTCODE says which)
3076 of pointer PTROP and integer INTOP. */
3078 tree
3079 pointer_int_sum (location_t loc, enum tree_code resultcode,
3080 tree ptrop, tree intop, bool complain)
3082 tree size_exp, ret;
3084 /* The result is a pointer of the same type that is being added. */
3085 tree result_type = TREE_TYPE (ptrop);
3087 if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
3089 if (complain && warn_pointer_arith)
3090 pedwarn (loc, OPT_Wpointer_arith,
3091 "pointer of type %<void *%> used in arithmetic");
3092 else if (!complain)
3093 return error_mark_node;
3094 size_exp = integer_one_node;
3096 else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3098 if (complain && warn_pointer_arith)
3099 pedwarn (loc, OPT_Wpointer_arith,
3100 "pointer to a function used in arithmetic");
3101 else if (!complain)
3102 return error_mark_node;
3103 size_exp = integer_one_node;
3105 else
3106 size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3108 /* We are manipulating pointer values, so we don't need to warn
3109 about relying on undefined signed overflow. We disable the
3110 warning here because we use integer types so fold won't know that
3111 they are really pointers. */
3112 fold_defer_overflow_warnings ();
3114 /* If what we are about to multiply by the size of the elements
3115 contains a constant term, apply distributive law
3116 and multiply that constant term separately.
3117 This helps produce common subexpressions. */
3118 if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3119 && !TREE_CONSTANT (intop)
3120 && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3121 && TREE_CONSTANT (size_exp)
3122 /* If the constant comes from pointer subtraction,
3123 skip this optimization--it would cause an error. */
3124 && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3125 /* If the constant is unsigned, and smaller than the pointer size,
3126 then we must skip this optimization. This is because it could cause
3127 an overflow error if the constant is negative but INTOP is not. */
3128 && (!TYPE_UNSIGNED (TREE_TYPE (intop))
3129 || (TYPE_PRECISION (TREE_TYPE (intop))
3130 == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3132 enum tree_code subcode = resultcode;
3133 tree int_type = TREE_TYPE (intop);
3134 if (TREE_CODE (intop) == MINUS_EXPR)
3135 subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3136 /* Convert both subexpression types to the type of intop,
3137 because weird cases involving pointer arithmetic
3138 can result in a sum or difference with different type args. */
3139 ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3140 subcode, ptrop,
3141 convert (int_type, TREE_OPERAND (intop, 1)),
3142 true);
3143 intop = convert (int_type, TREE_OPERAND (intop, 0));
3146 /* Convert the integer argument to a type the same size as sizetype
3147 so the multiply won't overflow spuriously. */
3148 if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3149 || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3150 intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3151 TYPE_UNSIGNED (sizetype)), intop);
3153 /* Replace the integer argument with a suitable product by the object size.
3154 Do this multiplication as signed, then convert to the appropriate type
3155 for the pointer operation and disregard an overflow that occurred only
3156 because of the sign-extension change in the latter conversion. */
3158 tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3159 convert (TREE_TYPE (intop), size_exp));
3160 intop = convert (sizetype, t);
3161 if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3162 intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3165 /* Create the sum or difference. */
3166 if (resultcode == MINUS_EXPR)
3167 intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3169 ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3171 fold_undefer_and_ignore_overflow_warnings ();
3173 return ret;
3176 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3177 and if NON_CONST is known not to be permitted in an evaluated part
3178 of a constant expression. */
3180 tree
3181 c_wrap_maybe_const (tree expr, bool non_const)
3183 bool nowarning = TREE_NO_WARNING (expr);
3184 location_t loc = EXPR_LOCATION (expr);
3186 /* This should never be called for C++. */
3187 if (c_dialect_cxx ())
3188 gcc_unreachable ();
3190 /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING. */
3191 STRIP_TYPE_NOPS (expr);
3192 expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3193 C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3194 if (nowarning)
3195 TREE_NO_WARNING (expr) = 1;
3196 protected_set_expr_location (expr, loc);
3198 return expr;
3201 /* Return whether EXPR is a declaration whose address can never be
3202 NULL. */
3204 bool
3205 decl_with_nonnull_addr_p (const_tree expr)
3207 return (DECL_P (expr)
3208 && (TREE_CODE (expr) == PARM_DECL
3209 || TREE_CODE (expr) == LABEL_DECL
3210 || !DECL_WEAK (expr)));
3213 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3214 or for an `if' or `while' statement or ?..: exp. It should already
3215 have been validated to be of suitable type; otherwise, a bad
3216 diagnostic may result.
3218 The EXPR is located at LOCATION.
3220 This preparation consists of taking the ordinary
3221 representation of an expression expr and producing a valid tree
3222 boolean expression describing whether expr is nonzero. We could
3223 simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3224 but we optimize comparisons, &&, ||, and !.
3226 The resulting type should always be `truthvalue_type_node'. */
3228 tree
3229 c_common_truthvalue_conversion (location_t location, tree expr)
3231 switch (TREE_CODE (expr))
3233 case EQ_EXPR: case NE_EXPR: case UNEQ_EXPR: case LTGT_EXPR:
3234 case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
3235 case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3236 case ORDERED_EXPR: case UNORDERED_EXPR:
3237 if (TREE_TYPE (expr) == truthvalue_type_node)
3238 return expr;
3239 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3240 TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3241 goto ret;
3243 case TRUTH_ANDIF_EXPR:
3244 case TRUTH_ORIF_EXPR:
3245 case TRUTH_AND_EXPR:
3246 case TRUTH_OR_EXPR:
3247 case TRUTH_XOR_EXPR:
3248 if (TREE_TYPE (expr) == truthvalue_type_node)
3249 return expr;
3250 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3251 c_common_truthvalue_conversion (location,
3252 TREE_OPERAND (expr, 0)),
3253 c_common_truthvalue_conversion (location,
3254 TREE_OPERAND (expr, 1)));
3255 goto ret;
3257 case TRUTH_NOT_EXPR:
3258 if (TREE_TYPE (expr) == truthvalue_type_node)
3259 return expr;
3260 expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3261 c_common_truthvalue_conversion (location,
3262 TREE_OPERAND (expr, 0)));
3263 goto ret;
3265 case ERROR_MARK:
3266 return expr;
3268 case INTEGER_CST:
3269 if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3270 && !integer_zerop (expr)
3271 && !integer_onep (expr))
3272 warning_at (location, OPT_Wint_in_bool_context,
3273 "enum constant in boolean context");
3274 return integer_zerop (expr) ? truthvalue_false_node
3275 : truthvalue_true_node;
3277 case REAL_CST:
3278 return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3279 ? truthvalue_true_node
3280 : truthvalue_false_node;
3282 case FIXED_CST:
3283 return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3284 &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3285 ? truthvalue_true_node
3286 : truthvalue_false_node;
3288 case FUNCTION_DECL:
3289 expr = build_unary_op (location, ADDR_EXPR, expr, false);
3290 /* Fall through. */
3292 case ADDR_EXPR:
3294 tree inner = TREE_OPERAND (expr, 0);
3295 if (decl_with_nonnull_addr_p (inner))
3297 /* Common Ada/Pascal programmer's mistake. */
3298 warning_at (location,
3299 OPT_Waddress,
3300 "the address of %qD will always evaluate as %<true%>",
3301 inner);
3302 return truthvalue_true_node;
3304 break;
3307 case COMPLEX_EXPR:
3308 expr = build_binary_op (EXPR_LOCATION (expr),
3309 (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3310 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3311 c_common_truthvalue_conversion (location,
3312 TREE_OPERAND (expr, 0)),
3313 c_common_truthvalue_conversion (location,
3314 TREE_OPERAND (expr, 1)),
3315 false);
3316 goto ret;
3318 case NEGATE_EXPR:
3319 case ABS_EXPR:
3320 case FLOAT_EXPR:
3321 case EXCESS_PRECISION_EXPR:
3322 /* These don't change whether an object is nonzero or zero. */
3323 return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3325 case LROTATE_EXPR:
3326 case RROTATE_EXPR:
3327 /* These don't change whether an object is zero or nonzero, but
3328 we can't ignore them if their second arg has side-effects. */
3329 if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3331 expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3332 TREE_OPERAND (expr, 1),
3333 c_common_truthvalue_conversion
3334 (location, TREE_OPERAND (expr, 0)));
3335 goto ret;
3337 else
3338 return c_common_truthvalue_conversion (location,
3339 TREE_OPERAND (expr, 0));
3341 case MULT_EXPR:
3342 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3343 "%<*%> in boolean context, suggest %<&&%> instead");
3344 break;
3346 case LSHIFT_EXPR:
3347 /* We will only warn on signed shifts here, because the majority of
3348 false positive warnings happen in code where unsigned arithmetic
3349 was used in anticipation of a possible overflow.
3350 Furthermore, if we see an unsigned type here we know that the
3351 result of the shift is not subject to integer promotion rules. */
3352 if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3353 && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3354 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3355 "%<<<%> in boolean context, did you mean %<<%> ?");
3356 break;
3358 case COND_EXPR:
3359 if (warn_int_in_bool_context
3360 && !from_macro_definition_at (EXPR_LOCATION (expr)))
3362 tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3363 tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3364 if (TREE_CODE (val1) == INTEGER_CST
3365 && TREE_CODE (val2) == INTEGER_CST
3366 && !integer_zerop (val1)
3367 && !integer_zerop (val2)
3368 && (!integer_onep (val1)
3369 || !integer_onep (val2)))
3370 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3371 "?: using integer constants in boolean context, "
3372 "the expression will always evaluate to %<true%>");
3373 else if ((TREE_CODE (val1) == INTEGER_CST
3374 && !integer_zerop (val1)
3375 && !integer_onep (val1))
3376 || (TREE_CODE (val2) == INTEGER_CST
3377 && !integer_zerop (val2)
3378 && !integer_onep (val2)))
3379 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3380 "?: using integer constants in boolean context");
3382 /* Distribute the conversion into the arms of a COND_EXPR. */
3383 if (c_dialect_cxx ())
3384 /* Avoid premature folding. */
3385 break;
3386 else
3388 int w = warn_int_in_bool_context;
3389 warn_int_in_bool_context = 0;
3390 /* Folding will happen later for C. */
3391 expr = build3 (COND_EXPR, truthvalue_type_node,
3392 TREE_OPERAND (expr, 0),
3393 c_common_truthvalue_conversion (location,
3394 TREE_OPERAND (expr, 1)),
3395 c_common_truthvalue_conversion (location,
3396 TREE_OPERAND (expr, 2)));
3397 warn_int_in_bool_context = w;
3398 goto ret;
3401 CASE_CONVERT:
3403 tree totype = TREE_TYPE (expr);
3404 tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3406 if (POINTER_TYPE_P (totype)
3407 && !c_inhibit_evaluation_warnings
3408 && TREE_CODE (fromtype) == REFERENCE_TYPE)
3410 tree inner = expr;
3411 STRIP_NOPS (inner);
3413 if (DECL_P (inner))
3414 warning_at (location,
3415 OPT_Waddress,
3416 "the compiler can assume that the address of "
3417 "%qD will always evaluate to %<true%>",
3418 inner);
3421 /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3422 since that affects how `default_conversion' will behave. */
3423 if (TREE_CODE (totype) == REFERENCE_TYPE
3424 || TREE_CODE (fromtype) == REFERENCE_TYPE)
3425 break;
3426 /* Don't strip a conversion from C++0x scoped enum, since they
3427 don't implicitly convert to other types. */
3428 if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3429 && ENUM_IS_SCOPED (fromtype))
3430 break;
3431 /* If this isn't narrowing the argument, we can ignore it. */
3432 if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3433 return c_common_truthvalue_conversion (location,
3434 TREE_OPERAND (expr, 0));
3436 break;
3438 case MODIFY_EXPR:
3439 if (!TREE_NO_WARNING (expr)
3440 && warn_parentheses)
3442 warning_at (location, OPT_Wparentheses,
3443 "suggest parentheses around assignment used as "
3444 "truth value");
3445 TREE_NO_WARNING (expr) = 1;
3447 break;
3449 default:
3450 break;
3453 if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3455 tree t = save_expr (expr);
3456 expr = (build_binary_op
3457 (EXPR_LOCATION (expr),
3458 (TREE_SIDE_EFFECTS (expr)
3459 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3460 c_common_truthvalue_conversion
3461 (location,
3462 build_unary_op (location, REALPART_EXPR, t, false)),
3463 c_common_truthvalue_conversion
3464 (location,
3465 build_unary_op (location, IMAGPART_EXPR, t, false)),
3466 false));
3467 goto ret;
3470 if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
3472 tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3473 FCONST0 (TYPE_MODE
3474 (TREE_TYPE (expr))));
3475 return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3477 else
3478 return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3480 ret:
3481 protected_set_expr_location (expr, location);
3482 return expr;
3485 static void def_builtin_1 (enum built_in_function fncode,
3486 const char *name,
3487 enum built_in_class fnclass,
3488 tree fntype, tree libtype,
3489 bool both_p, bool fallback_p, bool nonansi_p,
3490 tree fnattrs, bool implicit_p);
3493 /* Apply the TYPE_QUALS to the new DECL. */
3495 void
3496 c_apply_type_quals_to_decl (int type_quals, tree decl)
3498 tree type = TREE_TYPE (decl);
3500 if (type == error_mark_node)
3501 return;
3503 if ((type_quals & TYPE_QUAL_CONST)
3504 || (type && TREE_CODE (type) == REFERENCE_TYPE))
3505 /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3506 constructor can produce constant init, so rely on cp_finish_decl to
3507 clear TREE_READONLY if the variable has non-constant init. */
3508 TREE_READONLY (decl) = 1;
3509 if (type_quals & TYPE_QUAL_VOLATILE)
3511 TREE_SIDE_EFFECTS (decl) = 1;
3512 TREE_THIS_VOLATILE (decl) = 1;
3514 if (type_quals & TYPE_QUAL_RESTRICT)
3516 while (type && TREE_CODE (type) == ARRAY_TYPE)
3517 /* Allow 'restrict' on arrays of pointers.
3518 FIXME currently we just ignore it. */
3519 type = TREE_TYPE (type);
3520 if (!type
3521 || !POINTER_TYPE_P (type)
3522 || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3523 error ("invalid use of %<restrict%>");
3527 /* Return the typed-based alias set for T, which may be an expression
3528 or a type. Return -1 if we don't do anything special. */
3530 alias_set_type
3531 c_common_get_alias_set (tree t)
3533 /* For VLAs, use the alias set of the element type rather than the
3534 default of alias set 0 for types compared structurally. */
3535 if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3537 if (TREE_CODE (t) == ARRAY_TYPE)
3538 return get_alias_set (TREE_TYPE (t));
3539 return -1;
3542 /* That's all the expressions we handle specially. */
3543 if (!TYPE_P (t))
3544 return -1;
3546 /* The C standard guarantees that any object may be accessed via an
3547 lvalue that has character type. */
3548 if (t == char_type_node
3549 || t == signed_char_type_node
3550 || t == unsigned_char_type_node)
3551 return 0;
3553 /* The C standard specifically allows aliasing between signed and
3554 unsigned variants of the same type. We treat the signed
3555 variant as canonical. */
3556 if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
3558 tree t1 = c_common_signed_type (t);
3560 /* t1 == t can happen for boolean nodes which are always unsigned. */
3561 if (t1 != t)
3562 return get_alias_set (t1);
3565 return -1;
3568 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3569 the IS_SIZEOF parameter indicates which operator is being applied.
3570 The COMPLAIN flag controls whether we should diagnose possibly
3571 ill-formed constructs or not. LOC is the location of the SIZEOF or
3572 TYPEOF operator. If MIN_ALIGNOF, the least alignment required for
3573 a type in any context should be returned, rather than the normal
3574 alignment for that type. */
3576 tree
3577 c_sizeof_or_alignof_type (location_t loc,
3578 tree type, bool is_sizeof, bool min_alignof,
3579 int complain)
3581 const char *op_name;
3582 tree value = NULL;
3583 enum tree_code type_code = TREE_CODE (type);
3585 op_name = is_sizeof ? "sizeof" : "__alignof__";
3587 if (type_code == FUNCTION_TYPE)
3589 if (is_sizeof)
3591 if (complain && warn_pointer_arith)
3592 pedwarn (loc, OPT_Wpointer_arith,
3593 "invalid application of %<sizeof%> to a function type");
3594 else if (!complain)
3595 return error_mark_node;
3596 value = size_one_node;
3598 else
3600 if (complain)
3602 if (c_dialect_cxx ())
3603 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3604 "%<alignof%> applied to a function type");
3605 else
3606 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3607 "%<_Alignof%> applied to a function type");
3609 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3612 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3614 if (type_code == VOID_TYPE
3615 && complain && warn_pointer_arith)
3616 pedwarn (loc, OPT_Wpointer_arith,
3617 "invalid application of %qs to a void type", op_name);
3618 else if (!complain)
3619 return error_mark_node;
3620 value = size_one_node;
3622 else if (!COMPLETE_TYPE_P (type)
3623 && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3625 if (complain)
3626 error_at (loc, "invalid application of %qs to incomplete type %qT",
3627 op_name, type);
3628 return error_mark_node;
3630 else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3631 && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3633 if (complain)
3634 error_at (loc, "invalid application of %qs to array type %qT of "
3635 "incomplete element type", op_name, type);
3636 return error_mark_node;
3638 else
3640 if (is_sizeof)
3641 /* Convert in case a char is more than one unit. */
3642 value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3643 size_int (TYPE_PRECISION (char_type_node)
3644 / BITS_PER_UNIT));
3645 else if (min_alignof)
3646 value = size_int (min_align_of_type (type));
3647 else
3648 value = size_int (TYPE_ALIGN_UNIT (type));
3651 /* VALUE will have the middle-end integer type sizetype.
3652 However, we should really return a value of type `size_t',
3653 which is just a typedef for an ordinary integer type. */
3654 value = fold_convert_loc (loc, size_type_node, value);
3656 return value;
3659 /* Implement the __alignof keyword: Return the minimum required
3660 alignment of EXPR, measured in bytes. For VAR_DECLs,
3661 FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3662 from an "aligned" __attribute__ specification). LOC is the
3663 location of the ALIGNOF operator. */
3665 tree
3666 c_alignof_expr (location_t loc, tree expr)
3668 tree t;
3670 if (VAR_OR_FUNCTION_DECL_P (expr))
3671 t = size_int (DECL_ALIGN_UNIT (expr));
3673 else if (TREE_CODE (expr) == COMPONENT_REF
3674 && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3676 error_at (loc, "%<__alignof%> applied to a bit-field");
3677 t = size_one_node;
3679 else if (TREE_CODE (expr) == COMPONENT_REF
3680 && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3681 t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3683 else if (INDIRECT_REF_P (expr))
3685 tree t = TREE_OPERAND (expr, 0);
3686 tree best = t;
3687 int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3689 while (CONVERT_EXPR_P (t)
3690 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3692 int thisalign;
3694 t = TREE_OPERAND (t, 0);
3695 thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3696 if (thisalign > bestalign)
3697 best = t, bestalign = thisalign;
3699 return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
3701 else
3702 return c_alignof (loc, TREE_TYPE (expr));
3704 return fold_convert_loc (loc, size_type_node, t);
3707 /* Handle C and C++ default attributes. */
3709 enum built_in_attribute
3711 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
3712 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
3713 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
3714 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
3715 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
3716 #include "builtin-attrs.def"
3717 #undef DEF_ATTR_NULL_TREE
3718 #undef DEF_ATTR_INT
3719 #undef DEF_ATTR_STRING
3720 #undef DEF_ATTR_IDENT
3721 #undef DEF_ATTR_TREE_LIST
3722 ATTR_LAST
3725 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
3727 static void c_init_attributes (void);
3729 enum c_builtin_type
3731 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
3732 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
3733 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
3734 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
3735 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3736 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3737 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
3738 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3739 ARG6) NAME,
3740 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3741 ARG6, ARG7) NAME,
3742 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3743 ARG6, ARG7, ARG8) NAME,
3744 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3745 ARG6, ARG7, ARG8, ARG9) NAME,
3746 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3747 ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
3748 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3749 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
3750 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
3751 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
3752 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
3753 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3754 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3755 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3756 NAME,
3757 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3758 ARG6) NAME,
3759 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3760 ARG6, ARG7) NAME,
3761 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
3762 #include "builtin-types.def"
3763 #undef DEF_PRIMITIVE_TYPE
3764 #undef DEF_FUNCTION_TYPE_0
3765 #undef DEF_FUNCTION_TYPE_1
3766 #undef DEF_FUNCTION_TYPE_2
3767 #undef DEF_FUNCTION_TYPE_3
3768 #undef DEF_FUNCTION_TYPE_4
3769 #undef DEF_FUNCTION_TYPE_5
3770 #undef DEF_FUNCTION_TYPE_6
3771 #undef DEF_FUNCTION_TYPE_7
3772 #undef DEF_FUNCTION_TYPE_8
3773 #undef DEF_FUNCTION_TYPE_9
3774 #undef DEF_FUNCTION_TYPE_10
3775 #undef DEF_FUNCTION_TYPE_11
3776 #undef DEF_FUNCTION_TYPE_VAR_0
3777 #undef DEF_FUNCTION_TYPE_VAR_1
3778 #undef DEF_FUNCTION_TYPE_VAR_2
3779 #undef DEF_FUNCTION_TYPE_VAR_3
3780 #undef DEF_FUNCTION_TYPE_VAR_4
3781 #undef DEF_FUNCTION_TYPE_VAR_5
3782 #undef DEF_FUNCTION_TYPE_VAR_6
3783 #undef DEF_FUNCTION_TYPE_VAR_7
3784 #undef DEF_POINTER_TYPE
3785 BT_LAST
3788 typedef enum c_builtin_type builtin_type;
3790 /* A temporary array for c_common_nodes_and_builtins. Used in
3791 communication with def_fn_type. */
3792 static tree builtin_types[(int) BT_LAST + 1];
3794 /* A helper function for c_common_nodes_and_builtins. Build function type
3795 for DEF with return type RET and N arguments. If VAR is true, then the
3796 function should be variadic after those N arguments.
3798 Takes special care not to ICE if any of the types involved are
3799 error_mark_node, which indicates that said type is not in fact available
3800 (see builtin_type_for_size). In which case the function type as a whole
3801 should be error_mark_node. */
3803 static void
3804 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
3806 tree t;
3807 tree *args = XALLOCAVEC (tree, n);
3808 va_list list;
3809 int i;
3811 va_start (list, n);
3812 for (i = 0; i < n; ++i)
3814 builtin_type a = (builtin_type) va_arg (list, int);
3815 t = builtin_types[a];
3816 if (t == error_mark_node)
3817 goto egress;
3818 args[i] = t;
3821 t = builtin_types[ret];
3822 if (t == error_mark_node)
3823 goto egress;
3824 if (var)
3825 t = build_varargs_function_type_array (t, n, args);
3826 else
3827 t = build_function_type_array (t, n, args);
3829 egress:
3830 builtin_types[def] = t;
3831 va_end (list);
3834 /* Build builtin functions common to both C and C++ language
3835 frontends. */
3837 static void
3838 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
3840 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
3841 builtin_types[ENUM] = VALUE;
3842 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
3843 def_fn_type (ENUM, RETURN, 0, 0);
3844 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
3845 def_fn_type (ENUM, RETURN, 0, 1, ARG1);
3846 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
3847 def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
3848 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3849 def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
3850 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3851 def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
3852 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3853 def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3854 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3855 ARG6) \
3856 def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3857 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3858 ARG6, ARG7) \
3859 def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3860 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3861 ARG6, ARG7, ARG8) \
3862 def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3863 ARG7, ARG8);
3864 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3865 ARG6, ARG7, ARG8, ARG9) \
3866 def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3867 ARG7, ARG8, ARG9);
3868 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3869 ARG6, ARG7, ARG8, ARG9, ARG10) \
3870 def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3871 ARG7, ARG8, ARG9, ARG10);
3872 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3873 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
3874 def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3875 ARG7, ARG8, ARG9, ARG10, ARG11);
3876 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
3877 def_fn_type (ENUM, RETURN, 1, 0);
3878 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
3879 def_fn_type (ENUM, RETURN, 1, 1, ARG1);
3880 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
3881 def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
3882 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3883 def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
3884 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3885 def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
3886 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3887 def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3888 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3889 ARG6) \
3890 def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3891 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3892 ARG6, ARG7) \
3893 def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3894 #define DEF_POINTER_TYPE(ENUM, TYPE) \
3895 builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
3897 #include "builtin-types.def"
3899 #undef DEF_PRIMITIVE_TYPE
3900 #undef DEF_FUNCTION_TYPE_0
3901 #undef DEF_FUNCTION_TYPE_1
3902 #undef DEF_FUNCTION_TYPE_2
3903 #undef DEF_FUNCTION_TYPE_3
3904 #undef DEF_FUNCTION_TYPE_4
3905 #undef DEF_FUNCTION_TYPE_5
3906 #undef DEF_FUNCTION_TYPE_6
3907 #undef DEF_FUNCTION_TYPE_7
3908 #undef DEF_FUNCTION_TYPE_8
3909 #undef DEF_FUNCTION_TYPE_9
3910 #undef DEF_FUNCTION_TYPE_10
3911 #undef DEF_FUNCTION_TYPE_11
3912 #undef DEF_FUNCTION_TYPE_VAR_0
3913 #undef DEF_FUNCTION_TYPE_VAR_1
3914 #undef DEF_FUNCTION_TYPE_VAR_2
3915 #undef DEF_FUNCTION_TYPE_VAR_3
3916 #undef DEF_FUNCTION_TYPE_VAR_4
3917 #undef DEF_FUNCTION_TYPE_VAR_5
3918 #undef DEF_FUNCTION_TYPE_VAR_6
3919 #undef DEF_FUNCTION_TYPE_VAR_7
3920 #undef DEF_POINTER_TYPE
3921 builtin_types[(int) BT_LAST] = NULL_TREE;
3923 c_init_attributes ();
3925 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
3926 NONANSI_P, ATTRS, IMPLICIT, COND) \
3927 if (NAME && COND) \
3928 def_builtin_1 (ENUM, NAME, CLASS, \
3929 builtin_types[(int) TYPE], \
3930 builtin_types[(int) LIBTYPE], \
3931 BOTH_P, FALLBACK_P, NONANSI_P, \
3932 built_in_attributes[(int) ATTRS], IMPLICIT);
3933 #include "builtins.def"
3935 targetm.init_builtins ();
3937 build_common_builtin_nodes ();
3939 if (flag_cilkplus)
3940 cilk_init_builtins ();
3943 /* Like get_identifier, but avoid warnings about null arguments when
3944 the argument may be NULL for targets where GCC lacks stdint.h type
3945 information. */
3947 static inline tree
3948 c_get_ident (const char *id)
3950 return get_identifier (id);
3953 /* Build tree nodes and builtin functions common to both C and C++ language
3954 frontends. */
3956 void
3957 c_common_nodes_and_builtins (void)
3959 int char16_type_size;
3960 int char32_type_size;
3961 int wchar_type_size;
3962 tree array_domain_type;
3963 tree va_list_ref_type_node;
3964 tree va_list_arg_type_node;
3965 int i;
3967 build_common_tree_nodes (flag_signed_char);
3969 /* Define `int' and `char' first so that dbx will output them first. */
3970 record_builtin_type (RID_INT, NULL, integer_type_node);
3971 record_builtin_type (RID_CHAR, "char", char_type_node);
3973 /* `signed' is the same as `int'. FIXME: the declarations of "signed",
3974 "unsigned long", "long long unsigned" and "unsigned short" were in C++
3975 but not C. Are the conditionals here needed? */
3976 if (c_dialect_cxx ())
3977 record_builtin_type (RID_SIGNED, NULL, integer_type_node);
3978 record_builtin_type (RID_LONG, "long int", long_integer_type_node);
3979 record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
3980 record_builtin_type (RID_MAX, "long unsigned int",
3981 long_unsigned_type_node);
3983 for (i = 0; i < NUM_INT_N_ENTS; i ++)
3985 char name[25];
3987 sprintf (name, "__int%d", int_n_data[i].bitsize);
3988 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
3989 int_n_trees[i].signed_type);
3990 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
3991 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
3994 if (c_dialect_cxx ())
3995 record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
3996 record_builtin_type (RID_MAX, "long long int",
3997 long_long_integer_type_node);
3998 record_builtin_type (RID_MAX, "long long unsigned int",
3999 long_long_unsigned_type_node);
4000 if (c_dialect_cxx ())
4001 record_builtin_type (RID_MAX, "long long unsigned",
4002 long_long_unsigned_type_node);
4003 record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4004 record_builtin_type (RID_MAX, "short unsigned int",
4005 short_unsigned_type_node);
4006 if (c_dialect_cxx ())
4007 record_builtin_type (RID_MAX, "unsigned short",
4008 short_unsigned_type_node);
4010 /* Define both `signed char' and `unsigned char'. */
4011 record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4012 record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4014 /* These are types that c_common_type_for_size and
4015 c_common_type_for_mode use. */
4016 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4017 TYPE_DECL, NULL_TREE,
4018 intQI_type_node));
4019 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4020 TYPE_DECL, NULL_TREE,
4021 intHI_type_node));
4022 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4023 TYPE_DECL, NULL_TREE,
4024 intSI_type_node));
4025 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4026 TYPE_DECL, NULL_TREE,
4027 intDI_type_node));
4028 #if HOST_BITS_PER_WIDE_INT >= 64
4029 /* Note that this is different than the __int128 type that's part of
4030 the generic __intN support. */
4031 if (targetm.scalar_mode_supported_p (TImode))
4032 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4033 TYPE_DECL,
4034 get_identifier ("__int128_t"),
4035 intTI_type_node));
4036 #endif
4037 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4038 TYPE_DECL, NULL_TREE,
4039 unsigned_intQI_type_node));
4040 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4041 TYPE_DECL, NULL_TREE,
4042 unsigned_intHI_type_node));
4043 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4044 TYPE_DECL, NULL_TREE,
4045 unsigned_intSI_type_node));
4046 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4047 TYPE_DECL, NULL_TREE,
4048 unsigned_intDI_type_node));
4049 #if HOST_BITS_PER_WIDE_INT >= 64
4050 if (targetm.scalar_mode_supported_p (TImode))
4051 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4052 TYPE_DECL,
4053 get_identifier ("__uint128_t"),
4054 unsigned_intTI_type_node));
4055 #endif
4057 /* Create the widest literal types. */
4058 if (targetm.scalar_mode_supported_p (TImode))
4060 widest_integer_literal_type_node = intTI_type_node;
4061 widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4063 else
4065 widest_integer_literal_type_node = intDI_type_node;
4066 widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4069 signed_size_type_node = c_common_signed_type (size_type_node);
4071 pid_type_node =
4072 TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4074 record_builtin_type (RID_FLOAT, NULL, float_type_node);
4075 record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4076 record_builtin_type (RID_MAX, "long double", long_double_type_node);
4078 if (!c_dialect_cxx ())
4079 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4080 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4081 record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4082 FLOATN_NX_TYPE_NODE (i));
4084 /* Only supported decimal floating point extension if the target
4085 actually supports underlying modes. */
4086 if (targetm.scalar_mode_supported_p (SDmode)
4087 && targetm.scalar_mode_supported_p (DDmode)
4088 && targetm.scalar_mode_supported_p (TDmode))
4090 record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4091 record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4092 record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4095 if (targetm.fixed_point_supported_p ())
4097 record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4098 record_builtin_type (RID_FRACT, NULL, fract_type_node);
4099 record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4100 record_builtin_type (RID_MAX, "long long _Fract",
4101 long_long_fract_type_node);
4102 record_builtin_type (RID_MAX, "unsigned short _Fract",
4103 unsigned_short_fract_type_node);
4104 record_builtin_type (RID_MAX, "unsigned _Fract",
4105 unsigned_fract_type_node);
4106 record_builtin_type (RID_MAX, "unsigned long _Fract",
4107 unsigned_long_fract_type_node);
4108 record_builtin_type (RID_MAX, "unsigned long long _Fract",
4109 unsigned_long_long_fract_type_node);
4110 record_builtin_type (RID_MAX, "_Sat short _Fract",
4111 sat_short_fract_type_node);
4112 record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4113 record_builtin_type (RID_MAX, "_Sat long _Fract",
4114 sat_long_fract_type_node);
4115 record_builtin_type (RID_MAX, "_Sat long long _Fract",
4116 sat_long_long_fract_type_node);
4117 record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4118 sat_unsigned_short_fract_type_node);
4119 record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4120 sat_unsigned_fract_type_node);
4121 record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4122 sat_unsigned_long_fract_type_node);
4123 record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4124 sat_unsigned_long_long_fract_type_node);
4125 record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4126 record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4127 record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4128 record_builtin_type (RID_MAX, "long long _Accum",
4129 long_long_accum_type_node);
4130 record_builtin_type (RID_MAX, "unsigned short _Accum",
4131 unsigned_short_accum_type_node);
4132 record_builtin_type (RID_MAX, "unsigned _Accum",
4133 unsigned_accum_type_node);
4134 record_builtin_type (RID_MAX, "unsigned long _Accum",
4135 unsigned_long_accum_type_node);
4136 record_builtin_type (RID_MAX, "unsigned long long _Accum",
4137 unsigned_long_long_accum_type_node);
4138 record_builtin_type (RID_MAX, "_Sat short _Accum",
4139 sat_short_accum_type_node);
4140 record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4141 record_builtin_type (RID_MAX, "_Sat long _Accum",
4142 sat_long_accum_type_node);
4143 record_builtin_type (RID_MAX, "_Sat long long _Accum",
4144 sat_long_long_accum_type_node);
4145 record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4146 sat_unsigned_short_accum_type_node);
4147 record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4148 sat_unsigned_accum_type_node);
4149 record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4150 sat_unsigned_long_accum_type_node);
4151 record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4152 sat_unsigned_long_long_accum_type_node);
4156 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4157 TYPE_DECL,
4158 get_identifier ("complex int"),
4159 complex_integer_type_node));
4160 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4161 TYPE_DECL,
4162 get_identifier ("complex float"),
4163 complex_float_type_node));
4164 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4165 TYPE_DECL,
4166 get_identifier ("complex double"),
4167 complex_double_type_node));
4168 lang_hooks.decls.pushdecl
4169 (build_decl (UNKNOWN_LOCATION,
4170 TYPE_DECL, get_identifier ("complex long double"),
4171 complex_long_double_type_node));
4173 if (!c_dialect_cxx ())
4174 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4175 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4177 char buf[30];
4178 sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4179 floatn_nx_types[i].extended ? "x" : "");
4180 lang_hooks.decls.pushdecl
4181 (build_decl (UNKNOWN_LOCATION,
4182 TYPE_DECL,
4183 get_identifier (buf),
4184 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4187 if (c_dialect_cxx ())
4189 /* For C++, make fileptr_type_node a distinct void * type until
4190 FILE type is defined. Likewise for const struct tm*. */
4191 for (unsigned i = 0;
4192 i < sizeof (builtin_structptr_types)
4193 / sizeof (builtin_structptr_type);
4194 ++i)
4195 builtin_structptr_types[i].node =
4196 build_variant_type_copy (builtin_structptr_types[i].base);
4200 record_builtin_type (RID_VOID, NULL, void_type_node);
4202 /* Set the TYPE_NAME for any variants that were built before
4203 record_builtin_type gave names to the built-in types. */
4205 tree void_name = TYPE_NAME (void_type_node);
4206 TYPE_NAME (void_type_node) = NULL_TREE;
4207 TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4208 = void_name;
4209 TYPE_NAME (void_type_node) = void_name;
4212 void_list_node = build_void_list_node ();
4214 /* Make a type to be the domain of a few array types
4215 whose domains don't really matter.
4216 200 is small enough that it always fits in size_t
4217 and large enough that it can hold most function names for the
4218 initializations of __FUNCTION__ and __PRETTY_FUNCTION__. */
4219 array_domain_type = build_index_type (size_int (200));
4221 /* Make a type for arrays of characters.
4222 With luck nothing will ever really depend on the length of this
4223 array type. */
4224 char_array_type_node
4225 = build_array_type (char_type_node, array_domain_type);
4227 string_type_node = build_pointer_type (char_type_node);
4228 const_string_type_node
4229 = build_pointer_type (build_qualified_type
4230 (char_type_node, TYPE_QUAL_CONST));
4232 /* This is special for C++ so functions can be overloaded. */
4233 wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4234 wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4235 wchar_type_size = TYPE_PRECISION (wchar_type_node);
4236 underlying_wchar_type_node = wchar_type_node;
4237 if (c_dialect_cxx ())
4239 if (TYPE_UNSIGNED (wchar_type_node))
4240 wchar_type_node = make_unsigned_type (wchar_type_size);
4241 else
4242 wchar_type_node = make_signed_type (wchar_type_size);
4243 record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4246 /* This is for wide string constants. */
4247 wchar_array_type_node
4248 = build_array_type (wchar_type_node, array_domain_type);
4250 /* Define 'char16_t'. */
4251 char16_type_node = get_identifier (CHAR16_TYPE);
4252 char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4253 char16_type_size = TYPE_PRECISION (char16_type_node);
4254 if (c_dialect_cxx ())
4256 char16_type_node = make_unsigned_type (char16_type_size);
4258 if (cxx_dialect >= cxx11)
4259 record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4262 /* This is for UTF-16 string constants. */
4263 char16_array_type_node
4264 = build_array_type (char16_type_node, array_domain_type);
4266 /* Define 'char32_t'. */
4267 char32_type_node = get_identifier (CHAR32_TYPE);
4268 char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4269 char32_type_size = TYPE_PRECISION (char32_type_node);
4270 if (c_dialect_cxx ())
4272 char32_type_node = make_unsigned_type (char32_type_size);
4274 if (cxx_dialect >= cxx11)
4275 record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4278 /* This is for UTF-32 string constants. */
4279 char32_array_type_node
4280 = build_array_type (char32_type_node, array_domain_type);
4282 wint_type_node =
4283 TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4285 intmax_type_node =
4286 TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4287 uintmax_type_node =
4288 TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4290 if (SIG_ATOMIC_TYPE)
4291 sig_atomic_type_node =
4292 TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4293 if (INT8_TYPE)
4294 int8_type_node =
4295 TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4296 if (INT16_TYPE)
4297 int16_type_node =
4298 TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4299 if (INT32_TYPE)
4300 int32_type_node =
4301 TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4302 if (INT64_TYPE)
4303 int64_type_node =
4304 TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4305 if (UINT8_TYPE)
4306 uint8_type_node =
4307 TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4308 if (UINT16_TYPE)
4309 c_uint16_type_node = uint16_type_node =
4310 TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4311 if (UINT32_TYPE)
4312 c_uint32_type_node = uint32_type_node =
4313 TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4314 if (UINT64_TYPE)
4315 c_uint64_type_node = uint64_type_node =
4316 TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4317 if (INT_LEAST8_TYPE)
4318 int_least8_type_node =
4319 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4320 if (INT_LEAST16_TYPE)
4321 int_least16_type_node =
4322 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4323 if (INT_LEAST32_TYPE)
4324 int_least32_type_node =
4325 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4326 if (INT_LEAST64_TYPE)
4327 int_least64_type_node =
4328 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4329 if (UINT_LEAST8_TYPE)
4330 uint_least8_type_node =
4331 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4332 if (UINT_LEAST16_TYPE)
4333 uint_least16_type_node =
4334 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4335 if (UINT_LEAST32_TYPE)
4336 uint_least32_type_node =
4337 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4338 if (UINT_LEAST64_TYPE)
4339 uint_least64_type_node =
4340 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4341 if (INT_FAST8_TYPE)
4342 int_fast8_type_node =
4343 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4344 if (INT_FAST16_TYPE)
4345 int_fast16_type_node =
4346 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4347 if (INT_FAST32_TYPE)
4348 int_fast32_type_node =
4349 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4350 if (INT_FAST64_TYPE)
4351 int_fast64_type_node =
4352 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4353 if (UINT_FAST8_TYPE)
4354 uint_fast8_type_node =
4355 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4356 if (UINT_FAST16_TYPE)
4357 uint_fast16_type_node =
4358 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4359 if (UINT_FAST32_TYPE)
4360 uint_fast32_type_node =
4361 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4362 if (UINT_FAST64_TYPE)
4363 uint_fast64_type_node =
4364 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4365 if (INTPTR_TYPE)
4366 intptr_type_node =
4367 TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4368 if (UINTPTR_TYPE)
4369 uintptr_type_node =
4370 TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4372 default_function_type
4373 = build_varargs_function_type_list (integer_type_node, NULL_TREE);
4374 unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4376 lang_hooks.decls.pushdecl
4377 (build_decl (UNKNOWN_LOCATION,
4378 TYPE_DECL, get_identifier ("__builtin_va_list"),
4379 va_list_type_node));
4380 if (targetm.enum_va_list_p)
4382 int l;
4383 const char *pname;
4384 tree ptype;
4386 for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4388 lang_hooks.decls.pushdecl
4389 (build_decl (UNKNOWN_LOCATION,
4390 TYPE_DECL, get_identifier (pname),
4391 ptype));
4396 if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4398 va_list_arg_type_node = va_list_ref_type_node =
4399 build_pointer_type (TREE_TYPE (va_list_type_node));
4401 else
4403 va_list_arg_type_node = va_list_type_node;
4404 va_list_ref_type_node = build_reference_type (va_list_type_node);
4407 if (!flag_preprocess_only)
4408 c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4410 main_identifier_node = get_identifier ("main");
4412 /* Create the built-in __null node. It is important that this is
4413 not shared. */
4414 null_node = make_int_cst (1, 1);
4415 TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4417 /* Since builtin_types isn't gc'ed, don't export these nodes. */
4418 memset (builtin_types, 0, sizeof (builtin_types));
4421 /* The number of named compound-literals generated thus far. */
4422 static GTY(()) int compound_literal_number;
4424 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal. */
4426 void
4427 set_compound_literal_name (tree decl)
4429 char *name;
4430 ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4431 compound_literal_number);
4432 compound_literal_number++;
4433 DECL_NAME (decl) = get_identifier (name);
4436 /* build_va_arg helper function. Return a VA_ARG_EXPR with location LOC, type
4437 TYPE and operand OP. */
4439 static tree
4440 build_va_arg_1 (location_t loc, tree type, tree op)
4442 tree expr = build1 (VA_ARG_EXPR, type, op);
4443 SET_EXPR_LOCATION (expr, loc);
4444 return expr;
4447 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4448 va_arg (EXPR, TYPE) at source location LOC. */
4450 tree
4451 build_va_arg (location_t loc, tree expr, tree type)
4453 tree va_type = TREE_TYPE (expr);
4454 tree canon_va_type = (va_type == error_mark_node
4455 ? error_mark_node
4456 : targetm.canonical_va_list_type (va_type));
4458 if (va_type == error_mark_node
4459 || canon_va_type == NULL_TREE)
4461 if (canon_va_type == NULL_TREE)
4462 error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4464 /* Let's handle things neutrallly, if expr:
4465 - has undeclared type, or
4466 - is not an va_list type. */
4467 return build_va_arg_1 (loc, type, error_mark_node);
4470 if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4472 /* Case 1: Not an array type. */
4474 /* Take the address, to get '&ap'. Note that &ap is not a va_list
4475 type. */
4476 mark_addressable (expr);
4477 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4479 return build_va_arg_1 (loc, type, expr);
4482 /* Case 2: Array type.
4484 Background:
4486 For contrast, let's start with the simple case (case 1). If
4487 canon_va_type is not an array type, but say a char *, then when
4488 passing-by-value a va_list, the type of the va_list param decl is
4489 the same as for another va_list decl (all ap's are char *):
4491 f2_1 (char * ap)
4492 D.1815 = VA_ARG (&ap, 0B, 1);
4493 return D.1815;
4495 f2 (int i)
4496 char * ap.0;
4497 char * ap;
4498 __builtin_va_start (&ap, 0);
4499 ap.0 = ap;
4500 res = f2_1 (ap.0);
4501 __builtin_va_end (&ap);
4502 D.1812 = res;
4503 return D.1812;
4505 However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4506 va_list the type of the va_list param decl (case 2b, struct * ap) is not
4507 the same as for another va_list decl (case 2a, struct ap[1]).
4509 f2_1 (struct * ap)
4510 D.1844 = VA_ARG (ap, 0B, 0);
4511 return D.1844;
4513 f2 (int i)
4514 struct ap[1];
4515 __builtin_va_start (&ap, 0);
4516 res = f2_1 (&ap);
4517 __builtin_va_end (&ap);
4518 D.1841 = res;
4519 return D.1841;
4521 Case 2b is different because:
4522 - on the callee side, the parm decl has declared type va_list, but
4523 grokdeclarator changes the type of the parm decl to a pointer to the
4524 array elem type.
4525 - on the caller side, the pass-by-value uses &ap.
4527 We unify these two cases (case 2a: va_list is array type,
4528 case 2b: va_list is pointer to array elem type), by adding '&' for the
4529 array type case, such that we have a pointer to array elem in both
4530 cases. */
4532 if (TREE_CODE (va_type) == ARRAY_TYPE)
4534 /* Case 2a: va_list is array type. */
4536 /* Take the address, to get '&ap'. Make sure it's a pointer to array
4537 elem type. */
4538 mark_addressable (expr);
4539 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4540 expr);
4542 /* Verify that &ap is still recognized as having va_list type. */
4543 tree canon_expr_type
4544 = targetm.canonical_va_list_type (TREE_TYPE (expr));
4545 gcc_assert (canon_expr_type != NULL_TREE);
4547 else
4549 /* Case 2b: va_list is pointer to array elem type. */
4550 gcc_assert (POINTER_TYPE_P (va_type));
4552 /* Comparison as in std_canonical_va_list_type. */
4553 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4554 == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4556 /* Don't take the address. We've already got '&ap'. */
4560 return build_va_arg_1 (loc, type, expr);
4564 /* Linked list of disabled built-in functions. */
4566 struct disabled_builtin
4568 const char *name;
4569 struct disabled_builtin *next;
4571 static disabled_builtin *disabled_builtins = NULL;
4573 static bool builtin_function_disabled_p (const char *);
4575 /* Disable a built-in function specified by -fno-builtin-NAME. If NAME
4576 begins with "__builtin_", give an error. */
4578 void
4579 disable_builtin_function (const char *name)
4581 if (strncmp (name, "__builtin_", strlen ("__builtin_")) == 0)
4582 error ("cannot disable built-in function %qs", name);
4583 else
4585 disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4586 new_disabled_builtin->name = name;
4587 new_disabled_builtin->next = disabled_builtins;
4588 disabled_builtins = new_disabled_builtin;
4593 /* Return true if the built-in function NAME has been disabled, false
4594 otherwise. */
4596 static bool
4597 builtin_function_disabled_p (const char *name)
4599 disabled_builtin *p;
4600 for (p = disabled_builtins; p != NULL; p = p->next)
4602 if (strcmp (name, p->name) == 0)
4603 return true;
4605 return false;
4609 /* Worker for DEF_BUILTIN.
4610 Possibly define a builtin function with one or two names.
4611 Does not declare a non-__builtin_ function if flag_no_builtin, or if
4612 nonansi_p and flag_no_nonansi_builtin. */
4614 static void
4615 def_builtin_1 (enum built_in_function fncode,
4616 const char *name,
4617 enum built_in_class fnclass,
4618 tree fntype, tree libtype,
4619 bool both_p, bool fallback_p, bool nonansi_p,
4620 tree fnattrs, bool implicit_p)
4622 tree decl;
4623 const char *libname;
4625 if (fntype == error_mark_node)
4626 return;
4628 gcc_assert ((!both_p && !fallback_p)
4629 || !strncmp (name, "__builtin_",
4630 strlen ("__builtin_")));
4632 libname = name + strlen ("__builtin_");
4633 decl = add_builtin_function (name, fntype, fncode, fnclass,
4634 (fallback_p ? libname : NULL),
4635 fnattrs);
4637 set_builtin_decl (fncode, decl, implicit_p);
4639 if (both_p
4640 && !flag_no_builtin && !builtin_function_disabled_p (libname)
4641 && !(nonansi_p && flag_no_nonansi_builtin))
4642 add_builtin_function (libname, libtype, fncode, fnclass,
4643 NULL, fnattrs);
4646 /* Nonzero if the type T promotes to int. This is (nearly) the
4647 integral promotions defined in ISO C99 6.3.1.1/2. */
4649 bool
4650 c_promoting_integer_type_p (const_tree t)
4652 switch (TREE_CODE (t))
4654 case INTEGER_TYPE:
4655 return (TYPE_MAIN_VARIANT (t) == char_type_node
4656 || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4657 || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4658 || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4659 || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
4660 || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
4662 case ENUMERAL_TYPE:
4663 /* ??? Technically all enumerations not larger than an int
4664 promote to an int. But this is used along code paths
4665 that only want to notice a size change. */
4666 return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
4668 case BOOLEAN_TYPE:
4669 return true;
4671 default:
4672 return false;
4676 /* Return 1 if PARMS specifies a fixed number of parameters
4677 and none of their types is affected by default promotions. */
4679 bool
4680 self_promoting_args_p (const_tree parms)
4682 const_tree t;
4683 for (t = parms; t; t = TREE_CHAIN (t))
4685 tree type = TREE_VALUE (t);
4687 if (type == error_mark_node)
4688 continue;
4690 if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
4691 return false;
4693 if (type == NULL_TREE)
4694 return false;
4696 if (TYPE_MAIN_VARIANT (type) == float_type_node)
4697 return false;
4699 if (c_promoting_integer_type_p (type))
4700 return false;
4702 return true;
4705 /* Recursively remove any '*' or '&' operator from TYPE. */
4706 tree
4707 strip_pointer_operator (tree t)
4709 while (POINTER_TYPE_P (t))
4710 t = TREE_TYPE (t);
4711 return t;
4714 /* Recursively remove pointer or array type from TYPE. */
4715 tree
4716 strip_pointer_or_array_types (tree t)
4718 while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
4719 t = TREE_TYPE (t);
4720 return t;
4723 /* Used to compare case labels. K1 and K2 are actually tree nodes
4724 representing case labels, or NULL_TREE for a `default' label.
4725 Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
4726 K2, and 0 if K1 and K2 are equal. */
4729 case_compare (splay_tree_key k1, splay_tree_key k2)
4731 /* Consider a NULL key (such as arises with a `default' label) to be
4732 smaller than anything else. */
4733 if (!k1)
4734 return k2 ? -1 : 0;
4735 else if (!k2)
4736 return k1 ? 1 : 0;
4738 return tree_int_cst_compare ((tree) k1, (tree) k2);
4741 /* Process a case label, located at LOC, for the range LOW_VALUE
4742 ... HIGH_VALUE. If LOW_VALUE and HIGH_VALUE are both NULL_TREE
4743 then this case label is actually a `default' label. If only
4744 HIGH_VALUE is NULL_TREE, then case label was declared using the
4745 usual C/C++ syntax, rather than the GNU case range extension.
4746 CASES is a tree containing all the case ranges processed so far;
4747 COND is the condition for the switch-statement itself.
4748 OUTSIDE_RANGE_P says whether there was a case value that doesn't
4749 fit into the range of the ORIG_TYPE. Returns the CASE_LABEL_EXPR
4750 created, or ERROR_MARK_NODE if no CASE_LABEL_EXPR is created. */
4752 tree
4753 c_add_case_label (location_t loc, splay_tree cases, tree cond, tree orig_type,
4754 tree low_value, tree high_value, bool *outside_range_p)
4756 tree type;
4757 tree label;
4758 tree case_label;
4759 splay_tree_node node;
4761 /* Create the LABEL_DECL itself. */
4762 label = create_artificial_label (loc);
4764 /* If there was an error processing the switch condition, bail now
4765 before we get more confused. */
4766 if (!cond || cond == error_mark_node)
4767 goto error_out;
4769 if ((low_value && TREE_TYPE (low_value)
4770 && POINTER_TYPE_P (TREE_TYPE (low_value)))
4771 || (high_value && TREE_TYPE (high_value)
4772 && POINTER_TYPE_P (TREE_TYPE (high_value))))
4774 error_at (loc, "pointers are not permitted as case values");
4775 goto error_out;
4778 /* Case ranges are a GNU extension. */
4779 if (high_value)
4780 pedwarn (loc, OPT_Wpedantic,
4781 "range expressions in switch statements are non-standard");
4783 type = TREE_TYPE (cond);
4784 if (low_value)
4786 low_value = check_case_value (loc, low_value);
4787 low_value = convert_and_check (loc, type, low_value);
4788 if (low_value == error_mark_node)
4789 goto error_out;
4791 if (high_value)
4793 high_value = check_case_value (loc, high_value);
4794 high_value = convert_and_check (loc, type, high_value);
4795 if (high_value == error_mark_node)
4796 goto error_out;
4799 if (low_value && high_value)
4801 /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
4802 really a case range, even though it was written that way.
4803 Remove the HIGH_VALUE to simplify later processing. */
4804 if (tree_int_cst_equal (low_value, high_value))
4805 high_value = NULL_TREE;
4806 else if (!tree_int_cst_lt (low_value, high_value))
4807 warning_at (loc, 0, "empty range specified");
4810 /* See if the case is in range of the type of the original testing
4811 expression. If both low_value and high_value are out of range,
4812 don't insert the case label and return NULL_TREE. */
4813 if (low_value
4814 && !check_case_bounds (loc, type, orig_type,
4815 &low_value, high_value ? &high_value : NULL,
4816 outside_range_p))
4817 return NULL_TREE;
4819 /* Look up the LOW_VALUE in the table of case labels we already
4820 have. */
4821 node = splay_tree_lookup (cases, (splay_tree_key) low_value);
4822 /* If there was not an exact match, check for overlapping ranges.
4823 There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
4824 that's a `default' label and the only overlap is an exact match. */
4825 if (!node && (low_value || high_value))
4827 splay_tree_node low_bound;
4828 splay_tree_node high_bound;
4830 /* Even though there wasn't an exact match, there might be an
4831 overlap between this case range and another case range.
4832 Since we've (inductively) not allowed any overlapping case
4833 ranges, we simply need to find the greatest low case label
4834 that is smaller that LOW_VALUE, and the smallest low case
4835 label that is greater than LOW_VALUE. If there is an overlap
4836 it will occur in one of these two ranges. */
4837 low_bound = splay_tree_predecessor (cases,
4838 (splay_tree_key) low_value);
4839 high_bound = splay_tree_successor (cases,
4840 (splay_tree_key) low_value);
4842 /* Check to see if the LOW_BOUND overlaps. It is smaller than
4843 the LOW_VALUE, so there is no need to check unless the
4844 LOW_BOUND is in fact itself a case range. */
4845 if (low_bound
4846 && CASE_HIGH ((tree) low_bound->value)
4847 && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
4848 low_value) >= 0)
4849 node = low_bound;
4850 /* Check to see if the HIGH_BOUND overlaps. The low end of that
4851 range is bigger than the low end of the current range, so we
4852 are only interested if the current range is a real range, and
4853 not an ordinary case label. */
4854 else if (high_bound
4855 && high_value
4856 && (tree_int_cst_compare ((tree) high_bound->key,
4857 high_value)
4858 <= 0))
4859 node = high_bound;
4861 /* If there was an overlap, issue an error. */
4862 if (node)
4864 tree duplicate = CASE_LABEL ((tree) node->value);
4866 if (high_value)
4868 error_at (loc, "duplicate (or overlapping) case value");
4869 inform (DECL_SOURCE_LOCATION (duplicate),
4870 "this is the first entry overlapping that value");
4872 else if (low_value)
4874 error_at (loc, "duplicate case value") ;
4875 inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
4877 else
4879 error_at (loc, "multiple default labels in one switch");
4880 inform (DECL_SOURCE_LOCATION (duplicate),
4881 "this is the first default label");
4883 goto error_out;
4886 /* Add a CASE_LABEL to the statement-tree. */
4887 case_label = add_stmt (build_case_label (low_value, high_value, label));
4888 /* Register this case label in the splay tree. */
4889 splay_tree_insert (cases,
4890 (splay_tree_key) low_value,
4891 (splay_tree_value) case_label);
4893 return case_label;
4895 error_out:
4896 /* Add a label so that the back-end doesn't think that the beginning of
4897 the switch is unreachable. Note that we do not add a case label, as
4898 that just leads to duplicates and thence to failure later on. */
4899 if (!cases->root)
4901 tree t = create_artificial_label (loc);
4902 add_stmt (build_stmt (loc, LABEL_EXPR, t));
4904 return error_mark_node;
4907 /* Finish an expression taking the address of LABEL (an
4908 IDENTIFIER_NODE). Returns an expression for the address.
4910 LOC is the location for the expression returned. */
4912 tree
4913 finish_label_address_expr (tree label, location_t loc)
4915 tree result;
4917 pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
4919 if (label == error_mark_node)
4920 return error_mark_node;
4922 label = lookup_label (label);
4923 if (label == NULL_TREE)
4924 result = null_pointer_node;
4925 else
4927 TREE_USED (label) = 1;
4928 result = build1 (ADDR_EXPR, ptr_type_node, label);
4929 /* The current function is not necessarily uninlinable.
4930 Computed gotos are incompatible with inlining, but the value
4931 here could be used only in a diagnostic, for example. */
4932 protected_set_expr_location (result, loc);
4935 return result;
4939 /* Given a boolean expression ARG, return a tree representing an increment
4940 or decrement (as indicated by CODE) of ARG. The front end must check for
4941 invalid cases (e.g., decrement in C++). */
4942 tree
4943 boolean_increment (enum tree_code code, tree arg)
4945 tree val;
4946 tree true_res = build_int_cst (TREE_TYPE (arg), 1);
4948 arg = stabilize_reference (arg);
4949 switch (code)
4951 case PREINCREMENT_EXPR:
4952 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
4953 break;
4954 case POSTINCREMENT_EXPR:
4955 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
4956 arg = save_expr (arg);
4957 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
4958 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
4959 break;
4960 case PREDECREMENT_EXPR:
4961 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
4962 invert_truthvalue_loc (input_location, arg));
4963 break;
4964 case POSTDECREMENT_EXPR:
4965 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
4966 invert_truthvalue_loc (input_location, arg));
4967 arg = save_expr (arg);
4968 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
4969 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
4970 break;
4971 default:
4972 gcc_unreachable ();
4974 TREE_SIDE_EFFECTS (val) = 1;
4975 return val;
4978 /* Built-in macros for stddef.h and stdint.h, that require macros
4979 defined in this file. */
4980 void
4981 c_stddef_cpp_builtins(void)
4983 builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
4984 builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
4985 builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
4986 builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
4987 builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
4988 builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
4989 builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
4990 builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
4991 if (SIG_ATOMIC_TYPE)
4992 builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
4993 if (INT8_TYPE)
4994 builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
4995 if (INT16_TYPE)
4996 builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
4997 if (INT32_TYPE)
4998 builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
4999 if (INT64_TYPE)
5000 builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5001 if (UINT8_TYPE)
5002 builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5003 if (UINT16_TYPE)
5004 builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5005 if (UINT32_TYPE)
5006 builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5007 if (UINT64_TYPE)
5008 builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5009 if (INT_LEAST8_TYPE)
5010 builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5011 if (INT_LEAST16_TYPE)
5012 builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5013 if (INT_LEAST32_TYPE)
5014 builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5015 if (INT_LEAST64_TYPE)
5016 builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5017 if (UINT_LEAST8_TYPE)
5018 builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5019 if (UINT_LEAST16_TYPE)
5020 builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5021 if (UINT_LEAST32_TYPE)
5022 builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5023 if (UINT_LEAST64_TYPE)
5024 builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5025 if (INT_FAST8_TYPE)
5026 builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5027 if (INT_FAST16_TYPE)
5028 builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5029 if (INT_FAST32_TYPE)
5030 builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5031 if (INT_FAST64_TYPE)
5032 builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5033 if (UINT_FAST8_TYPE)
5034 builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5035 if (UINT_FAST16_TYPE)
5036 builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5037 if (UINT_FAST32_TYPE)
5038 builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5039 if (UINT_FAST64_TYPE)
5040 builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5041 if (INTPTR_TYPE)
5042 builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5043 if (UINTPTR_TYPE)
5044 builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5047 static void
5048 c_init_attributes (void)
5050 /* Fill in the built_in_attributes array. */
5051 #define DEF_ATTR_NULL_TREE(ENUM) \
5052 built_in_attributes[(int) ENUM] = NULL_TREE;
5053 #define DEF_ATTR_INT(ENUM, VALUE) \
5054 built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5055 #define DEF_ATTR_STRING(ENUM, VALUE) \
5056 built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5057 #define DEF_ATTR_IDENT(ENUM, STRING) \
5058 built_in_attributes[(int) ENUM] = get_identifier (STRING);
5059 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5060 built_in_attributes[(int) ENUM] \
5061 = tree_cons (built_in_attributes[(int) PURPOSE], \
5062 built_in_attributes[(int) VALUE], \
5063 built_in_attributes[(int) CHAIN]);
5064 #include "builtin-attrs.def"
5065 #undef DEF_ATTR_NULL_TREE
5066 #undef DEF_ATTR_INT
5067 #undef DEF_ATTR_IDENT
5068 #undef DEF_ATTR_TREE_LIST
5071 /* Check whether ALIGN is a valid user-specified alignment. If so,
5072 return its base-2 log; if not, output an error and return -1. If
5073 ALLOW_ZERO then 0 is valid and should result in a return of -1 with
5074 no error. */
5076 check_user_alignment (const_tree align, bool allow_zero)
5078 int i;
5080 if (error_operand_p (align))
5081 return -1;
5082 if (TREE_CODE (align) != INTEGER_CST
5083 || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5085 error ("requested alignment is not an integer constant");
5086 return -1;
5088 else if (allow_zero && integer_zerop (align))
5089 return -1;
5090 else if (tree_int_cst_sgn (align) == -1
5091 || (i = tree_log2 (align)) == -1)
5093 error ("requested alignment is not a positive power of 2");
5094 return -1;
5096 else if (i >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5098 error ("requested alignment is too large");
5099 return -1;
5101 return i;
5104 /* Determine the ELF symbol visibility for DECL, which is either a
5105 variable or a function. It is an error to use this function if a
5106 definition of DECL is not available in this translation unit.
5107 Returns true if the final visibility has been determined by this
5108 function; false if the caller is free to make additional
5109 modifications. */
5111 bool
5112 c_determine_visibility (tree decl)
5114 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5116 /* If the user explicitly specified the visibility with an
5117 attribute, honor that. DECL_VISIBILITY will have been set during
5118 the processing of the attribute. We check for an explicit
5119 attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5120 to distinguish the use of an attribute from the use of a "#pragma
5121 GCC visibility push(...)"; in the latter case we still want other
5122 considerations to be able to overrule the #pragma. */
5123 if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5124 || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5125 && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5126 || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5127 return true;
5129 /* Set default visibility to whatever the user supplied with
5130 visibility_specified depending on #pragma GCC visibility. */
5131 if (!DECL_VISIBILITY_SPECIFIED (decl))
5133 if (visibility_options.inpragma
5134 || DECL_VISIBILITY (decl) != default_visibility)
5136 DECL_VISIBILITY (decl) = default_visibility;
5137 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5138 /* If visibility changed and DECL already has DECL_RTL, ensure
5139 symbol flags are updated. */
5140 if (((VAR_P (decl) && TREE_STATIC (decl))
5141 || TREE_CODE (decl) == FUNCTION_DECL)
5142 && DECL_RTL_SET_P (decl))
5143 make_decl_rtl (decl);
5146 return false;
5149 /* Data to communicate through check_function_arguments_recurse between
5150 check_function_nonnull and check_nonnull_arg. */
5152 struct nonnull_arg_ctx
5154 location_t loc;
5155 bool warned_p;
5158 /* Check the argument list of a function call for null in argument slots
5159 that are marked as requiring a non-null pointer argument. The NARGS
5160 arguments are passed in the array ARGARRAY. Return true if we have
5161 warned. */
5163 static bool
5164 check_function_nonnull (location_t loc, tree attrs, int nargs, tree *argarray)
5166 tree a;
5167 int i;
5169 attrs = lookup_attribute ("nonnull", attrs);
5170 if (attrs == NULL_TREE)
5171 return false;
5173 a = attrs;
5174 /* See if any of the nonnull attributes has no arguments. If so,
5175 then every pointer argument is checked (in which case the check
5176 for pointer type is done in check_nonnull_arg). */
5177 if (TREE_VALUE (a) != NULL_TREE)
5179 a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5180 while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5182 struct nonnull_arg_ctx ctx = { loc, false };
5183 if (a != NULL_TREE)
5184 for (i = 0; i < nargs; i++)
5185 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5186 i + 1);
5187 else
5189 /* Walk the argument list. If we encounter an argument number we
5190 should check for non-null, do it. */
5191 for (i = 0; i < nargs; i++)
5193 for (a = attrs; ; a = TREE_CHAIN (a))
5195 a = lookup_attribute ("nonnull", a);
5196 if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5197 break;
5200 if (a != NULL_TREE)
5201 check_function_arguments_recurse (check_nonnull_arg, &ctx,
5202 argarray[i], i + 1);
5205 return ctx.warned_p;
5208 /* Check that the Nth argument of a function call (counting backwards
5209 from the end) is a (pointer)0. The NARGS arguments are passed in the
5210 array ARGARRAY. */
5212 static void
5213 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5215 tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5217 if (attr)
5219 int len = 0;
5220 int pos = 0;
5221 tree sentinel;
5222 function_args_iterator iter;
5223 tree t;
5225 /* Skip over the named arguments. */
5226 FOREACH_FUNCTION_ARGS (fntype, t, iter)
5228 if (len == nargs)
5229 break;
5230 len++;
5233 if (TREE_VALUE (attr))
5235 tree p = TREE_VALUE (TREE_VALUE (attr));
5236 pos = TREE_INT_CST_LOW (p);
5239 /* The sentinel must be one of the varargs, i.e.
5240 in position >= the number of fixed arguments. */
5241 if ((nargs - 1 - pos) < len)
5243 warning (OPT_Wformat_,
5244 "not enough variable arguments to fit a sentinel");
5245 return;
5248 /* Validate the sentinel. */
5249 sentinel = argarray[nargs - 1 - pos];
5250 if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5251 || !integer_zerop (sentinel))
5252 /* Although __null (in C++) is only an integer we allow it
5253 nevertheless, as we are guaranteed that it's exactly
5254 as wide as a pointer, and we don't want to force
5255 users to cast the NULL they have written there.
5256 We warn with -Wstrict-null-sentinel, though. */
5257 && (warn_strict_null_sentinel || null_node != sentinel))
5258 warning (OPT_Wformat_, "missing sentinel in function call");
5262 /* Check that the same argument isn't passed to restrict arguments
5263 and other arguments. */
5265 static void
5266 check_function_restrict (const_tree fndecl, const_tree fntype,
5267 int nargs, tree *argarray)
5269 int i;
5270 tree parms;
5272 if (fndecl
5273 && TREE_CODE (fndecl) == FUNCTION_DECL
5274 && DECL_ARGUMENTS (fndecl))
5275 parms = DECL_ARGUMENTS (fndecl);
5276 else
5277 parms = TYPE_ARG_TYPES (fntype);
5279 for (i = 0; i < nargs; i++)
5280 TREE_VISITED (argarray[i]) = 0;
5282 for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5284 tree type;
5285 if (TREE_CODE (parms) == PARM_DECL)
5287 type = TREE_TYPE (parms);
5288 parms = DECL_CHAIN (parms);
5290 else
5292 type = TREE_VALUE (parms);
5293 parms = TREE_CHAIN (parms);
5295 if (POINTER_TYPE_P (type)
5296 && TYPE_RESTRICT (type)
5297 && !TYPE_READONLY (TREE_TYPE (type)))
5298 warn_for_restrict (i, argarray, nargs);
5301 for (i = 0; i < nargs; i++)
5302 TREE_VISITED (argarray[i]) = 0;
5305 /* Helper for check_function_nonnull; given a list of operands which
5306 must be non-null in ARGS, determine if operand PARAM_NUM should be
5307 checked. */
5309 static bool
5310 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5312 unsigned HOST_WIDE_INT arg_num = 0;
5314 for (; args; args = TREE_CHAIN (args))
5316 bool found = get_nonnull_operand (TREE_VALUE (args), &arg_num);
5318 gcc_assert (found);
5320 if (arg_num == param_num)
5321 return true;
5323 return false;
5326 /* Check that the function argument PARAM (which is operand number
5327 PARAM_NUM) is non-null. This is called by check_function_nonnull
5328 via check_function_arguments_recurse. */
5330 static void
5331 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5333 struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5335 /* Just skip checking the argument if it's not a pointer. This can
5336 happen if the "nonnull" attribute was given without an operand
5337 list (which means to check every pointer argument). */
5339 if (TREE_CODE (TREE_TYPE (param)) != POINTER_TYPE)
5340 return;
5342 /* When not optimizing diagnose the simple cases of null arguments.
5343 When optimization is enabled defer the checking until expansion
5344 when more cases can be detected. */
5345 if (integer_zerop (param))
5347 warning_at (pctx->loc, OPT_Wnonnull, "null argument where non-null "
5348 "required (argument %lu)", (unsigned long) param_num);
5349 pctx->warned_p = true;
5353 /* Helper for nonnull attribute handling; fetch the operand number
5354 from the attribute argument list. */
5356 bool
5357 get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5359 /* Verify the arg number is a small constant. */
5360 if (tree_fits_uhwi_p (arg_num_expr))
5362 *valp = tree_to_uhwi (arg_num_expr);
5363 return true;
5365 else
5366 return false;
5369 /* Arguments being collected for optimization. */
5370 typedef const char *const_char_p; /* For DEF_VEC_P. */
5371 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5374 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5375 options in ARGS. ATTR_P is true if this is for attribute(optimize), and
5376 false for #pragma GCC optimize. */
5378 bool
5379 parse_optimize_options (tree args, bool attr_p)
5381 bool ret = true;
5382 unsigned opt_argc;
5383 unsigned i;
5384 const char **opt_argv;
5385 struct cl_decoded_option *decoded_options;
5386 unsigned int decoded_options_count;
5387 tree ap;
5389 /* Build up argv vector. Just in case the string is stored away, use garbage
5390 collected strings. */
5391 vec_safe_truncate (optimize_args, 0);
5392 vec_safe_push (optimize_args, (const char *) NULL);
5394 for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5396 tree value = TREE_VALUE (ap);
5398 if (TREE_CODE (value) == INTEGER_CST)
5400 char buffer[20];
5401 sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5402 vec_safe_push (optimize_args, ggc_strdup (buffer));
5405 else if (TREE_CODE (value) == STRING_CST)
5407 /* Split string into multiple substrings. */
5408 size_t len = TREE_STRING_LENGTH (value);
5409 char *p = ASTRDUP (TREE_STRING_POINTER (value));
5410 char *end = p + len;
5411 char *comma;
5412 char *next_p = p;
5414 while (next_p != NULL)
5416 size_t len2;
5417 char *q, *r;
5419 p = next_p;
5420 comma = strchr (p, ',');
5421 if (comma)
5423 len2 = comma - p;
5424 *comma = '\0';
5425 next_p = comma+1;
5427 else
5429 len2 = end - p;
5430 next_p = NULL;
5433 r = q = (char *) ggc_alloc_atomic (len2 + 3);
5435 /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5436 options. */
5437 if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5439 ret = false;
5440 if (attr_p)
5441 warning (OPT_Wattributes,
5442 "bad option %qs to attribute %<optimize%>", p);
5443 else
5444 warning (OPT_Wpragmas,
5445 "bad option %qs to pragma %<optimize%>", p);
5446 continue;
5449 if (*p != '-')
5451 *r++ = '-';
5453 /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5454 itself is -Os, and any other switch begins with a -f. */
5455 if ((*p >= '0' && *p <= '9')
5456 || (p[0] == 's' && p[1] == '\0'))
5457 *r++ = 'O';
5458 else if (*p != 'O')
5459 *r++ = 'f';
5462 memcpy (r, p, len2);
5463 r[len2] = '\0';
5464 vec_safe_push (optimize_args, (const char *) q);
5470 opt_argc = optimize_args->length ();
5471 opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5473 for (i = 1; i < opt_argc; i++)
5474 opt_argv[i] = (*optimize_args)[i];
5476 /* Now parse the options. */
5477 decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
5478 &decoded_options,
5479 &decoded_options_count);
5480 /* Drop non-Optimization options. */
5481 unsigned j = 1;
5482 for (i = 1; i < decoded_options_count; ++i)
5484 if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
5486 ret = false;
5487 if (attr_p)
5488 warning (OPT_Wattributes,
5489 "bad option %qs to attribute %<optimize%>",
5490 decoded_options[i].orig_option_with_args_text);
5491 else
5492 warning (OPT_Wpragmas,
5493 "bad option %qs to pragma %<optimize%>",
5494 decoded_options[i].orig_option_with_args_text);
5495 continue;
5497 if (i != j)
5498 decoded_options[j] = decoded_options[i];
5499 j++;
5501 decoded_options_count = j;
5502 /* And apply them. */
5503 decode_options (&global_options, &global_options_set,
5504 decoded_options, decoded_options_count,
5505 input_location, global_dc, NULL);
5507 targetm.override_options_after_change();
5509 optimize_args->truncate (0);
5510 return ret;
5513 /* Check whether ATTR is a valid attribute fallthrough. */
5515 bool
5516 attribute_fallthrough_p (tree attr)
5518 if (attr == error_mark_node)
5519 return false;
5520 tree t = lookup_attribute ("fallthrough", attr);
5521 if (t == NULL_TREE)
5522 return false;
5523 /* This attribute shall appear at most once in each attribute-list. */
5524 if (lookup_attribute ("fallthrough", TREE_CHAIN (t)))
5525 warning (OPT_Wattributes, "%<fallthrough%> attribute specified multiple "
5526 "times");
5527 /* No attribute-argument-clause shall be present. */
5528 else if (TREE_VALUE (t) != NULL_TREE)
5529 warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
5530 "a parameter");
5531 /* Warn if other attributes are found. */
5532 for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
5534 tree name = get_attribute_name (t);
5535 if (!is_attribute_p ("fallthrough", name))
5536 warning (OPT_Wattributes, "%qE attribute ignored", name);
5538 return true;
5542 /* Check for valid arguments being passed to a function with FNTYPE.
5543 There are NARGS arguments in the array ARGARRAY. LOC should be used for
5544 diagnostics. Return true if -Wnonnull warning has been diagnosed. */
5545 bool
5546 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
5547 int nargs, tree *argarray, vec<location_t> *arglocs)
5549 bool warned_p = false;
5551 /* Check for null being passed in a pointer argument that must be
5552 non-null. We also need to do this if format checking is enabled. */
5554 if (warn_nonnull)
5555 warned_p = check_function_nonnull (loc, TYPE_ATTRIBUTES (fntype),
5556 nargs, argarray);
5558 /* Check for errors in format strings. */
5560 if (warn_format || warn_suggest_attribute_format)
5561 check_function_format (TYPE_ATTRIBUTES (fntype), nargs, argarray, arglocs);
5563 if (warn_format)
5564 check_function_sentinel (fntype, nargs, argarray);
5566 if (warn_restrict)
5567 check_function_restrict (fndecl, fntype, nargs, argarray);
5568 return warned_p;
5571 /* Generic argument checking recursion routine. PARAM is the argument to
5572 be checked. PARAM_NUM is the number of the argument. CALLBACK is invoked
5573 once the argument is resolved. CTX is context for the callback. */
5574 void
5575 check_function_arguments_recurse (void (*callback)
5576 (void *, tree, unsigned HOST_WIDE_INT),
5577 void *ctx, tree param,
5578 unsigned HOST_WIDE_INT param_num)
5580 if (CONVERT_EXPR_P (param)
5581 && (TYPE_PRECISION (TREE_TYPE (param))
5582 == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
5584 /* Strip coercion. */
5585 check_function_arguments_recurse (callback, ctx,
5586 TREE_OPERAND (param, 0), param_num);
5587 return;
5590 if (TREE_CODE (param) == CALL_EXPR)
5592 tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
5593 tree attrs;
5594 bool found_format_arg = false;
5596 /* See if this is a call to a known internationalization function
5597 that modifies a format arg. Such a function may have multiple
5598 format_arg attributes (for example, ngettext). */
5600 for (attrs = TYPE_ATTRIBUTES (type);
5601 attrs;
5602 attrs = TREE_CHAIN (attrs))
5603 if (is_attribute_p ("format_arg", TREE_PURPOSE (attrs)))
5605 tree inner_arg;
5606 tree format_num_expr;
5607 int format_num;
5608 int i;
5609 call_expr_arg_iterator iter;
5611 /* Extract the argument number, which was previously checked
5612 to be valid. */
5613 format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
5615 format_num = tree_to_uhwi (format_num_expr);
5617 for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
5618 inner_arg != NULL_TREE;
5619 inner_arg = next_call_expr_arg (&iter), i++)
5620 if (i == format_num)
5622 check_function_arguments_recurse (callback, ctx,
5623 inner_arg, param_num);
5624 found_format_arg = true;
5625 break;
5629 /* If we found a format_arg attribute and did a recursive check,
5630 we are done with checking this argument. Otherwise, we continue
5631 and this will be considered a non-literal. */
5632 if (found_format_arg)
5633 return;
5636 if (TREE_CODE (param) == COND_EXPR)
5638 /* Simplify to avoid warning for an impossible case. */
5639 param = fold_for_warn (param);
5640 if (TREE_CODE (param) == COND_EXPR)
5642 /* Check both halves of the conditional expression. */
5643 check_function_arguments_recurse (callback, ctx,
5644 TREE_OPERAND (param, 1),
5645 param_num);
5646 check_function_arguments_recurse (callback, ctx,
5647 TREE_OPERAND (param, 2),
5648 param_num);
5649 return;
5653 (*callback) (ctx, param, param_num);
5656 /* Checks for a builtin function FNDECL that the number of arguments
5657 NARGS against the required number REQUIRED and issues an error if
5658 there is a mismatch. Returns true if the number of arguments is
5659 correct, otherwise false. LOC is the location of FNDECL. */
5661 static bool
5662 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
5663 int required)
5665 if (nargs < required)
5667 error_at (loc, "too few arguments to function %qE", fndecl);
5668 return false;
5670 else if (nargs > required)
5672 error_at (loc, "too many arguments to function %qE", fndecl);
5673 return false;
5675 return true;
5678 /* Helper macro for check_builtin_function_arguments. */
5679 #define ARG_LOCATION(N) \
5680 (arg_loc.is_empty () \
5681 ? EXPR_LOC_OR_LOC (args[(N)], input_location) \
5682 : expansion_point_location (arg_loc[(N)]))
5684 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
5685 Returns false if there was an error, otherwise true. LOC is the
5686 location of the function; ARG_LOC is a vector of locations of the
5687 arguments. */
5689 bool
5690 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
5691 tree fndecl, int nargs, tree *args)
5693 if (!DECL_BUILT_IN (fndecl)
5694 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
5695 return true;
5697 switch (DECL_FUNCTION_CODE (fndecl))
5699 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
5700 if (!tree_fits_uhwi_p (args[2]))
5702 error_at (ARG_LOCATION (2),
5703 "third argument to function %qE must be a constant integer",
5704 fndecl);
5705 return false;
5707 /* fall through */
5709 case BUILT_IN_ALLOCA_WITH_ALIGN:
5711 /* Get the requested alignment (in bits) if it's a constant
5712 integer expression. */
5713 unsigned HOST_WIDE_INT align
5714 = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
5716 /* Determine if the requested alignment is a power of 2. */
5717 if ((align & (align - 1)))
5718 align = 0;
5720 /* The maximum alignment in bits corresponding to the same
5721 maximum in bytes enforced in check_user_alignment(). */
5722 unsigned maxalign = (UINT_MAX >> 1) + 1;
5724 /* Reject invalid alignments. */
5725 if (align < BITS_PER_UNIT || maxalign < align)
5727 error_at (ARG_LOCATION (1),
5728 "second argument to function %qE must be a constant "
5729 "integer power of 2 between %qi and %qu bits",
5730 fndecl, BITS_PER_UNIT, maxalign);
5731 return false;
5733 return true;
5736 case BUILT_IN_CONSTANT_P:
5737 return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
5739 case BUILT_IN_ISFINITE:
5740 case BUILT_IN_ISINF:
5741 case BUILT_IN_ISINF_SIGN:
5742 case BUILT_IN_ISNAN:
5743 case BUILT_IN_ISNORMAL:
5744 case BUILT_IN_SIGNBIT:
5745 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
5747 if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
5749 error_at (ARG_LOCATION (0), "non-floating-point argument in "
5750 "call to function %qE", fndecl);
5751 return false;
5753 return true;
5755 return false;
5757 case BUILT_IN_ISGREATER:
5758 case BUILT_IN_ISGREATEREQUAL:
5759 case BUILT_IN_ISLESS:
5760 case BUILT_IN_ISLESSEQUAL:
5761 case BUILT_IN_ISLESSGREATER:
5762 case BUILT_IN_ISUNORDERED:
5763 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
5765 enum tree_code code0, code1;
5766 code0 = TREE_CODE (TREE_TYPE (args[0]));
5767 code1 = TREE_CODE (TREE_TYPE (args[1]));
5768 if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
5769 || (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
5770 || (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
5772 error_at (loc, "non-floating-point arguments in call to "
5773 "function %qE", fndecl);
5774 return false;
5776 return true;
5778 return false;
5780 case BUILT_IN_FPCLASSIFY:
5781 if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
5783 for (unsigned int i = 0; i < 5; i++)
5784 if (TREE_CODE (args[i]) != INTEGER_CST)
5786 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
5787 "call to function %qE", i + 1, fndecl);
5788 return false;
5791 if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
5793 error_at (ARG_LOCATION (5), "non-floating-point argument in "
5794 "call to function %qE", fndecl);
5795 return false;
5797 return true;
5799 return false;
5801 case BUILT_IN_ASSUME_ALIGNED:
5802 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
5804 if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
5806 error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
5807 "function %qE", fndecl);
5808 return false;
5810 return true;
5812 return false;
5814 case BUILT_IN_ADD_OVERFLOW:
5815 case BUILT_IN_SUB_OVERFLOW:
5816 case BUILT_IN_MUL_OVERFLOW:
5817 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
5819 unsigned i;
5820 for (i = 0; i < 2; i++)
5821 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
5823 error_at (ARG_LOCATION (i), "argument %u in call to function "
5824 "%qE does not have integral type", i + 1, fndecl);
5825 return false;
5827 if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
5828 || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
5830 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5831 "does not have pointer to integral type", fndecl);
5832 return false;
5834 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
5836 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5837 "has pointer to enumerated type", fndecl);
5838 return false;
5840 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
5842 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5843 "has pointer to boolean type", fndecl);
5844 return false;
5846 return true;
5848 return false;
5850 case BUILT_IN_ADD_OVERFLOW_P:
5851 case BUILT_IN_SUB_OVERFLOW_P:
5852 case BUILT_IN_MUL_OVERFLOW_P:
5853 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
5855 unsigned i;
5856 for (i = 0; i < 3; i++)
5857 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
5859 error_at (ARG_LOCATION (i), "argument %u in call to function "
5860 "%qE does not have integral type", i + 1, fndecl);
5861 return false;
5863 if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
5865 error_at (ARG_LOCATION (2), "argument 3 in call to function "
5866 "%qE has enumerated type", fndecl);
5867 return false;
5869 else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
5871 error_at (ARG_LOCATION (2), "argument 3 in call to function "
5872 "%qE has boolean type", fndecl);
5873 return false;
5875 return true;
5877 return false;
5879 default:
5880 return true;
5884 /* Subroutine of c_parse_error.
5885 Return the result of concatenating LHS and RHS. RHS is really
5886 a string literal, its first character is indicated by RHS_START and
5887 RHS_SIZE is its length (including the terminating NUL character).
5889 The caller is responsible for deleting the returned pointer. */
5891 static char *
5892 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
5894 const size_t lhs_size = strlen (lhs);
5895 char *result = XNEWVEC (char, lhs_size + rhs_size);
5896 memcpy (result, lhs, lhs_size);
5897 memcpy (result + lhs_size, rhs_start, rhs_size);
5898 return result;
5901 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
5902 before TOKEN, which had the associated VALUE. */
5904 void
5905 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
5906 tree value, unsigned char token_flags,
5907 rich_location *richloc)
5909 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
5911 char *message = NULL;
5913 if (token_type == CPP_EOF)
5914 message = catenate_messages (gmsgid, " at end of input");
5915 else if (token_type == CPP_CHAR
5916 || token_type == CPP_WCHAR
5917 || token_type == CPP_CHAR16
5918 || token_type == CPP_CHAR32
5919 || token_type == CPP_UTF8CHAR)
5921 unsigned int val = TREE_INT_CST_LOW (value);
5922 const char *prefix;
5924 switch (token_type)
5926 default:
5927 prefix = "";
5928 break;
5929 case CPP_WCHAR:
5930 prefix = "L";
5931 break;
5932 case CPP_CHAR16:
5933 prefix = "u";
5934 break;
5935 case CPP_CHAR32:
5936 prefix = "U";
5937 break;
5938 case CPP_UTF8CHAR:
5939 prefix = "u8";
5940 break;
5943 if (val <= UCHAR_MAX && ISGRAPH (val))
5944 message = catenate_messages (gmsgid, " before %s'%c'");
5945 else
5946 message = catenate_messages (gmsgid, " before %s'\\x%x'");
5948 error_at (richloc, message, prefix, val);
5949 free (message);
5950 message = NULL;
5952 else if (token_type == CPP_CHAR_USERDEF
5953 || token_type == CPP_WCHAR_USERDEF
5954 || token_type == CPP_CHAR16_USERDEF
5955 || token_type == CPP_CHAR32_USERDEF
5956 || token_type == CPP_UTF8CHAR_USERDEF)
5957 message = catenate_messages (gmsgid,
5958 " before user-defined character literal");
5959 else if (token_type == CPP_STRING_USERDEF
5960 || token_type == CPP_WSTRING_USERDEF
5961 || token_type == CPP_STRING16_USERDEF
5962 || token_type == CPP_STRING32_USERDEF
5963 || token_type == CPP_UTF8STRING_USERDEF)
5964 message = catenate_messages (gmsgid, " before user-defined string literal");
5965 else if (token_type == CPP_STRING
5966 || token_type == CPP_WSTRING
5967 || token_type == CPP_STRING16
5968 || token_type == CPP_STRING32
5969 || token_type == CPP_UTF8STRING)
5970 message = catenate_messages (gmsgid, " before string constant");
5971 else if (token_type == CPP_NUMBER)
5972 message = catenate_messages (gmsgid, " before numeric constant");
5973 else if (token_type == CPP_NAME)
5975 message = catenate_messages (gmsgid, " before %qE");
5976 error_at (richloc, message, value);
5977 free (message);
5978 message = NULL;
5980 else if (token_type == CPP_PRAGMA)
5981 message = catenate_messages (gmsgid, " before %<#pragma%>");
5982 else if (token_type == CPP_PRAGMA_EOL)
5983 message = catenate_messages (gmsgid, " before end of line");
5984 else if (token_type == CPP_DECLTYPE)
5985 message = catenate_messages (gmsgid, " before %<decltype%>");
5986 else if (token_type < N_TTYPES)
5988 message = catenate_messages (gmsgid, " before %qs token");
5989 error_at (richloc, message, cpp_type2name (token_type, token_flags));
5990 free (message);
5991 message = NULL;
5993 else
5994 error_at (richloc, gmsgid);
5996 if (message)
5998 error_at (richloc, message);
5999 free (message);
6001 #undef catenate_messages
6004 /* Return the gcc option code associated with the reason for a cpp
6005 message, or 0 if none. */
6007 static int
6008 c_option_controlling_cpp_error (int reason)
6010 const struct cpp_reason_option_codes_t *entry;
6012 for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6014 if (entry->reason == reason)
6015 return entry->option_code;
6017 return 0;
6020 /* Callback from cpp_error for PFILE to print diagnostics from the
6021 preprocessor. The diagnostic is of type LEVEL, with REASON set
6022 to the reason code if LEVEL is represents a warning, at location
6023 RICHLOC unless this is after lexing and the compiler's location
6024 should be used instead; MSG is the translated message and AP
6025 the arguments. Returns true if a diagnostic was emitted, false
6026 otherwise. */
6028 bool
6029 c_cpp_error (cpp_reader *pfile ATTRIBUTE_UNUSED, int level, int reason,
6030 rich_location *richloc,
6031 const char *msg, va_list *ap)
6033 diagnostic_info diagnostic;
6034 diagnostic_t dlevel;
6035 bool save_warn_system_headers = global_dc->dc_warn_system_headers;
6036 bool ret;
6038 switch (level)
6040 case CPP_DL_WARNING_SYSHDR:
6041 if (flag_no_output)
6042 return false;
6043 global_dc->dc_warn_system_headers = 1;
6044 /* Fall through. */
6045 case CPP_DL_WARNING:
6046 if (flag_no_output)
6047 return false;
6048 dlevel = DK_WARNING;
6049 break;
6050 case CPP_DL_PEDWARN:
6051 if (flag_no_output && !flag_pedantic_errors)
6052 return false;
6053 dlevel = DK_PEDWARN;
6054 break;
6055 case CPP_DL_ERROR:
6056 dlevel = DK_ERROR;
6057 break;
6058 case CPP_DL_ICE:
6059 dlevel = DK_ICE;
6060 break;
6061 case CPP_DL_NOTE:
6062 dlevel = DK_NOTE;
6063 break;
6064 case CPP_DL_FATAL:
6065 dlevel = DK_FATAL;
6066 break;
6067 default:
6068 gcc_unreachable ();
6070 if (done_lexing)
6071 richloc->set_range (line_table, 0, input_location, true);
6072 diagnostic_set_info_translated (&diagnostic, msg, ap,
6073 richloc, dlevel);
6074 diagnostic_override_option_index (&diagnostic,
6075 c_option_controlling_cpp_error (reason));
6076 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6077 if (level == CPP_DL_WARNING_SYSHDR)
6078 global_dc->dc_warn_system_headers = save_warn_system_headers;
6079 return ret;
6082 /* Convert a character from the host to the target execution character
6083 set. cpplib handles this, mostly. */
6085 HOST_WIDE_INT
6086 c_common_to_target_charset (HOST_WIDE_INT c)
6088 /* Character constants in GCC proper are sign-extended under -fsigned-char,
6089 zero-extended under -fno-signed-char. cpplib insists that characters
6090 and character constants are always unsigned. Hence we must convert
6091 back and forth. */
6092 cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6094 uc = cpp_host_to_exec_charset (parse_in, uc);
6096 if (flag_signed_char)
6097 return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6098 >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6099 else
6100 return uc;
6103 /* Fold an offsetof-like expression. EXPR is a nested sequence of component
6104 references with an INDIRECT_REF of a constant at the bottom; much like the
6105 traditional rendering of offsetof as a macro. Return the folded result. */
6107 tree
6108 fold_offsetof_1 (tree expr, enum tree_code ctx)
6110 tree base, off, t;
6111 tree_code code = TREE_CODE (expr);
6112 switch (code)
6114 case ERROR_MARK:
6115 return expr;
6117 case VAR_DECL:
6118 error ("cannot apply %<offsetof%> to static data member %qD", expr);
6119 return error_mark_node;
6121 case CALL_EXPR:
6122 case TARGET_EXPR:
6123 error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6124 return error_mark_node;
6126 case NOP_EXPR:
6127 case INDIRECT_REF:
6128 if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6130 error ("cannot apply %<offsetof%> to a non constant address");
6131 return error_mark_node;
6133 return TREE_OPERAND (expr, 0);
6135 case COMPONENT_REF:
6136 base = fold_offsetof_1 (TREE_OPERAND (expr, 0), code);
6137 if (base == error_mark_node)
6138 return base;
6140 t = TREE_OPERAND (expr, 1);
6141 if (DECL_C_BIT_FIELD (t))
6143 error ("attempt to take address of bit-field structure "
6144 "member %qD", t);
6145 return error_mark_node;
6147 off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6148 size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6149 / BITS_PER_UNIT));
6150 break;
6152 case ARRAY_REF:
6153 base = fold_offsetof_1 (TREE_OPERAND (expr, 0), code);
6154 if (base == error_mark_node)
6155 return base;
6157 t = TREE_OPERAND (expr, 1);
6159 /* Check if the offset goes beyond the upper bound of the array. */
6160 if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6162 tree upbound = array_ref_up_bound (expr);
6163 if (upbound != NULL_TREE
6164 && TREE_CODE (upbound) == INTEGER_CST
6165 && !tree_int_cst_equal (upbound,
6166 TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6168 if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6169 upbound = size_binop (PLUS_EXPR, upbound,
6170 build_int_cst (TREE_TYPE (upbound), 1));
6171 if (tree_int_cst_lt (upbound, t))
6173 tree v;
6175 for (v = TREE_OPERAND (expr, 0);
6176 TREE_CODE (v) == COMPONENT_REF;
6177 v = TREE_OPERAND (v, 0))
6178 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6179 == RECORD_TYPE)
6181 tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6182 for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6183 if (TREE_CODE (fld_chain) == FIELD_DECL)
6184 break;
6186 if (fld_chain)
6187 break;
6189 /* Don't warn if the array might be considered a poor
6190 man's flexible array member with a very permissive
6191 definition thereof. */
6192 if (TREE_CODE (v) == ARRAY_REF
6193 || TREE_CODE (v) == COMPONENT_REF)
6194 warning (OPT_Warray_bounds,
6195 "index %E denotes an offset "
6196 "greater than size of %qT",
6197 t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6202 t = convert (sizetype, t);
6203 off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6204 break;
6206 case COMPOUND_EXPR:
6207 /* Handle static members of volatile structs. */
6208 t = TREE_OPERAND (expr, 1);
6209 gcc_assert (VAR_P (t));
6210 return fold_offsetof_1 (t);
6212 default:
6213 gcc_unreachable ();
6216 return fold_build_pointer_plus (base, off);
6219 /* Likewise, but convert it to the return type of offsetof. */
6221 tree
6222 fold_offsetof (tree expr)
6224 return convert (size_type_node, fold_offsetof_1 (expr));
6228 /* *PTYPE is an incomplete array. Complete it with a domain based on
6229 INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6230 is true. Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6231 2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty. */
6234 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6236 tree maxindex, type, main_type, elt, unqual_elt;
6237 int failure = 0, quals;
6238 bool overflow_p = false;
6240 maxindex = size_zero_node;
6241 if (initial_value)
6243 if (TREE_CODE (initial_value) == STRING_CST)
6245 int eltsize
6246 = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6247 maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6249 else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6251 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6253 if (vec_safe_is_empty (v))
6255 if (pedantic)
6256 failure = 3;
6257 maxindex = ssize_int (-1);
6259 else
6261 tree curindex;
6262 unsigned HOST_WIDE_INT cnt;
6263 constructor_elt *ce;
6264 bool fold_p = false;
6266 if ((*v)[0].index)
6267 maxindex = (*v)[0].index, fold_p = true;
6269 curindex = maxindex;
6271 for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
6273 bool curfold_p = false;
6274 if (ce->index)
6275 curindex = ce->index, curfold_p = true;
6276 else
6278 if (fold_p)
6280 /* Since we treat size types now as ordinary
6281 unsigned types, we need an explicit overflow
6282 check. */
6283 tree orig = curindex;
6284 curindex = fold_convert (sizetype, curindex);
6285 overflow_p |= tree_int_cst_lt (curindex, orig);
6287 curindex = size_binop (PLUS_EXPR, curindex,
6288 size_one_node);
6290 if (tree_int_cst_lt (maxindex, curindex))
6291 maxindex = curindex, fold_p = curfold_p;
6293 if (fold_p)
6295 tree orig = maxindex;
6296 maxindex = fold_convert (sizetype, maxindex);
6297 overflow_p |= tree_int_cst_lt (maxindex, orig);
6301 else
6303 /* Make an error message unless that happened already. */
6304 if (initial_value != error_mark_node)
6305 failure = 1;
6308 else
6310 failure = 2;
6311 if (!do_default)
6312 return failure;
6315 type = *ptype;
6316 elt = TREE_TYPE (type);
6317 quals = TYPE_QUALS (strip_array_types (elt));
6318 if (quals == 0)
6319 unqual_elt = elt;
6320 else
6321 unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
6323 /* Using build_distinct_type_copy and modifying things afterward instead
6324 of using build_array_type to create a new type preserves all of the
6325 TYPE_LANG_FLAG_? bits that the front end may have set. */
6326 main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
6327 TREE_TYPE (main_type) = unqual_elt;
6328 TYPE_DOMAIN (main_type)
6329 = build_range_type (TREE_TYPE (maxindex),
6330 build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
6331 TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
6332 layout_type (main_type);
6334 /* Make sure we have the canonical MAIN_TYPE. */
6335 hashval_t hashcode = type_hash_canon_hash (main_type);
6336 main_type = type_hash_canon (hashcode, main_type);
6338 /* Fix the canonical type. */
6339 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
6340 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
6341 SET_TYPE_STRUCTURAL_EQUALITY (main_type);
6342 else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
6343 || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
6344 != TYPE_DOMAIN (main_type)))
6345 TYPE_CANONICAL (main_type)
6346 = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
6347 TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
6348 TYPE_TYPELESS_STORAGE (main_type));
6349 else
6350 TYPE_CANONICAL (main_type) = main_type;
6352 if (quals == 0)
6353 type = main_type;
6354 else
6355 type = c_build_qualified_type (main_type, quals);
6357 if (COMPLETE_TYPE_P (type)
6358 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
6359 && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
6361 error ("size of array is too large");
6362 /* If we proceed with the array type as it is, we'll eventually
6363 crash in tree_to_[su]hwi(). */
6364 type = error_mark_node;
6367 *ptype = type;
6368 return failure;
6371 /* Like c_mark_addressable but don't check register qualifier. */
6372 void
6373 c_common_mark_addressable_vec (tree t)
6375 if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
6376 t = C_MAYBE_CONST_EXPR_EXPR (t);
6377 while (handled_component_p (t))
6378 t = TREE_OPERAND (t, 0);
6379 if (!VAR_P (t)
6380 && TREE_CODE (t) != PARM_DECL
6381 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR)
6382 return;
6383 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
6384 TREE_ADDRESSABLE (t) = 1;
6389 /* Used to help initialize the builtin-types.def table. When a type of
6390 the correct size doesn't exist, use error_mark_node instead of NULL.
6391 The later results in segfaults even when a decl using the type doesn't
6392 get invoked. */
6394 tree
6395 builtin_type_for_size (int size, bool unsignedp)
6397 tree type = c_common_type_for_size (size, unsignedp);
6398 return type ? type : error_mark_node;
6401 /* A helper function for resolve_overloaded_builtin in resolving the
6402 overloaded __sync_ builtins. Returns a positive power of 2 if the
6403 first operand of PARAMS is a pointer to a supported data type.
6404 Returns 0 if an error is encountered.
6405 FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
6406 built-ins. */
6408 static int
6409 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch)
6411 /* Type of the argument. */
6412 tree argtype;
6413 /* Type the argument points to. */
6414 tree type;
6415 int size;
6417 if (vec_safe_is_empty (params))
6419 error ("too few arguments to function %qE", function);
6420 return 0;
6423 argtype = type = TREE_TYPE ((*params)[0]);
6424 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6426 /* Force array-to-pointer decay for C++. */
6427 (*params)[0] = default_conversion ((*params)[0]);
6428 type = TREE_TYPE ((*params)[0]);
6430 if (TREE_CODE (type) != POINTER_TYPE)
6431 goto incompatible;
6433 type = TREE_TYPE (type);
6434 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
6435 goto incompatible;
6437 if (!COMPLETE_TYPE_P (type))
6438 goto incompatible;
6440 if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
6441 goto incompatible;
6443 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
6444 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
6445 return size;
6447 incompatible:
6448 /* Issue the diagnostic only if the argument is valid, otherwise
6449 it would be redundant at best and could be misleading. */
6450 if (argtype != error_mark_node)
6451 error ("operand type %qT is incompatible with argument %d of %qE",
6452 argtype, 1, function);
6453 return 0;
6456 /* A helper function for resolve_overloaded_builtin. Adds casts to
6457 PARAMS to make arguments match up with those of FUNCTION. Drops
6458 the variadic arguments at the end. Returns false if some error
6459 was encountered; true on success. */
6461 static bool
6462 sync_resolve_params (location_t loc, tree orig_function, tree function,
6463 vec<tree, va_gc> *params, bool orig_format)
6465 function_args_iterator iter;
6466 tree ptype;
6467 unsigned int parmnum;
6469 function_args_iter_init (&iter, TREE_TYPE (function));
6470 /* We've declared the implementation functions to use "volatile void *"
6471 as the pointer parameter, so we shouldn't get any complaints from the
6472 call to check_function_arguments what ever type the user used. */
6473 function_args_iter_next (&iter);
6474 ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
6475 ptype = TYPE_MAIN_VARIANT (ptype);
6477 /* For the rest of the values, we need to cast these to FTYPE, so that we
6478 don't get warnings for passing pointer types, etc. */
6479 parmnum = 0;
6480 while (1)
6482 tree val, arg_type;
6484 arg_type = function_args_iter_cond (&iter);
6485 /* XXX void_type_node belies the abstraction. */
6486 if (arg_type == void_type_node)
6487 break;
6489 ++parmnum;
6490 if (params->length () <= parmnum)
6492 error_at (loc, "too few arguments to function %qE", orig_function);
6493 return false;
6496 /* Only convert parameters if arg_type is unsigned integer type with
6497 new format sync routines, i.e. don't attempt to convert pointer
6498 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
6499 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
6500 kinds). */
6501 if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
6503 /* Ideally for the first conversion we'd use convert_for_assignment
6504 so that we get warnings for anything that doesn't match the pointer
6505 type. This isn't portable across the C and C++ front ends atm. */
6506 val = (*params)[parmnum];
6507 val = convert (ptype, val);
6508 val = convert (arg_type, val);
6509 (*params)[parmnum] = val;
6512 function_args_iter_next (&iter);
6515 /* __atomic routines are not variadic. */
6516 if (!orig_format && params->length () != parmnum + 1)
6518 error_at (loc, "too many arguments to function %qE", orig_function);
6519 return false;
6522 /* The definition of these primitives is variadic, with the remaining
6523 being "an optional list of variables protected by the memory barrier".
6524 No clue what that's supposed to mean, precisely, but we consider all
6525 call-clobbered variables to be protected so we're safe. */
6526 params->truncate (parmnum + 1);
6528 return true;
6531 /* A helper function for resolve_overloaded_builtin. Adds a cast to
6532 RESULT to make it match the type of the first pointer argument in
6533 PARAMS. */
6535 static tree
6536 sync_resolve_return (tree first_param, tree result, bool orig_format)
6538 tree ptype = TREE_TYPE (TREE_TYPE (first_param));
6539 tree rtype = TREE_TYPE (result);
6540 ptype = TYPE_MAIN_VARIANT (ptype);
6542 /* New format doesn't require casting unless the types are the same size. */
6543 if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
6544 return convert (ptype, result);
6545 else
6546 return result;
6549 /* This function verifies the PARAMS to generic atomic FUNCTION.
6550 It returns the size if all the parameters are the same size, otherwise
6551 0 is returned if the parameters are invalid. */
6553 static int
6554 get_atomic_generic_size (location_t loc, tree function,
6555 vec<tree, va_gc> *params)
6557 unsigned int n_param;
6558 unsigned int n_model;
6559 unsigned int x;
6560 int size_0;
6561 tree type_0;
6563 /* Determine the parameter makeup. */
6564 switch (DECL_FUNCTION_CODE (function))
6566 case BUILT_IN_ATOMIC_EXCHANGE:
6567 n_param = 4;
6568 n_model = 1;
6569 break;
6570 case BUILT_IN_ATOMIC_LOAD:
6571 case BUILT_IN_ATOMIC_STORE:
6572 n_param = 3;
6573 n_model = 1;
6574 break;
6575 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
6576 n_param = 6;
6577 n_model = 2;
6578 break;
6579 default:
6580 gcc_unreachable ();
6583 if (vec_safe_length (params) != n_param)
6585 error_at (loc, "incorrect number of arguments to function %qE", function);
6586 return 0;
6589 /* Get type of first parameter, and determine its size. */
6590 type_0 = TREE_TYPE ((*params)[0]);
6591 if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
6593 /* Force array-to-pointer decay for C++. */
6594 (*params)[0] = default_conversion ((*params)[0]);
6595 type_0 = TREE_TYPE ((*params)[0]);
6597 if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
6599 error_at (loc, "argument 1 of %qE must be a non-void pointer type",
6600 function);
6601 return 0;
6604 /* Types must be compile time constant sizes. */
6605 if (TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))) != INTEGER_CST)
6607 error_at (loc,
6608 "argument 1 of %qE must be a pointer to a constant size type",
6609 function);
6610 return 0;
6613 size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
6615 /* Zero size objects are not allowed. */
6616 if (size_0 == 0)
6618 error_at (loc,
6619 "argument 1 of %qE must be a pointer to a nonzero size object",
6620 function);
6621 return 0;
6624 /* Check each other parameter is a pointer and the same size. */
6625 for (x = 0; x < n_param - n_model; x++)
6627 int size;
6628 tree type = TREE_TYPE ((*params)[x]);
6629 /* __atomic_compare_exchange has a bool in the 4th position, skip it. */
6630 if (n_param == 6 && x == 3)
6631 continue;
6632 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6634 /* Force array-to-pointer decay for C++. */
6635 (*params)[x] = default_conversion ((*params)[x]);
6636 type = TREE_TYPE ((*params)[x]);
6638 if (!POINTER_TYPE_P (type))
6640 error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
6641 function);
6642 return 0;
6644 else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
6645 && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
6646 != INTEGER_CST)
6648 error_at (loc, "argument %d of %qE must be a pointer to a constant "
6649 "size type", x + 1, function);
6650 return 0;
6652 else if (FUNCTION_POINTER_TYPE_P (type))
6654 error_at (loc, "argument %d of %qE must not be a pointer to a "
6655 "function", x + 1, function);
6656 return 0;
6658 tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
6659 size = type_size ? tree_to_uhwi (type_size) : 0;
6660 if (size != size_0)
6662 error_at (loc, "size mismatch in argument %d of %qE", x + 1,
6663 function);
6664 return 0;
6668 /* Check memory model parameters for validity. */
6669 for (x = n_param - n_model ; x < n_param; x++)
6671 tree p = (*params)[x];
6672 if (TREE_CODE (p) == INTEGER_CST)
6674 /* memmodel_base masks the low 16 bits, thus ignore any bits above
6675 it by using TREE_INT_CST_LOW instead of tree_to_*hwi. Those high
6676 bits will be checked later during expansion in target specific
6677 way. */
6678 if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
6679 warning_at (loc, OPT_Winvalid_memory_model,
6680 "invalid memory model argument %d of %qE", x + 1,
6681 function);
6683 else
6684 if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
6686 error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
6687 function);
6688 return 0;
6692 return size_0;
6696 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
6697 at the beginning of the parameter list PARAMS representing the size of the
6698 objects. This is to match the library ABI requirement. LOC is the location
6699 of the function call.
6700 The new function is returned if it needed rebuilding, otherwise NULL_TREE is
6701 returned to allow the external call to be constructed. */
6703 static tree
6704 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
6705 vec<tree, va_gc> *params)
6707 tree size_node;
6709 /* Insert a SIZE_T parameter as the first param. If there isn't
6710 enough space, allocate a new vector and recursively re-build with that. */
6711 if (!params->space (1))
6713 unsigned int z, len;
6714 vec<tree, va_gc> *v;
6715 tree f;
6717 len = params->length ();
6718 vec_alloc (v, len + 1);
6719 v->quick_push (build_int_cst (size_type_node, n));
6720 for (z = 0; z < len; z++)
6721 v->quick_push ((*params)[z]);
6722 f = build_function_call_vec (loc, vNULL, function, v, NULL);
6723 vec_free (v);
6724 return f;
6727 /* Add the size parameter and leave as a function call for processing. */
6728 size_node = build_int_cst (size_type_node, n);
6729 params->quick_insert (0, size_node);
6730 return NULL_TREE;
6734 /* Return whether atomic operations for naturally aligned N-byte
6735 arguments are supported, whether inline or through libatomic. */
6736 static bool
6737 atomic_size_supported_p (int n)
6739 switch (n)
6741 case 1:
6742 case 2:
6743 case 4:
6744 case 8:
6745 return true;
6747 case 16:
6748 return targetm.scalar_mode_supported_p (TImode);
6750 default:
6751 return false;
6755 /* This will process an __atomic_exchange function call, determine whether it
6756 needs to be mapped to the _N variation, or turned into a library call.
6757 LOC is the location of the builtin call.
6758 FUNCTION is the DECL that has been invoked;
6759 PARAMS is the argument list for the call. The return value is non-null
6760 TRUE is returned if it is translated into the proper format for a call to the
6761 external library, and NEW_RETURN is set the tree for that function.
6762 FALSE is returned if processing for the _N variation is required, and
6763 NEW_RETURN is set to the return value the result is copied into. */
6764 static bool
6765 resolve_overloaded_atomic_exchange (location_t loc, tree function,
6766 vec<tree, va_gc> *params, tree *new_return)
6768 tree p0, p1, p2, p3;
6769 tree I_type, I_type_ptr;
6770 int n = get_atomic_generic_size (loc, function, params);
6772 /* Size of 0 is an error condition. */
6773 if (n == 0)
6775 *new_return = error_mark_node;
6776 return true;
6779 /* If not a lock-free size, change to the library generic format. */
6780 if (!atomic_size_supported_p (n))
6782 *new_return = add_atomic_size_parameter (n, loc, function, params);
6783 return true;
6786 /* Otherwise there is a lockfree match, transform the call from:
6787 void fn(T* mem, T* desired, T* return, model)
6788 into
6789 *return = (T) (fn (In* mem, (In) *desired, model)) */
6791 p0 = (*params)[0];
6792 p1 = (*params)[1];
6793 p2 = (*params)[2];
6794 p3 = (*params)[3];
6796 /* Create pointer to appropriate size. */
6797 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6798 I_type_ptr = build_pointer_type (I_type);
6800 /* Convert object pointer to required type. */
6801 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6802 (*params)[0] = p0;
6803 /* Convert new value to required type, and dereference it. */
6804 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
6805 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
6806 (*params)[1] = p1;
6808 /* Move memory model to the 3rd position, and end param list. */
6809 (*params)[2] = p3;
6810 params->truncate (3);
6812 /* Convert return pointer and dereference it for later assignment. */
6813 *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
6815 return false;
6819 /* This will process an __atomic_compare_exchange function call, determine
6820 whether it needs to be mapped to the _N variation, or turned into a lib call.
6821 LOC is the location of the builtin call.
6822 FUNCTION is the DECL that has been invoked;
6823 PARAMS is the argument list for the call. The return value is non-null
6824 TRUE is returned if it is translated into the proper format for a call to the
6825 external library, and NEW_RETURN is set the tree for that function.
6826 FALSE is returned if processing for the _N variation is required. */
6828 static bool
6829 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
6830 vec<tree, va_gc> *params,
6831 tree *new_return)
6833 tree p0, p1, p2;
6834 tree I_type, I_type_ptr;
6835 int n = get_atomic_generic_size (loc, function, params);
6837 /* Size of 0 is an error condition. */
6838 if (n == 0)
6840 *new_return = error_mark_node;
6841 return true;
6844 /* If not a lock-free size, change to the library generic format. */
6845 if (!atomic_size_supported_p (n))
6847 /* The library generic format does not have the weak parameter, so
6848 remove it from the param list. Since a parameter has been removed,
6849 we can be sure that there is room for the SIZE_T parameter, meaning
6850 there will not be a recursive rebuilding of the parameter list, so
6851 there is no danger this will be done twice. */
6852 if (n > 0)
6854 (*params)[3] = (*params)[4];
6855 (*params)[4] = (*params)[5];
6856 params->truncate (5);
6858 *new_return = add_atomic_size_parameter (n, loc, function, params);
6859 return true;
6862 /* Otherwise, there is a match, so the call needs to be transformed from:
6863 bool fn(T* mem, T* desired, T* return, weak, success, failure)
6864 into
6865 bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail) */
6867 p0 = (*params)[0];
6868 p1 = (*params)[1];
6869 p2 = (*params)[2];
6871 /* Create pointer to appropriate size. */
6872 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6873 I_type_ptr = build_pointer_type (I_type);
6875 /* Convert object pointer to required type. */
6876 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6877 (*params)[0] = p0;
6879 /* Convert expected pointer to required type. */
6880 p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
6881 (*params)[1] = p1;
6883 /* Convert desired value to required type, and dereference it. */
6884 p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
6885 p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
6886 (*params)[2] = p2;
6888 /* The rest of the parameters are fine. NULL means no special return value
6889 processing.*/
6890 *new_return = NULL;
6891 return false;
6895 /* This will process an __atomic_load function call, determine whether it
6896 needs to be mapped to the _N variation, or turned into a library call.
6897 LOC is the location of the builtin call.
6898 FUNCTION is the DECL that has been invoked;
6899 PARAMS is the argument list for the call. The return value is non-null
6900 TRUE is returned if it is translated into the proper format for a call to the
6901 external library, and NEW_RETURN is set the tree for that function.
6902 FALSE is returned if processing for the _N variation is required, and
6903 NEW_RETURN is set to the return value the result is copied into. */
6905 static bool
6906 resolve_overloaded_atomic_load (location_t loc, tree function,
6907 vec<tree, va_gc> *params, tree *new_return)
6909 tree p0, p1, p2;
6910 tree I_type, I_type_ptr;
6911 int n = get_atomic_generic_size (loc, function, params);
6913 /* Size of 0 is an error condition. */
6914 if (n == 0)
6916 *new_return = error_mark_node;
6917 return true;
6920 /* If not a lock-free size, change to the library generic format. */
6921 if (!atomic_size_supported_p (n))
6923 *new_return = add_atomic_size_parameter (n, loc, function, params);
6924 return true;
6927 /* Otherwise, there is a match, so the call needs to be transformed from:
6928 void fn(T* mem, T* return, model)
6929 into
6930 *return = (T) (fn ((In *) mem, model)) */
6932 p0 = (*params)[0];
6933 p1 = (*params)[1];
6934 p2 = (*params)[2];
6936 /* Create pointer to appropriate size. */
6937 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6938 I_type_ptr = build_pointer_type (I_type);
6940 /* Convert object pointer to required type. */
6941 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6942 (*params)[0] = p0;
6944 /* Move memory model to the 2nd position, and end param list. */
6945 (*params)[1] = p2;
6946 params->truncate (2);
6948 /* Convert return pointer and dereference it for later assignment. */
6949 *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
6951 return false;
6955 /* This will process an __atomic_store function call, determine whether it
6956 needs to be mapped to the _N variation, or turned into a library call.
6957 LOC is the location of the builtin call.
6958 FUNCTION is the DECL that has been invoked;
6959 PARAMS is the argument list for the call. The return value is non-null
6960 TRUE is returned if it is translated into the proper format for a call to the
6961 external library, and NEW_RETURN is set the tree for that function.
6962 FALSE is returned if processing for the _N variation is required, and
6963 NEW_RETURN is set to the return value the result is copied into. */
6965 static bool
6966 resolve_overloaded_atomic_store (location_t loc, tree function,
6967 vec<tree, va_gc> *params, tree *new_return)
6969 tree p0, p1;
6970 tree I_type, I_type_ptr;
6971 int n = get_atomic_generic_size (loc, function, params);
6973 /* Size of 0 is an error condition. */
6974 if (n == 0)
6976 *new_return = error_mark_node;
6977 return true;
6980 /* If not a lock-free size, change to the library generic format. */
6981 if (!atomic_size_supported_p (n))
6983 *new_return = add_atomic_size_parameter (n, loc, function, params);
6984 return true;
6987 /* Otherwise, there is a match, so the call needs to be transformed from:
6988 void fn(T* mem, T* value, model)
6989 into
6990 fn ((In *) mem, (In) *value, model) */
6992 p0 = (*params)[0];
6993 p1 = (*params)[1];
6995 /* Create pointer to appropriate size. */
6996 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6997 I_type_ptr = build_pointer_type (I_type);
6999 /* Convert object pointer to required type. */
7000 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7001 (*params)[0] = p0;
7003 /* Convert new value to required type, and dereference it. */
7004 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7005 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7006 (*params)[1] = p1;
7008 /* The memory model is in the right spot already. Return is void. */
7009 *new_return = NULL_TREE;
7011 return false;
7015 /* Some builtin functions are placeholders for other expressions. This
7016 function should be called immediately after parsing the call expression
7017 before surrounding code has committed to the type of the expression.
7019 LOC is the location of the builtin call.
7021 FUNCTION is the DECL that has been invoked; it is known to be a builtin.
7022 PARAMS is the argument list for the call. The return value is non-null
7023 when expansion is complete, and null if normal processing should
7024 continue. */
7026 tree
7027 resolve_overloaded_builtin (location_t loc, tree function,
7028 vec<tree, va_gc> *params)
7030 enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
7032 /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
7033 Those are not valid to call with a pointer to _Bool (or C++ bool)
7034 and so must be rejected. */
7035 bool fetch_op = true;
7036 bool orig_format = true;
7037 tree new_return = NULL_TREE;
7039 switch (DECL_BUILT_IN_CLASS (function))
7041 case BUILT_IN_NORMAL:
7042 break;
7043 case BUILT_IN_MD:
7044 if (targetm.resolve_overloaded_builtin)
7045 return targetm.resolve_overloaded_builtin (loc, function, params);
7046 else
7047 return NULL_TREE;
7048 default:
7049 return NULL_TREE;
7052 /* Handle BUILT_IN_NORMAL here. */
7053 switch (orig_code)
7055 case BUILT_IN_ATOMIC_EXCHANGE:
7056 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7057 case BUILT_IN_ATOMIC_LOAD:
7058 case BUILT_IN_ATOMIC_STORE:
7060 /* Handle these 4 together so that they can fall through to the next
7061 case if the call is transformed to an _N variant. */
7062 switch (orig_code)
7064 case BUILT_IN_ATOMIC_EXCHANGE:
7066 if (resolve_overloaded_atomic_exchange (loc, function, params,
7067 &new_return))
7068 return new_return;
7069 /* Change to the _N variant. */
7070 orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
7071 break;
7074 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7076 if (resolve_overloaded_atomic_compare_exchange (loc, function,
7077 params,
7078 &new_return))
7079 return new_return;
7080 /* Change to the _N variant. */
7081 orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
7082 break;
7084 case BUILT_IN_ATOMIC_LOAD:
7086 if (resolve_overloaded_atomic_load (loc, function, params,
7087 &new_return))
7088 return new_return;
7089 /* Change to the _N variant. */
7090 orig_code = BUILT_IN_ATOMIC_LOAD_N;
7091 break;
7093 case BUILT_IN_ATOMIC_STORE:
7095 if (resolve_overloaded_atomic_store (loc, function, params,
7096 &new_return))
7097 return new_return;
7098 /* Change to the _N variant. */
7099 orig_code = BUILT_IN_ATOMIC_STORE_N;
7100 break;
7102 default:
7103 gcc_unreachable ();
7106 /* FALLTHRU */
7107 case BUILT_IN_ATOMIC_EXCHANGE_N:
7108 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
7109 case BUILT_IN_ATOMIC_LOAD_N:
7110 case BUILT_IN_ATOMIC_STORE_N:
7111 fetch_op = false;
7112 /* FALLTHRU */
7113 case BUILT_IN_ATOMIC_ADD_FETCH_N:
7114 case BUILT_IN_ATOMIC_SUB_FETCH_N:
7115 case BUILT_IN_ATOMIC_AND_FETCH_N:
7116 case BUILT_IN_ATOMIC_NAND_FETCH_N:
7117 case BUILT_IN_ATOMIC_XOR_FETCH_N:
7118 case BUILT_IN_ATOMIC_OR_FETCH_N:
7119 case BUILT_IN_ATOMIC_FETCH_ADD_N:
7120 case BUILT_IN_ATOMIC_FETCH_SUB_N:
7121 case BUILT_IN_ATOMIC_FETCH_AND_N:
7122 case BUILT_IN_ATOMIC_FETCH_NAND_N:
7123 case BUILT_IN_ATOMIC_FETCH_XOR_N:
7124 case BUILT_IN_ATOMIC_FETCH_OR_N:
7125 orig_format = false;
7126 /* FALLTHRU */
7127 case BUILT_IN_SYNC_FETCH_AND_ADD_N:
7128 case BUILT_IN_SYNC_FETCH_AND_SUB_N:
7129 case BUILT_IN_SYNC_FETCH_AND_OR_N:
7130 case BUILT_IN_SYNC_FETCH_AND_AND_N:
7131 case BUILT_IN_SYNC_FETCH_AND_XOR_N:
7132 case BUILT_IN_SYNC_FETCH_AND_NAND_N:
7133 case BUILT_IN_SYNC_ADD_AND_FETCH_N:
7134 case BUILT_IN_SYNC_SUB_AND_FETCH_N:
7135 case BUILT_IN_SYNC_OR_AND_FETCH_N:
7136 case BUILT_IN_SYNC_AND_AND_FETCH_N:
7137 case BUILT_IN_SYNC_XOR_AND_FETCH_N:
7138 case BUILT_IN_SYNC_NAND_AND_FETCH_N:
7139 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
7140 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
7141 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
7142 case BUILT_IN_SYNC_LOCK_RELEASE_N:
7144 /* The following are not _FETCH_OPs and must be accepted with
7145 pointers to _Bool (or C++ bool). */
7146 if (fetch_op)
7147 fetch_op =
7148 (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7149 && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
7150 && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
7151 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
7153 int n = sync_resolve_size (function, params, fetch_op);
7154 tree new_function, first_param, result;
7155 enum built_in_function fncode;
7157 if (n == 0)
7158 return error_mark_node;
7160 fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
7161 new_function = builtin_decl_explicit (fncode);
7162 if (!sync_resolve_params (loc, function, new_function, params,
7163 orig_format))
7164 return error_mark_node;
7166 first_param = (*params)[0];
7167 result = build_function_call_vec (loc, vNULL, new_function, params,
7168 NULL);
7169 if (result == error_mark_node)
7170 return result;
7171 if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7172 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
7173 && orig_code != BUILT_IN_ATOMIC_STORE_N
7174 && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
7175 result = sync_resolve_return (first_param, result, orig_format);
7177 if (fetch_op)
7178 /* Prevent -Wunused-value warning. */
7179 TREE_USED (result) = true;
7181 /* If new_return is set, assign function to that expr and cast the
7182 result to void since the generic interface returned void. */
7183 if (new_return)
7185 /* Cast function result from I{1,2,4,8,16} to the required type. */
7186 result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
7187 result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
7188 result);
7189 TREE_SIDE_EFFECTS (result) = 1;
7190 protected_set_expr_location (result, loc);
7191 result = convert (void_type_node, result);
7193 return result;
7196 default:
7197 return NULL_TREE;
7201 /* vector_types_compatible_elements_p is used in type checks of vectors
7202 values used as operands of binary operators. Where it returns true, and
7203 the other checks of the caller succeed (being vector types in he first
7204 place, and matching number of elements), we can just treat the types
7205 as essentially the same.
7206 Contrast with vector_targets_convertible_p, which is used for vector
7207 pointer types, and vector_types_convertible_p, which will allow
7208 language-specific matches under the control of flag_lax_vector_conversions,
7209 and might still require a conversion. */
7210 /* True if vector types T1 and T2 can be inputs to the same binary
7211 operator without conversion.
7212 We don't check the overall vector size here because some of our callers
7213 want to give different error messages when the vectors are compatible
7214 except for the element count. */
7216 bool
7217 vector_types_compatible_elements_p (tree t1, tree t2)
7219 bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
7220 t1 = TREE_TYPE (t1);
7221 t2 = TREE_TYPE (t2);
7223 enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
7225 gcc_assert ((c1 == INTEGER_TYPE || c1 == REAL_TYPE || c1 == FIXED_POINT_TYPE)
7226 && (c2 == INTEGER_TYPE || c2 == REAL_TYPE
7227 || c2 == FIXED_POINT_TYPE));
7229 t1 = c_common_signed_type (t1);
7230 t2 = c_common_signed_type (t2);
7231 /* Equality works here because c_common_signed_type uses
7232 TYPE_MAIN_VARIANT. */
7233 if (t1 == t2)
7234 return true;
7235 if (opaque && c1 == c2
7236 && (c1 == INTEGER_TYPE || c1 == REAL_TYPE)
7237 && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
7238 return true;
7239 return false;
7242 /* Check for missing format attributes on function pointers. LTYPE is
7243 the new type or left-hand side type. RTYPE is the old type or
7244 right-hand side type. Returns TRUE if LTYPE is missing the desired
7245 attribute. */
7247 bool
7248 check_missing_format_attribute (tree ltype, tree rtype)
7250 tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
7251 tree ra;
7253 for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
7254 if (is_attribute_p ("format", TREE_PURPOSE (ra)))
7255 break;
7256 if (ra)
7258 tree la;
7259 for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
7260 if (is_attribute_p ("format", TREE_PURPOSE (la)))
7261 break;
7262 return !la;
7264 else
7265 return false;
7268 /* Setup a TYPE_DECL node as a typedef representation.
7270 X is a TYPE_DECL for a typedef statement. Create a brand new
7271 ..._TYPE node (which will be just a variant of the existing
7272 ..._TYPE node with identical properties) and then install X
7273 as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
7275 The whole point here is to end up with a situation where each
7276 and every ..._TYPE node the compiler creates will be uniquely
7277 associated with AT MOST one node representing a typedef name.
7278 This way, even though the compiler substitutes corresponding
7279 ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
7280 early on, later parts of the compiler can always do the reverse
7281 translation and get back the corresponding typedef name. For
7282 example, given:
7284 typedef struct S MY_TYPE;
7285 MY_TYPE object;
7287 Later parts of the compiler might only know that `object' was of
7288 type `struct S' if it were not for code just below. With this
7289 code however, later parts of the compiler see something like:
7291 struct S' == struct S
7292 typedef struct S' MY_TYPE;
7293 struct S' object;
7295 And they can then deduce (from the node for type struct S') that
7296 the original object declaration was:
7298 MY_TYPE object;
7300 Being able to do this is important for proper support of protoize,
7301 and also for generating precise symbolic debugging information
7302 which takes full account of the programmer's (typedef) vocabulary.
7304 Obviously, we don't want to generate a duplicate ..._TYPE node if
7305 the TYPE_DECL node that we are now processing really represents a
7306 standard built-in type. */
7308 void
7309 set_underlying_type (tree x)
7311 if (x == error_mark_node)
7312 return;
7313 if (DECL_IS_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
7315 if (TYPE_NAME (TREE_TYPE (x)) == 0)
7316 TYPE_NAME (TREE_TYPE (x)) = x;
7318 else if (TREE_TYPE (x) != error_mark_node
7319 && DECL_ORIGINAL_TYPE (x) == NULL_TREE)
7321 tree tt = TREE_TYPE (x);
7322 DECL_ORIGINAL_TYPE (x) = tt;
7323 tt = build_variant_type_copy (tt);
7324 TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
7325 TYPE_NAME (tt) = x;
7327 /* Mark the type as used only when its type decl is decorated
7328 with attribute unused. */
7329 if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
7330 TREE_USED (tt) = 1;
7332 TREE_TYPE (x) = tt;
7336 /* Record the types used by the current global variable declaration
7337 being parsed, so that we can decide later to emit their debug info.
7338 Those types are in types_used_by_cur_var_decl, and we are going to
7339 store them in the types_used_by_vars_hash hash table.
7340 DECL is the declaration of the global variable that has been parsed. */
7342 void
7343 record_types_used_by_current_var_decl (tree decl)
7345 gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
7347 while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
7349 tree type = types_used_by_cur_var_decl->pop ();
7350 types_used_by_var_decl_insert (type, decl);
7354 /* The C and C++ parsers both use vectors to hold function arguments.
7355 For efficiency, we keep a cache of unused vectors. This is the
7356 cache. */
7358 typedef vec<tree, va_gc> *tree_gc_vec;
7359 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
7361 /* Return a new vector from the cache. If the cache is empty,
7362 allocate a new vector. These vectors are GC'ed, so it is OK if the
7363 pointer is not released.. */
7365 vec<tree, va_gc> *
7366 make_tree_vector (void)
7368 if (tree_vector_cache && !tree_vector_cache->is_empty ())
7369 return tree_vector_cache->pop ();
7370 else
7372 /* Passing 0 to vec::alloc returns NULL, and our callers require
7373 that we always return a non-NULL value. The vector code uses
7374 4 when growing a NULL vector, so we do too. */
7375 vec<tree, va_gc> *v;
7376 vec_alloc (v, 4);
7377 return v;
7381 /* Release a vector of trees back to the cache. */
7383 void
7384 release_tree_vector (vec<tree, va_gc> *vec)
7386 if (vec != NULL)
7388 vec->truncate (0);
7389 vec_safe_push (tree_vector_cache, vec);
7393 /* Get a new tree vector holding a single tree. */
7395 vec<tree, va_gc> *
7396 make_tree_vector_single (tree t)
7398 vec<tree, va_gc> *ret = make_tree_vector ();
7399 ret->quick_push (t);
7400 return ret;
7403 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain. */
7405 vec<tree, va_gc> *
7406 make_tree_vector_from_list (tree list)
7408 vec<tree, va_gc> *ret = make_tree_vector ();
7409 for (; list; list = TREE_CHAIN (list))
7410 vec_safe_push (ret, TREE_VALUE (list));
7411 return ret;
7414 /* Get a new tree vector of the values of a CONSTRUCTOR. */
7416 vec<tree, va_gc> *
7417 make_tree_vector_from_ctor (tree ctor)
7419 vec<tree,va_gc> *ret = make_tree_vector ();
7420 vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
7421 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
7422 ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
7423 return ret;
7426 /* Get a new tree vector which is a copy of an existing one. */
7428 vec<tree, va_gc> *
7429 make_tree_vector_copy (const vec<tree, va_gc> *orig)
7431 vec<tree, va_gc> *ret;
7432 unsigned int ix;
7433 tree t;
7435 ret = make_tree_vector ();
7436 vec_safe_reserve (ret, vec_safe_length (orig));
7437 FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
7438 ret->quick_push (t);
7439 return ret;
7442 /* Return true if KEYWORD starts a type specifier. */
7444 bool
7445 keyword_begins_type_specifier (enum rid keyword)
7447 switch (keyword)
7449 case RID_AUTO_TYPE:
7450 case RID_INT:
7451 case RID_CHAR:
7452 case RID_FLOAT:
7453 case RID_DOUBLE:
7454 case RID_VOID:
7455 case RID_UNSIGNED:
7456 case RID_LONG:
7457 case RID_SHORT:
7458 case RID_SIGNED:
7459 CASE_RID_FLOATN_NX:
7460 case RID_DFLOAT32:
7461 case RID_DFLOAT64:
7462 case RID_DFLOAT128:
7463 case RID_FRACT:
7464 case RID_ACCUM:
7465 case RID_BOOL:
7466 case RID_WCHAR:
7467 case RID_CHAR16:
7468 case RID_CHAR32:
7469 case RID_SAT:
7470 case RID_COMPLEX:
7471 case RID_TYPEOF:
7472 case RID_STRUCT:
7473 case RID_CLASS:
7474 case RID_UNION:
7475 case RID_ENUM:
7476 return true;
7477 default:
7478 if (keyword >= RID_FIRST_INT_N
7479 && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
7480 && int_n_enabled_p[keyword-RID_FIRST_INT_N])
7481 return true;
7482 return false;
7486 /* Return true if KEYWORD names a type qualifier. */
7488 bool
7489 keyword_is_type_qualifier (enum rid keyword)
7491 switch (keyword)
7493 case RID_CONST:
7494 case RID_VOLATILE:
7495 case RID_RESTRICT:
7496 case RID_ATOMIC:
7497 return true;
7498 default:
7499 return false;
7503 /* Return true if KEYWORD names a storage class specifier.
7505 RID_TYPEDEF is not included in this list despite `typedef' being
7506 listed in C99 6.7.1.1. 6.7.1.3 indicates that `typedef' is listed as
7507 such for syntactic convenience only. */
7509 bool
7510 keyword_is_storage_class_specifier (enum rid keyword)
7512 switch (keyword)
7514 case RID_STATIC:
7515 case RID_EXTERN:
7516 case RID_REGISTER:
7517 case RID_AUTO:
7518 case RID_MUTABLE:
7519 case RID_THREAD:
7520 return true;
7521 default:
7522 return false;
7526 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec]. */
7528 static bool
7529 keyword_is_function_specifier (enum rid keyword)
7531 switch (keyword)
7533 case RID_INLINE:
7534 case RID_NORETURN:
7535 case RID_VIRTUAL:
7536 case RID_EXPLICIT:
7537 return true;
7538 default:
7539 return false;
7543 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
7544 declaration-specifier (C99 6.7). */
7546 bool
7547 keyword_is_decl_specifier (enum rid keyword)
7549 if (keyword_is_storage_class_specifier (keyword)
7550 || keyword_is_type_qualifier (keyword)
7551 || keyword_is_function_specifier (keyword))
7552 return true;
7554 switch (keyword)
7556 case RID_TYPEDEF:
7557 case RID_FRIEND:
7558 case RID_CONSTEXPR:
7559 return true;
7560 default:
7561 return false;
7565 /* Initialize language-specific-bits of tree_contains_struct. */
7567 void
7568 c_common_init_ts (void)
7570 MARK_TS_TYPED (C_MAYBE_CONST_EXPR);
7571 MARK_TS_TYPED (EXCESS_PRECISION_EXPR);
7572 MARK_TS_TYPED (ARRAY_NOTATION_REF);
7575 /* Build a user-defined numeric literal out of an integer constant type VALUE
7576 with identifier SUFFIX. */
7578 tree
7579 build_userdef_literal (tree suffix_id, tree value,
7580 enum overflow_type overflow, tree num_string)
7582 tree literal = make_node (USERDEF_LITERAL);
7583 USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
7584 USERDEF_LITERAL_VALUE (literal) = value;
7585 USERDEF_LITERAL_OVERFLOW (literal) = overflow;
7586 USERDEF_LITERAL_NUM_STRING (literal) = num_string;
7587 return literal;
7590 /* For vector[index], convert the vector to an array of the underlying type.
7591 Return true if the resulting ARRAY_REF should not be an lvalue. */
7593 bool
7594 convert_vector_to_array_for_subscript (location_t loc,
7595 tree *vecp, tree index)
7597 bool ret = false;
7598 if (VECTOR_TYPE_P (TREE_TYPE (*vecp)))
7600 tree type = TREE_TYPE (*vecp);
7602 ret = !lvalue_p (*vecp);
7604 if (TREE_CODE (index) == INTEGER_CST)
7605 if (!tree_fits_uhwi_p (index)
7606 || tree_to_uhwi (index) >= TYPE_VECTOR_SUBPARTS (type))
7607 warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
7609 /* We are building an ARRAY_REF so mark the vector as addressable
7610 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
7611 for function parameters. */
7612 c_common_mark_addressable_vec (*vecp);
7614 *vecp = build1 (VIEW_CONVERT_EXPR,
7615 build_array_type_nelts (TREE_TYPE (type),
7616 TYPE_VECTOR_SUBPARTS (type)),
7617 *vecp);
7619 return ret;
7622 /* Determine which of the operands, if any, is a scalar that needs to be
7623 converted to a vector, for the range of operations. */
7624 enum stv_conv
7625 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
7626 bool complain)
7628 tree type0 = TREE_TYPE (op0);
7629 tree type1 = TREE_TYPE (op1);
7630 bool integer_only_op = false;
7631 enum stv_conv ret = stv_firstarg;
7633 gcc_assert (VECTOR_TYPE_P (type0) || VECTOR_TYPE_P (type1));
7634 switch (code)
7636 /* Most GENERIC binary expressions require homogeneous arguments.
7637 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
7638 argument that is a vector and a second one that is a scalar, so
7639 we never return stv_secondarg for them. */
7640 case RSHIFT_EXPR:
7641 case LSHIFT_EXPR:
7642 if (TREE_CODE (type0) == INTEGER_TYPE
7643 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
7645 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7646 NULL_TREE, false))
7648 if (complain)
7649 error_at (loc, "conversion of scalar %qT to vector %qT "
7650 "involves truncation", type0, type1);
7651 return stv_error;
7653 else
7654 return stv_firstarg;
7656 break;
7658 case BIT_IOR_EXPR:
7659 case BIT_XOR_EXPR:
7660 case BIT_AND_EXPR:
7661 integer_only_op = true;
7662 /* fall through */
7664 case VEC_COND_EXPR:
7666 case PLUS_EXPR:
7667 case MINUS_EXPR:
7668 case MULT_EXPR:
7669 case TRUNC_DIV_EXPR:
7670 case CEIL_DIV_EXPR:
7671 case FLOOR_DIV_EXPR:
7672 case ROUND_DIV_EXPR:
7673 case EXACT_DIV_EXPR:
7674 case TRUNC_MOD_EXPR:
7675 case FLOOR_MOD_EXPR:
7676 case RDIV_EXPR:
7677 case EQ_EXPR:
7678 case NE_EXPR:
7679 case LE_EXPR:
7680 case GE_EXPR:
7681 case LT_EXPR:
7682 case GT_EXPR:
7683 /* What about UNLT_EXPR? */
7684 if (VECTOR_TYPE_P (type0))
7686 ret = stv_secondarg;
7687 std::swap (type0, type1);
7688 std::swap (op0, op1);
7691 if (TREE_CODE (type0) == INTEGER_TYPE
7692 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
7694 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7695 NULL_TREE, false))
7697 if (complain)
7698 error_at (loc, "conversion of scalar %qT to vector %qT "
7699 "involves truncation", type0, type1);
7700 return stv_error;
7702 return ret;
7704 else if (!integer_only_op
7705 /* Allow integer --> real conversion if safe. */
7706 && (TREE_CODE (type0) == REAL_TYPE
7707 || TREE_CODE (type0) == INTEGER_TYPE)
7708 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
7710 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7711 NULL_TREE, false))
7713 if (complain)
7714 error_at (loc, "conversion of scalar %qT to vector %qT "
7715 "involves truncation", type0, type1);
7716 return stv_error;
7718 return ret;
7720 default:
7721 break;
7724 return stv_nothing;
7727 /* Return the alignment of std::max_align_t.
7729 [support.types.layout] The type max_align_t is a POD type whose alignment
7730 requirement is at least as great as that of every scalar type, and whose
7731 alignment requirement is supported in every context. */
7733 unsigned
7734 max_align_t_align ()
7736 unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
7737 TYPE_ALIGN (long_double_type_node));
7738 if (float128_type_node != NULL_TREE)
7739 max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
7740 return max_align;
7743 /* Return true iff ALIGN is an integral constant that is a fundamental
7744 alignment, as defined by [basic.align] in the c++-11
7745 specifications.
7747 That is:
7749 [A fundamental alignment is represented by an alignment less than or
7750 equal to the greatest alignment supported by the implementation
7751 in all contexts, which is equal to alignof(max_align_t)]. */
7753 bool
7754 cxx_fundamental_alignment_p (unsigned align)
7756 return (align <= max_align_t_align ());
7759 /* Return true if T is a pointer to a zero-sized aggregate. */
7761 bool
7762 pointer_to_zero_sized_aggr_p (tree t)
7764 if (!POINTER_TYPE_P (t))
7765 return false;
7766 t = TREE_TYPE (t);
7767 return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
7770 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
7771 with no library fallback or for an ADDR_EXPR whose operand is such type
7772 issues an error pointing to the location LOC.
7773 Returns true when the expression has been diagnosed and false
7774 otherwise. */
7776 bool
7777 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
7779 if (TREE_CODE (expr) == ADDR_EXPR)
7780 expr = TREE_OPERAND (expr, 0);
7782 if (TREE_TYPE (expr)
7783 && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
7784 && TREE_CODE (expr) == FUNCTION_DECL
7785 /* The intersection of DECL_BUILT_IN and DECL_IS_BUILTIN avoids
7786 false positives for user-declared built-ins such as abs or
7787 strlen, and for C++ operators new and delete.
7788 The c_decl_implicit() test avoids false positives for implicitly
7789 declared built-ins with library fallbacks (such as abs). */
7790 && DECL_BUILT_IN (expr)
7791 && DECL_IS_BUILTIN (expr)
7792 && !c_decl_implicit (expr)
7793 && !DECL_ASSEMBLER_NAME_SET_P (expr))
7795 if (loc == UNKNOWN_LOCATION)
7796 loc = EXPR_LOC_OR_LOC (expr, input_location);
7798 /* Reject arguments that are built-in functions with
7799 no library fallback. */
7800 error_at (loc, "built-in function %qE must be directly called", expr);
7802 return true;
7805 return false;
7808 /* Check if array size calculations overflow or if the array covers more
7809 than half of the address space. Return true if the size of the array
7810 is valid, false otherwise. TYPE is the type of the array and NAME is
7811 the name of the array, or NULL_TREE for unnamed arrays. */
7813 bool
7814 valid_array_size_p (location_t loc, tree type, tree name)
7816 if (type != error_mark_node
7817 && COMPLETE_TYPE_P (type)
7818 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
7819 && !valid_constant_size_p (TYPE_SIZE_UNIT (type)))
7821 if (name)
7822 error_at (loc, "size of array %qE is too large", name);
7823 else
7824 error_at (loc, "size of unnamed array is too large");
7825 return false;
7827 return true;
7830 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
7831 timestamp to replace embedded current dates to get reproducible
7832 results. Returns -1 if SOURCE_DATE_EPOCH is not defined. */
7834 time_t
7835 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
7837 char *source_date_epoch;
7838 int64_t epoch;
7839 char *endptr;
7841 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
7842 if (!source_date_epoch)
7843 return (time_t) -1;
7845 errno = 0;
7846 #if defined(INT64_T_IS_LONG)
7847 epoch = strtol (source_date_epoch, &endptr, 10);
7848 #else
7849 epoch = strtoll (source_date_epoch, &endptr, 10);
7850 #endif
7851 if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
7852 || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
7854 error_at (input_location, "environment variable SOURCE_DATE_EPOCH must "
7855 "expand to a non-negative integer less than or equal to %wd",
7856 MAX_SOURCE_DATE_EPOCH);
7857 return (time_t) -1;
7860 return (time_t) epoch;
7863 /* Callback for libcpp for offering spelling suggestions for misspelled
7864 directives. GOAL is an unrecognized string; CANDIDATES is a
7865 NULL-terminated array of candidate strings. Return the closest
7866 match to GOAL within CANDIDATES, or NULL if none are good
7867 suggestions. */
7869 const char *
7870 cb_get_suggestion (cpp_reader *, const char *goal,
7871 const char *const *candidates)
7873 best_match<const char *, const char *> bm (goal);
7874 while (*candidates)
7875 bm.consider (*candidates++);
7876 return bm.get_best_meaningful_candidate ();
7879 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
7880 modes X, Y. This isn't just >, as the FLT_EVAL_METHOD values added
7881 by C TS 18661-3 for interchange types that are computed in their
7882 native precision are larger than the C11 values for evaluating in the
7883 precision of float/double/long double. If either mode is
7884 FLT_EVAL_METHOD_UNPREDICTABLE, return that. */
7886 enum flt_eval_method
7887 excess_precision_mode_join (enum flt_eval_method x,
7888 enum flt_eval_method y)
7890 if (x == FLT_EVAL_METHOD_UNPREDICTABLE
7891 || y == FLT_EVAL_METHOD_UNPREDICTABLE)
7892 return FLT_EVAL_METHOD_UNPREDICTABLE;
7894 /* GCC only supports one interchange type right now, _Float16. If
7895 we're evaluating _Float16 in 16-bit precision, then flt_eval_method
7896 will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
7897 if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
7898 return y;
7899 if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
7900 return x;
7902 /* Other values for flt_eval_method are directly comparable, and we want
7903 the maximum. */
7904 return MAX (x, y);
7907 /* Return the value that should be set for FLT_EVAL_METHOD in the
7908 context of ISO/IEC TS 18861-3.
7910 This relates to the effective excess precision seen by the user,
7911 which is the join point of the precision the target requests for
7912 -fexcess-precision={standard,fast} and the implicit excess precision
7913 the target uses. */
7915 static enum flt_eval_method
7916 c_ts18661_flt_eval_method (void)
7918 enum flt_eval_method implicit
7919 = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
7921 enum excess_precision_type flag_type
7922 = (flag_excess_precision_cmdline == EXCESS_PRECISION_STANDARD
7923 ? EXCESS_PRECISION_TYPE_STANDARD
7924 : EXCESS_PRECISION_TYPE_FAST);
7926 enum flt_eval_method requested
7927 = targetm.c.excess_precision (flag_type);
7929 return excess_precision_mode_join (implicit, requested);
7932 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
7933 those that were permitted by C11. That is to say, eliminates
7934 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
7936 static enum flt_eval_method
7937 c_c11_flt_eval_method (void)
7939 return excess_precision_mode_join (c_ts18661_flt_eval_method (),
7940 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
7943 /* Return the value that should be set for FLT_EVAL_METHOD.
7944 MAYBE_C11_ONLY_P is TRUE if we should check
7945 FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
7946 values we can return to those from C99/C11, and FALSE otherwise.
7947 See the comments on c_ts18661_flt_eval_method for what value we choose
7948 to set here. */
7951 c_flt_eval_method (bool maybe_c11_only_p)
7953 if (maybe_c11_only_p
7954 && flag_permitted_flt_eval_methods
7955 == PERMITTED_FLT_EVAL_METHODS_C11)
7956 return c_c11_flt_eval_method ();
7957 else
7958 return c_ts18661_flt_eval_method ();
7961 /* An enum for get_missing_token_insertion_kind for describing the best
7962 place to insert a missing token, if there is one. */
7964 enum missing_token_insertion_kind
7966 MTIK_IMPOSSIBLE,
7967 MTIK_INSERT_BEFORE_NEXT,
7968 MTIK_INSERT_AFTER_PREV
7971 /* Given a missing token of TYPE, determine if it is reasonable to
7972 emit a fix-it hint suggesting the insertion of the token, and,
7973 if so, where the token should be inserted relative to other tokens.
7975 It only makes sense to do this for values of TYPE that are symbols.
7977 Some symbols should go before the next token, e.g. in:
7978 if flag)
7979 we want to insert the missing '(' immediately before "flag",
7980 giving:
7981 if (flag)
7982 rather than:
7983 if( flag)
7984 These use MTIK_INSERT_BEFORE_NEXT.
7986 Other symbols should go after the previous token, e.g. in:
7987 if (flag
7988 do_something ();
7989 we want to insert the missing ')' immediately after the "flag",
7990 giving:
7991 if (flag)
7992 do_something ();
7993 rather than:
7994 if (flag
7995 )do_something ();
7996 These use MTIK_INSERT_AFTER_PREV. */
7998 static enum missing_token_insertion_kind
7999 get_missing_token_insertion_kind (enum cpp_ttype type)
8001 switch (type)
8003 /* Insert missing "opening" brackets immediately
8004 before the next token. */
8005 case CPP_OPEN_SQUARE:
8006 case CPP_OPEN_PAREN:
8007 return MTIK_INSERT_BEFORE_NEXT;
8009 /* Insert other missing symbols immediately after
8010 the previous token. */
8011 case CPP_CLOSE_PAREN:
8012 case CPP_CLOSE_SQUARE:
8013 case CPP_SEMICOLON:
8014 case CPP_COMMA:
8015 case CPP_COLON:
8016 return MTIK_INSERT_AFTER_PREV;
8018 /* Other kinds of token don't get fix-it hints. */
8019 default:
8020 return MTIK_IMPOSSIBLE;
8024 /* Given RICHLOC, a location for a diagnostic describing a missing token
8025 of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
8026 insertion of the token.
8028 The location of the attempted fix-it hint depends on TOKEN_TYPE:
8029 it will either be:
8030 (a) immediately after PREV_TOKEN_LOC, or
8032 (b) immediately before the primary location within RICHLOC (taken to
8033 be that of the token following where the token was expected).
8035 If we manage to add a fix-it hint, then the location of the
8036 fix-it hint is likely to be more useful as the primary location
8037 of the diagnostic than that of the following token, so we swap
8038 these locations.
8040 For example, given this bogus code:
8041 123456789012345678901234567890
8042 1 | int missing_semicolon (void)
8043 2 | {
8044 3 | return 42
8045 4 | }
8047 we will emit:
8049 "expected ';' before '}'"
8051 RICHLOC's primary location is at the closing brace, so before "swapping"
8052 we would emit the error at line 4 column 1:
8054 123456789012345678901234567890
8055 3 | return 42 |< fix-it hint emitted for this line
8056 | ; |
8057 4 | } |< "expected ';' before '}'" emitted at this line
8058 | ^ |
8060 It's more useful for the location of the diagnostic to be at the
8061 fix-it hint, so we swap the locations, so the primary location
8062 is at the fix-it hint, with the old primary location inserted
8063 as a secondary location, giving this, with the error at line 3
8064 column 12:
8066 123456789012345678901234567890
8067 3 | return 42 |< "expected ';' before '}'" emitted at this line,
8068 | ^ | with fix-it hint
8069 4 | ; |
8070 | } |< secondary range emitted here
8071 | ~ |. */
8073 void
8074 maybe_suggest_missing_token_insertion (rich_location *richloc,
8075 enum cpp_ttype token_type,
8076 location_t prev_token_loc)
8078 gcc_assert (richloc);
8080 enum missing_token_insertion_kind mtik
8081 = get_missing_token_insertion_kind (token_type);
8083 switch (mtik)
8085 default:
8086 gcc_unreachable ();
8087 break;
8089 case MTIK_IMPOSSIBLE:
8090 return;
8092 case MTIK_INSERT_BEFORE_NEXT:
8093 /* Attempt to add the fix-it hint before the primary location
8094 of RICHLOC. */
8095 richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
8096 break;
8098 case MTIK_INSERT_AFTER_PREV:
8099 /* Attempt to add the fix-it hint after PREV_TOKEN_LOC. */
8100 richloc->add_fixit_insert_after (prev_token_loc,
8101 cpp_type2name (token_type, 0));
8102 break;
8105 /* If we were successful, use the fix-it hint's location as the
8106 primary location within RICHLOC, adding the old primary location
8107 back as a secondary location. */
8108 if (!richloc->seen_impossible_fixit_p ())
8110 fixit_hint *hint = richloc->get_last_fixit_hint ();
8111 location_t hint_loc = hint->get_start_loc ();
8112 location_t old_loc = richloc->get_loc ();
8114 richloc->set_range (line_table, 0, hint_loc, true);
8115 richloc->add_range (old_loc, false);
8119 #if CHECKING_P
8121 namespace selftest {
8123 /* Run all of the tests within c-family. */
8125 void
8126 c_family_tests (void)
8128 c_format_c_tests ();
8131 } // namespace selftest
8133 #endif /* #if CHECKING_P */
8135 /* Attempt to locate a suitable location within FILE for a
8136 #include directive to be inserted before. FILE should
8137 be a string from libcpp (pointer equality is used).
8138 LOC is the location of the relevant diagnostic.
8140 Attempt to return the location within FILE immediately
8141 after the last #include within that file, or the start of
8142 that file if it has no #include directives.
8144 Return UNKNOWN_LOCATION if no suitable location is found,
8145 or if an error occurs. */
8147 static location_t
8148 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
8150 /* Locate the last ordinary map within FILE that ended with a #include. */
8151 const line_map_ordinary *last_include_ord_map = NULL;
8153 /* ...and the next ordinary map within FILE after that one. */
8154 const line_map_ordinary *last_ord_map_after_include = NULL;
8156 /* ...and the first ordinary map within FILE. */
8157 const line_map_ordinary *first_ord_map_in_file = NULL;
8159 /* Get ordinary map containing LOC (or its expansion). */
8160 const line_map_ordinary *ord_map_for_loc = NULL;
8161 loc = linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
8162 &ord_map_for_loc);
8163 gcc_assert (ord_map_for_loc);
8165 for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
8167 const line_map_ordinary *ord_map
8168 = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
8170 const line_map_ordinary *from = INCLUDED_FROM (line_table, ord_map);
8171 if (from)
8172 if (from->to_file == file)
8174 last_include_ord_map = from;
8175 last_ord_map_after_include = NULL;
8178 if (ord_map->to_file == file)
8180 if (!first_ord_map_in_file)
8181 first_ord_map_in_file = ord_map;
8182 if (last_include_ord_map && !last_ord_map_after_include)
8183 last_ord_map_after_include = ord_map;
8186 /* Stop searching when reaching the ord_map containing LOC,
8187 as it makes no sense to provide fix-it hints that appear
8188 after the diagnostic in question. */
8189 if (ord_map == ord_map_for_loc)
8190 break;
8193 /* Determine where to insert the #include. */
8194 const line_map_ordinary *ord_map_for_insertion;
8196 /* We want the next ordmap in the file after the last one that's a
8197 #include, but failing that, the start of the file. */
8198 if (last_ord_map_after_include)
8199 ord_map_for_insertion = last_ord_map_after_include;
8200 else
8201 ord_map_for_insertion = first_ord_map_in_file;
8203 if (!ord_map_for_insertion)
8204 return UNKNOWN_LOCATION;
8206 /* The "start_location" is column 0, meaning "the whole line".
8207 rich_location and edit_context can't cope with this, so use
8208 column 1 instead. */
8209 location_t col_0 = ord_map_for_insertion->start_location;
8210 return linemap_position_for_loc_and_offset (line_table, col_0, 1);
8213 /* A map from filenames to sets of headers added to them, for
8214 ensuring idempotency within maybe_add_include_fixit. */
8216 /* The values within the map. We need string comparison as there's
8217 no guarantee that two different diagnostics that are recommending
8218 adding e.g. "<stdio.h>" are using the same buffer. */
8220 typedef hash_set <const char *, nofree_string_hash> per_file_includes_t;
8222 /* The map itself. We don't need string comparison for the filename keys,
8223 as they come from libcpp. */
8225 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
8226 static added_includes_t *added_includes;
8228 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
8229 in a suitable location within the file of RICHLOC's primary
8230 location.
8232 This function is idempotent: a header will be added at most once to
8233 any given file. */
8235 void
8236 maybe_add_include_fixit (rich_location *richloc, const char *header)
8238 location_t loc = richloc->get_loc ();
8239 const char *file = LOCATION_FILE (loc);
8240 if (!file)
8241 return;
8243 /* Idempotency: don't add the same header more than once to a given file. */
8244 if (!added_includes)
8245 added_includes = new added_includes_t ();
8246 per_file_includes_t *&set = added_includes->get_or_insert (file);
8247 if (set)
8248 if (set->contains (header))
8249 /* ...then we've already added HEADER to that file. */
8250 return;
8251 if (!set)
8252 set = new per_file_includes_t ();
8253 set->add (header);
8255 /* Attempt to locate a suitable place for the new directive. */
8256 location_t include_insert_loc
8257 = try_to_locate_new_include_insertion_point (file, loc);
8258 if (include_insert_loc == UNKNOWN_LOCATION)
8259 return;
8261 char *text = xasprintf ("#include %s\n", header);
8262 richloc->add_fixit_insert_before (include_insert_loc, text);
8263 free (text);
8266 #include "gt-c-family-c-common.h"