Fix type of malloc parameter in trans-expr.cc
[official-gcc.git] / gcc / c-family / c-common.cc
blobb7586312537bcd539d99337e0ddc8944b5787ad7
1 /* Subroutines shared by all languages that are variants of C.
2 Copyright (C) 1992-2024 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 #define INCLUDE_MEMORY
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "target.h"
27 #include "function.h"
28 #include "tree.h"
29 #include "memmodel.h"
30 #include "c-common.h"
31 #include "gimple-expr.h"
32 #include "tm_p.h"
33 #include "stringpool.h"
34 #include "cgraph.h"
35 #include "diagnostic.h"
36 #include "intl.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "attribs.h"
40 #include "varasm.h"
41 #include "trans-mem.h"
42 #include "c-objc.h"
43 #include "common/common-target.h"
44 #include "langhooks.h"
45 #include "tree-inline.h"
46 #include "toplev.h"
47 #include "tree-iterator.h"
48 #include "opts.h"
49 #include "gimplify.h"
50 #include "substring-locations.h"
51 #include "spellcheck.h"
52 #include "c-spellcheck.h"
53 #include "selftest.h"
54 #include "debug.h"
55 #include "tree-vector-builder.h"
56 #include "vec-perm-indices.h"
57 #include "tree-pretty-print-markup.h"
59 cpp_reader *parse_in; /* Declared in c-pragma.h. */
61 /* Mode used to build pointers (VOIDmode means ptr_mode). */
63 machine_mode c_default_pointer_mode = VOIDmode;
65 /* The following symbols are subsumed in the c_global_trees array, and
66 listed here individually for documentation purposes.
68 INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
70 tree short_integer_type_node;
71 tree long_integer_type_node;
72 tree long_long_integer_type_node;
74 tree short_unsigned_type_node;
75 tree long_unsigned_type_node;
76 tree long_long_unsigned_type_node;
78 tree truthvalue_type_node;
79 tree truthvalue_false_node;
80 tree truthvalue_true_node;
82 tree ptrdiff_type_node;
84 tree unsigned_char_type_node;
85 tree signed_char_type_node;
86 tree wchar_type_node;
88 tree char8_type_node;
89 tree char16_type_node;
90 tree char32_type_node;
92 tree float_type_node;
93 tree double_type_node;
94 tree long_double_type_node;
96 tree complex_integer_type_node;
97 tree complex_float_type_node;
98 tree complex_double_type_node;
99 tree complex_long_double_type_node;
101 tree dfloat32_type_node;
102 tree dfloat64_type_node;
103 tree dfloat128_type_node;
104 tree dfloat64x_type_node;
106 tree intQI_type_node;
107 tree intHI_type_node;
108 tree intSI_type_node;
109 tree intDI_type_node;
110 tree intTI_type_node;
112 tree unsigned_intQI_type_node;
113 tree unsigned_intHI_type_node;
114 tree unsigned_intSI_type_node;
115 tree unsigned_intDI_type_node;
116 tree unsigned_intTI_type_node;
118 tree widest_integer_literal_type_node;
119 tree widest_unsigned_literal_type_node;
121 Nodes for types `void *' and `const void *'.
123 tree ptr_type_node, const_ptr_type_node;
125 Nodes for types `char *' and `const char *'.
127 tree string_type_node, const_string_type_node;
129 Type `char[SOMENUMBER]'.
130 Used when an array of char is needed and the size is irrelevant.
132 tree char_array_type_node;
134 Type `wchar_t[SOMENUMBER]' or something like it.
135 Used when a wide string literal is created.
137 tree wchar_array_type_node;
139 Type `char8_t[SOMENUMBER]' or something like it.
140 Used when a UTF-8 string literal is created.
142 tree char8_array_type_node;
144 Type `char16_t[SOMENUMBER]' or something like it.
145 Used when a UTF-16 string literal is created.
147 tree char16_array_type_node;
149 Type `char32_t[SOMENUMBER]' or something like it.
150 Used when a UTF-32 string literal is created.
152 tree char32_array_type_node;
154 Type `int ()' -- used for implicit declaration of functions.
156 tree default_function_type;
158 A VOID_TYPE node, packaged in a TREE_LIST.
160 tree void_list_node;
162 The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
163 and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
164 VAR_DECLS, but C++ does.)
166 tree function_name_decl_node;
167 tree pretty_function_name_decl_node;
168 tree c99_function_name_decl_node;
170 Stack of nested function name VAR_DECLs.
172 tree saved_function_name_decls;
176 tree c_global_trees[CTI_MAX];
178 /* Switches common to the C front ends. */
180 /* Nonzero means don't output line number information. */
182 char flag_no_line_commands;
184 /* Nonzero causes -E output not to be done, but directives such as
185 #define that have side effects are still obeyed. */
187 char flag_no_output;
189 /* Nonzero means dump macros in some fashion. */
191 char flag_dump_macros;
193 /* Nonzero means pass #include lines through to the output. */
195 char flag_dump_includes;
197 /* Nonzero means process PCH files while preprocessing. */
199 bool flag_pch_preprocess;
201 /* The file name to which we should write a precompiled header, or
202 NULL if no header will be written in this compile. */
204 const char *pch_file;
206 /* Nonzero if an ISO standard was selected. It rejects macros in the
207 user's namespace. */
208 int flag_iso;
210 /* C/ObjC language option variables. */
213 /* Nonzero means allow type mismatches in conditional expressions;
214 just make their values `void'. */
216 int flag_cond_mismatch;
218 /* Nonzero means enable C89 Amendment 1 features. */
220 int flag_isoc94;
222 /* Nonzero means use the ISO C99 (or later) dialect of C. */
224 int flag_isoc99;
226 /* Nonzero means use the ISO C11 (or later) dialect of C. */
228 int flag_isoc11;
230 /* Nonzero means use the ISO C23 (or later) dialect of C. */
232 int flag_isoc23;
234 /* Nonzero means use the ISO C2Y (or later) dialect of C. */
236 int flag_isoc2y;
238 /* Nonzero means that we have builtin functions, and main is an int. */
240 int flag_hosted = 1;
243 /* ObjC language option variables. */
246 /* Tells the compiler that this is a special run. Do not perform any
247 compiling, instead we are to test some platform dependent features
248 and output a C header file with appropriate definitions. */
250 int print_struct_values;
252 /* Tells the compiler what is the constant string class for ObjC. */
254 const char *constant_string_class_name;
257 /* C++ language option variables. */
259 /* The reference version of the ABI for -Wabi. */
261 int warn_abi_version = -1;
263 /* The C++ dialect being used. Default set in c_common_post_options. */
265 enum cxx_dialect cxx_dialect = cxx_unset;
267 /* Maximum template instantiation depth. This limit exists to limit the
268 time it takes to notice excessively recursive template instantiations.
270 The default is lower than the 1024 recommended by the C++0x standard
271 because G++ runs out of stack before 1024 with highly recursive template
272 argument deduction substitution (g++.dg/cpp0x/enum11.C). */
274 int max_tinst_depth = 900;
276 /* The elements of `ridpointers' are identifier nodes for the reserved
277 type names and storage classes. It is indexed by a RID_... value. */
278 tree *ridpointers;
280 tree (*make_fname_decl) (location_t, tree, int);
282 /* Nonzero means don't warn about problems that occur when the code is
283 executed. */
284 int c_inhibit_evaluation_warnings;
286 /* Whether we are building a boolean conversion inside
287 convert_for_assignment, or some other late binary operation. If
288 build_binary_op is called for C (from code shared by C and C++) in
289 this case, then the operands have already been folded and the
290 result will not be folded again, so C_MAYBE_CONST_EXPR should not
291 be generated. */
292 bool in_late_binary_op;
294 /* Depending on which phase of processing we are in, we may need
295 to prefer input_location to libcpp's locations. (Specifically,
296 after the C++ lexer is done lexing tokens, but prior to calling
297 cpp_finish (), we need to do so. */
298 bool override_libcpp_locations;
300 /* Information about how a function name is generated. */
301 struct fname_var_t
303 tree *const decl; /* pointer to the VAR_DECL. */
304 const unsigned rid; /* RID number for the identifier. */
305 const int pretty; /* How pretty is it? */
308 /* The three ways of getting then name of the current function. */
310 const struct fname_var_t fname_vars[] =
312 /* C99 compliant __func__, must be first. */
313 {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
314 /* GCC __FUNCTION__ compliant. */
315 {&function_name_decl_node, RID_FUNCTION_NAME, 0},
316 /* GCC __PRETTY_FUNCTION__ compliant. */
317 {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
318 {NULL, 0, 0},
321 /* Flags to restrict availability of generic features that
322 are known to __has_{feature,extension}. */
324 enum
326 HF_FLAG_NONE = 0,
327 HF_FLAG_EXT = 1, /* Available only as an extension. */
328 HF_FLAG_SANITIZE = 2, /* Availability depends on sanitizer flags. */
331 /* Info for generic features which can be queried through
332 __has_{feature,extension}. */
334 struct hf_feature_info
336 const char *ident;
337 unsigned flags;
338 unsigned mask;
341 /* Table of generic features which can be queried through
342 __has_{feature,extension}. */
344 static constexpr hf_feature_info has_feature_table[] =
346 { "address_sanitizer", HF_FLAG_SANITIZE, SANITIZE_ADDRESS },
347 { "thread_sanitizer", HF_FLAG_SANITIZE, SANITIZE_THREAD },
348 { "leak_sanitizer", HF_FLAG_SANITIZE, SANITIZE_LEAK },
349 { "hwaddress_sanitizer", HF_FLAG_SANITIZE, SANITIZE_HWADDRESS },
350 { "undefined_behavior_sanitizer", HF_FLAG_SANITIZE, SANITIZE_UNDEFINED },
351 { "attribute_deprecated_with_message", HF_FLAG_NONE, 0 },
352 { "attribute_unavailable_with_message", HF_FLAG_NONE, 0 },
353 { "enumerator_attributes", HF_FLAG_NONE, 0 },
354 { "tls", HF_FLAG_NONE, 0 },
355 { "gnu_asm_goto_with_outputs", HF_FLAG_EXT, 0 },
356 { "gnu_asm_goto_with_outputs_full", HF_FLAG_EXT, 0 }
359 /* Global visibility options. */
360 struct visibility_flags visibility_options;
362 static tree check_case_value (location_t, tree);
365 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
366 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
368 /* Reserved words. The third field is a mask: keywords are disabled
369 if they match the mask.
371 Masks for languages:
372 C --std=c89: D_C99 | D_C23 | D_CXXONLY | D_OBJC | D_CXX_OBJC
373 C --std=c99: D_C23 | D_CXXONLY | D_OBJC
374 C --std=c17: D_C23 | D_CXXONLY | D_OBJC
375 C --std=c23: D_CXXONLY | D_OBJC
376 ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
377 C++ --std=c++98: D_CONLY | D_CXX11 | D_CXX20 | D_OBJC
378 C++ --std=c++11: D_CONLY | D_CXX20 | D_OBJC
379 C++ --std=c++20: D_CONLY | D_OBJC
380 ObjC++ is like C++ except that D_OBJC is not set
382 If -fno-asm is used, D_ASM is added to the mask. If
383 -fno-gnu-keywords is used, D_EXT is added. If -fno-asm and C in
384 C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
385 In C with -Wc++-compat, we warn if D_CXXWARN is set.
387 Note the complication of the D_CXX_OBJC keywords. These are
388 reserved words such as 'class'. In C++, 'class' is a reserved
389 word. In Objective-C++ it is too. In Objective-C, it is a
390 reserved word too, but only if it follows an '@' sign.
392 const struct c_common_resword c_common_reswords[] =
394 { "_Alignas", RID_ALIGNAS, D_CONLY },
395 { "_Alignof", RID_ALIGNOF, D_CONLY },
396 { "_Atomic", RID_ATOMIC, D_CONLY },
397 { "_BitInt", RID_BITINT, D_CONLY },
398 { "_Bool", RID_BOOL, D_CONLY },
399 { "_Complex", RID_COMPLEX, 0 },
400 { "_Imaginary", RID_IMAGINARY, D_CONLY },
401 { "_Float16", RID_FLOAT16, 0 },
402 { "_Float32", RID_FLOAT32, 0 },
403 { "_Float64", RID_FLOAT64, 0 },
404 { "_Float128", RID_FLOAT128, 0 },
405 { "_Float32x", RID_FLOAT32X, 0 },
406 { "_Float64x", RID_FLOAT64X, 0 },
407 { "_Float128x", RID_FLOAT128X, 0 },
408 { "_Decimal32", RID_DFLOAT32, D_CONLY },
409 { "_Decimal64", RID_DFLOAT64, D_CONLY },
410 { "_Decimal128", RID_DFLOAT128, D_CONLY },
411 { "_Decimal64x", RID_DFLOAT64X, D_CONLY },
412 { "_Fract", RID_FRACT, D_CONLY | D_EXT },
413 { "_Accum", RID_ACCUM, D_CONLY | D_EXT },
414 { "_Sat", RID_SAT, D_CONLY | D_EXT },
415 { "_Static_assert", RID_STATIC_ASSERT, D_CONLY },
416 { "_Noreturn", RID_NORETURN, D_CONLY },
417 { "_Generic", RID_GENERIC, D_CONLY },
418 { "_Thread_local", RID_THREAD, D_CONLY },
419 { "__FUNCTION__", RID_FUNCTION_NAME, 0 },
420 { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
421 { "__alignof", RID_ALIGNOF, 0 },
422 { "__alignof__", RID_ALIGNOF, 0 },
423 { "__asm", RID_ASM, 0 },
424 { "__asm__", RID_ASM, 0 },
425 { "__attribute", RID_ATTRIBUTE, 0 },
426 { "__attribute__", RID_ATTRIBUTE, 0 },
427 { "__auto_type", RID_AUTO_TYPE, D_CONLY },
428 { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
429 { "__builtin_assoc_barrier", RID_BUILTIN_ASSOC_BARRIER, 0 },
430 { "__builtin_bit_cast", RID_BUILTIN_BIT_CAST, D_CXXONLY },
431 { "__builtin_call_with_static_chain",
432 RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
433 { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
434 { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
435 { "__builtin_convertvector", RID_BUILTIN_CONVERTVECTOR, 0 },
436 { "__builtin_counted_by_ref", RID_BUILTIN_COUNTED_BY_REF, D_CONLY },
437 { "__builtin_has_attribute", RID_BUILTIN_HAS_ATTRIBUTE, 0 },
438 { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
439 { "__builtin_operator_new", RID_BUILTIN_OPERATOR_NEW, D_CXXONLY },
440 { "__builtin_operator_delete", RID_BUILTIN_OPERATOR_DELETE, D_CXXONLY },
441 { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
442 { "__builtin_shufflevector", RID_BUILTIN_SHUFFLEVECTOR, 0 },
443 { "__builtin_stdc_bit_ceil", RID_BUILTIN_STDC, D_CONLY },
444 { "__builtin_stdc_bit_floor", RID_BUILTIN_STDC, D_CONLY },
445 { "__builtin_stdc_bit_width", RID_BUILTIN_STDC, D_CONLY },
446 { "__builtin_stdc_count_ones", RID_BUILTIN_STDC, D_CONLY },
447 { "__builtin_stdc_count_zeros", RID_BUILTIN_STDC, D_CONLY },
448 { "__builtin_stdc_first_leading_one", RID_BUILTIN_STDC, D_CONLY },
449 { "__builtin_stdc_first_leading_zero", RID_BUILTIN_STDC, D_CONLY },
450 { "__builtin_stdc_first_trailing_one", RID_BUILTIN_STDC, D_CONLY },
451 { "__builtin_stdc_first_trailing_zero", RID_BUILTIN_STDC, D_CONLY },
452 { "__builtin_stdc_has_single_bit", RID_BUILTIN_STDC, D_CONLY },
453 { "__builtin_stdc_leading_ones", RID_BUILTIN_STDC, D_CONLY },
454 { "__builtin_stdc_leading_zeros", RID_BUILTIN_STDC, D_CONLY },
455 { "__builtin_stdc_rotate_left", RID_BUILTIN_STDC, D_CONLY },
456 { "__builtin_stdc_rotate_right", RID_BUILTIN_STDC, D_CONLY },
457 { "__builtin_stdc_trailing_ones", RID_BUILTIN_STDC, D_CONLY },
458 { "__builtin_stdc_trailing_zeros", RID_BUILTIN_STDC, D_CONLY },
459 { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
460 { "__builtin_offsetof", RID_OFFSETOF, 0 },
461 { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
462 { "__builtin_va_arg", RID_VA_ARG, 0 },
463 { "__complex", RID_COMPLEX, 0 },
464 { "__complex__", RID_COMPLEX, 0 },
465 { "__const", RID_CONST, 0 },
466 { "__const__", RID_CONST, 0 },
467 { "__constinit", RID_CONSTINIT, D_CXXONLY },
468 { "__decltype", RID_DECLTYPE, D_CXXONLY },
469 { "__extension__", RID_EXTENSION, 0 },
470 { "__func__", RID_C99_FUNCTION_NAME, 0 },
471 { "__imag", RID_IMAGPART, 0 },
472 { "__imag__", RID_IMAGPART, 0 },
473 { "__inline", RID_INLINE, 0 },
474 { "__inline__", RID_INLINE, 0 },
475 { "__label__", RID_LABEL, 0 },
476 { "__null", RID_NULL, 0 },
477 { "__real", RID_REALPART, 0 },
478 { "__real__", RID_REALPART, 0 },
479 { "__restrict", RID_RESTRICT, 0 },
480 { "__restrict__", RID_RESTRICT, 0 },
481 { "__signed", RID_SIGNED, 0 },
482 { "__signed__", RID_SIGNED, 0 },
483 { "__thread", RID_THREAD, 0 },
484 { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
485 { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
486 { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
487 { "__typeof", RID_TYPEOF, 0 },
488 { "__typeof__", RID_TYPEOF, 0 },
489 { "__typeof_unqual", RID_TYPEOF_UNQUAL, D_CONLY },
490 { "__typeof_unqual__", RID_TYPEOF_UNQUAL, D_CONLY },
491 { "__volatile", RID_VOLATILE, 0 },
492 { "__volatile__", RID_VOLATILE, 0 },
493 { "__GIMPLE", RID_GIMPLE, D_CONLY },
494 { "__PHI", RID_PHI, D_CONLY },
495 { "__RTL", RID_RTL, D_CONLY },
496 { "alignas", RID_ALIGNAS, D_C23 | D_CXX11 | D_CXXWARN },
497 { "alignof", RID_ALIGNOF, D_C23 | D_CXX11 | D_CXXWARN },
498 { "asm", RID_ASM, D_ASM },
499 { "auto", RID_AUTO, 0 },
500 { "bool", RID_BOOL, D_C23 | D_CXXWARN },
501 { "break", RID_BREAK, 0 },
502 { "case", RID_CASE, 0 },
503 { "catch", RID_CATCH, D_CXX_OBJC | D_CXXWARN },
504 { "char", RID_CHAR, 0 },
505 { "char8_t", RID_CHAR8, D_CXX_CHAR8_T_FLAGS | D_CXXWARN },
506 { "char16_t", RID_CHAR16, D_CXXONLY | D_CXX11 | D_CXXWARN },
507 { "char32_t", RID_CHAR32, D_CXXONLY | D_CXX11 | D_CXXWARN },
508 { "class", RID_CLASS, D_CXX_OBJC | D_CXXWARN },
509 { "const", RID_CONST, 0 },
510 { "consteval", RID_CONSTEVAL, D_CXXONLY | D_CXX20 | D_CXXWARN },
511 { "constexpr", RID_CONSTEXPR, D_C23 | D_CXX11 | D_CXXWARN },
512 { "constinit", RID_CONSTINIT, D_CXXONLY | D_CXX20 | D_CXXWARN },
513 { "const_cast", RID_CONSTCAST, D_CXXONLY | D_CXXWARN },
514 { "continue", RID_CONTINUE, 0 },
515 { "decltype", RID_DECLTYPE, D_CXXONLY | D_CXX11 | D_CXXWARN },
516 { "default", RID_DEFAULT, 0 },
517 { "delete", RID_DELETE, D_CXXONLY | D_CXXWARN },
518 { "do", RID_DO, 0 },
519 { "double", RID_DOUBLE, 0 },
520 { "dynamic_cast", RID_DYNCAST, D_CXXONLY | D_CXXWARN },
521 { "else", RID_ELSE, 0 },
522 { "enum", RID_ENUM, 0 },
523 { "explicit", RID_EXPLICIT, D_CXXONLY | D_CXXWARN },
524 { "export", RID_EXPORT, D_CXXONLY | D_CXXWARN },
525 { "extern", RID_EXTERN, 0 },
526 { "false", RID_FALSE, D_C23 | D_CXXWARN },
527 { "float", RID_FLOAT, 0 },
528 { "for", RID_FOR, 0 },
529 { "friend", RID_FRIEND, D_CXXONLY | D_CXXWARN },
530 { "goto", RID_GOTO, 0 },
531 { "if", RID_IF, 0 },
532 { "inline", RID_INLINE, D_EXT89 },
533 { "int", RID_INT, 0 },
534 { "long", RID_LONG, 0 },
535 { "mutable", RID_MUTABLE, D_CXXONLY | D_CXXWARN },
536 { "namespace", RID_NAMESPACE, D_CXXONLY | D_CXXWARN },
537 { "new", RID_NEW, D_CXXONLY | D_CXXWARN },
538 { "noexcept", RID_NOEXCEPT, D_CXXONLY | D_CXX11 | D_CXXWARN },
539 { "nullptr", RID_NULLPTR, D_C23 | D_CXX11 | D_CXXWARN },
540 { "operator", RID_OPERATOR, D_CXXONLY | D_CXXWARN },
541 { "private", RID_PRIVATE, D_CXX_OBJC | D_CXXWARN },
542 { "protected", RID_PROTECTED, D_CXX_OBJC | D_CXXWARN },
543 { "public", RID_PUBLIC, D_CXX_OBJC | D_CXXWARN },
544 { "register", RID_REGISTER, 0 },
545 { "reinterpret_cast", RID_REINTCAST, D_CXXONLY | D_CXXWARN },
546 { "restrict", RID_RESTRICT, D_CONLY | D_C99 },
547 { "return", RID_RETURN, 0 },
548 { "short", RID_SHORT, 0 },
549 { "signed", RID_SIGNED, 0 },
550 { "sizeof", RID_SIZEOF, 0 },
551 { "static", RID_STATIC, 0 },
552 { "static_assert", RID_STATIC_ASSERT, D_C23 | D_CXX11 | D_CXXWARN },
553 { "static_cast", RID_STATCAST, D_CXXONLY | D_CXXWARN },
554 { "struct", RID_STRUCT, 0 },
555 { "switch", RID_SWITCH, 0 },
556 { "template", RID_TEMPLATE, D_CXXONLY | D_CXXWARN },
557 { "this", RID_THIS, D_CXXONLY | D_CXXWARN },
558 { "thread_local", RID_THREAD, D_C23 | D_CXX11 | D_CXXWARN },
559 { "throw", RID_THROW, D_CXX_OBJC | D_CXXWARN },
560 { "true", RID_TRUE, D_C23 | D_CXXWARN },
561 { "try", RID_TRY, D_CXX_OBJC | D_CXXWARN },
562 { "typedef", RID_TYPEDEF, 0 },
563 { "typename", RID_TYPENAME, D_CXXONLY | D_CXXWARN },
564 { "typeid", RID_TYPEID, D_CXXONLY | D_CXXWARN },
565 { "typeof", RID_TYPEOF, D_EXT11 },
566 { "typeof_unqual", RID_TYPEOF_UNQUAL, D_CONLY | D_C23 },
567 { "union", RID_UNION, 0 },
568 { "unsigned", RID_UNSIGNED, 0 },
569 { "using", RID_USING, D_CXXONLY | D_CXXWARN },
570 { "virtual", RID_VIRTUAL, D_CXXONLY | D_CXXWARN },
571 { "void", RID_VOID, 0 },
572 { "volatile", RID_VOLATILE, 0 },
573 { "wchar_t", RID_WCHAR, D_CXXONLY },
574 { "while", RID_WHILE, 0 },
576 /* C++ transactional memory. */
577 { "synchronized", RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
578 { "atomic_noexcept", RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
579 { "atomic_cancel", RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
580 { "atomic_commit", RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
582 /* Concepts-related keywords */
583 { "concept", RID_CONCEPT, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
584 { "requires", RID_REQUIRES, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
586 /* Modules-related keywords, these are internal unspellable tokens,
587 created by the preprocessor. */
588 { "module ", RID__MODULE, D_CXX_MODULES_FLAGS | D_CXXWARN },
589 { "import ", RID__IMPORT, D_CXX_MODULES_FLAGS | D_CXXWARN },
590 { "export ", RID__EXPORT, D_CXX_MODULES_FLAGS | D_CXXWARN },
592 /* Coroutines-related keywords */
593 { "co_await", RID_CO_AWAIT, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
594 { "co_yield", RID_CO_YIELD, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
595 { "co_return", RID_CO_RETURN, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
597 /* These Objective-C keywords are recognized only immediately after
598 an '@'. */
599 { "compatibility_alias", RID_AT_ALIAS, D_OBJC },
600 { "defs", RID_AT_DEFS, D_OBJC },
601 { "encode", RID_AT_ENCODE, D_OBJC },
602 { "end", RID_AT_END, D_OBJC },
603 { "implementation", RID_AT_IMPLEMENTATION, D_OBJC },
604 { "interface", RID_AT_INTERFACE, D_OBJC },
605 { "protocol", RID_AT_PROTOCOL, D_OBJC },
606 { "selector", RID_AT_SELECTOR, D_OBJC },
607 { "finally", RID_AT_FINALLY, D_OBJC },
608 { "optional", RID_AT_OPTIONAL, D_OBJC },
609 { "required", RID_AT_REQUIRED, D_OBJC },
610 { "property", RID_AT_PROPERTY, D_OBJC },
611 { "package", RID_AT_PACKAGE, D_OBJC },
612 { "synthesize", RID_AT_SYNTHESIZE, D_OBJC },
613 { "dynamic", RID_AT_DYNAMIC, D_OBJC },
614 /* These are recognized only in protocol-qualifier context
615 (see above) */
616 { "bycopy", RID_BYCOPY, D_OBJC },
617 { "byref", RID_BYREF, D_OBJC },
618 { "in", RID_IN, D_OBJC },
619 { "inout", RID_INOUT, D_OBJC },
620 { "oneway", RID_ONEWAY, D_OBJC },
621 { "out", RID_OUT, D_OBJC },
622 /* These are recognized inside a property attribute list */
623 { "assign", RID_ASSIGN, D_OBJC },
624 { "atomic", RID_PROPATOMIC, D_OBJC },
625 { "copy", RID_COPY, D_OBJC },
626 { "getter", RID_GETTER, D_OBJC },
627 { "nonatomic", RID_NONATOMIC, D_OBJC },
628 { "readonly", RID_READONLY, D_OBJC },
629 { "readwrite", RID_READWRITE, D_OBJC },
630 { "retain", RID_RETAIN, D_OBJC },
631 { "setter", RID_SETTER, D_OBJC },
632 /* These are Objective C implementation of nullability, accepted only in
633 specific contexts. */
634 { "null_unspecified", RID_NULL_UNSPECIFIED, D_OBJC },
635 { "nullable", RID_NULLABLE, D_OBJC },
636 { "nonnull", RID_NONNULL, D_OBJC },
637 { "null_resettable", RID_NULL_RESETTABLE, D_OBJC },
640 const unsigned int num_c_common_reswords = ARRAY_SIZE (c_common_reswords);
642 /* Return identifier for address space AS. */
644 const char *
645 c_addr_space_name (addr_space_t as)
647 int rid = RID_FIRST_ADDR_SPACE + as;
648 gcc_assert (ridpointers [rid]);
649 return IDENTIFIER_POINTER (ridpointers [rid]);
652 /* Push current bindings for the function name VAR_DECLS. */
654 void
655 start_fname_decls (void)
657 unsigned ix;
658 tree saved = NULL_TREE;
660 for (ix = 0; fname_vars[ix].decl; ix++)
662 tree decl = *fname_vars[ix].decl;
664 if (decl)
666 saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
667 saved);
668 *fname_vars[ix].decl = NULL_TREE;
671 if (saved || saved_function_name_decls)
672 /* Normally they'll have been NULL, so only push if we've got a
673 stack, or they are non-NULL. */
674 saved_function_name_decls = tree_cons (saved, NULL_TREE,
675 saved_function_name_decls);
678 /* Finish up the current bindings, adding them into the current function's
679 statement tree. This must be done _before_ finish_stmt_tree is called.
680 If there is no current function, we must be at file scope and no statements
681 are involved. Pop the previous bindings. */
683 void
684 finish_fname_decls (void)
686 unsigned ix;
687 tree stmts = NULL_TREE;
688 tree stack = saved_function_name_decls;
690 for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
691 append_to_statement_list (TREE_VALUE (stack), &stmts);
693 if (stmts)
695 tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
697 if (TREE_CODE (*bodyp) == BIND_EXPR)
698 bodyp = &BIND_EXPR_BODY (*bodyp);
700 append_to_statement_list_force (*bodyp, &stmts);
701 *bodyp = stmts;
704 for (ix = 0; fname_vars[ix].decl; ix++)
705 *fname_vars[ix].decl = NULL_TREE;
707 if (stack)
709 /* We had saved values, restore them. */
710 tree saved;
712 for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
714 tree decl = TREE_PURPOSE (saved);
715 unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
717 *fname_vars[ix].decl = decl;
719 stack = TREE_CHAIN (stack);
721 saved_function_name_decls = stack;
724 /* Return the text name of the current function, suitably prettified
725 by PRETTY_P. Return string must be freed by caller. */
727 const char *
728 fname_as_string (int pretty_p)
730 const char *name = "top level";
731 char *namep;
732 int vrb = 2, len;
733 cpp_string cstr = { 0, 0 }, strname;
735 if (!pretty_p)
737 name = "";
738 vrb = 0;
741 if (current_function_decl)
742 name = lang_hooks.decl_printable_name (current_function_decl, vrb);
744 len = strlen (name) + 3; /* Two for '"'s. One for NULL. */
746 namep = XNEWVEC (char, len);
747 snprintf (namep, len, "\"%s\"", name);
748 strname.text = (unsigned char *) namep;
749 strname.len = len - 1;
751 if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
753 XDELETEVEC (namep);
754 return (const char *) cstr.text;
757 return namep;
760 /* Return the VAR_DECL for a const char array naming the current
761 function. If the VAR_DECL has not yet been created, create it
762 now. RID indicates how it should be formatted and IDENTIFIER_NODE
763 ID is its name (unfortunately C and C++ hold the RID values of
764 keywords in different places, so we can't derive RID from ID in
765 this language independent code. LOC is the location of the
766 function. */
768 tree
769 fname_decl (location_t loc, unsigned int rid, tree id)
771 unsigned ix;
772 tree decl = NULL_TREE;
774 for (ix = 0; fname_vars[ix].decl; ix++)
775 if (fname_vars[ix].rid == rid)
776 break;
778 decl = *fname_vars[ix].decl;
779 if (!decl)
781 /* If a tree is built here, it would normally have the lineno of
782 the current statement. Later this tree will be moved to the
783 beginning of the function and this line number will be wrong.
784 To avoid this problem set the lineno to 0 here; that prevents
785 it from appearing in the RTL. */
786 tree stmts;
787 location_t saved_location = input_location;
788 input_location = UNKNOWN_LOCATION;
790 stmts = push_stmt_list ();
791 decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
792 stmts = pop_stmt_list (stmts);
793 if (!IS_EMPTY_STMT (stmts))
794 saved_function_name_decls
795 = tree_cons (decl, stmts, saved_function_name_decls);
796 *fname_vars[ix].decl = decl;
797 input_location = saved_location;
799 if (!ix && !current_function_decl)
800 pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
802 return decl;
805 /* Given a STRING_CST, give it a suitable array-of-chars data type. */
807 tree
808 fix_string_type (tree value)
810 int length = TREE_STRING_LENGTH (value);
811 int nchars, charsz;
812 tree e_type, i_type, a_type;
814 /* Compute the number of elements, for the array type. */
815 if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
817 charsz = 1;
818 e_type = char_type_node;
820 else if (flag_char8_t && TREE_TYPE (value) == char8_array_type_node)
822 charsz = TYPE_PRECISION (char8_type_node) / BITS_PER_UNIT;
823 e_type = char8_type_node;
825 else if (TREE_TYPE (value) == char16_array_type_node)
827 charsz = TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT;
828 e_type = char16_type_node;
830 else if (TREE_TYPE (value) == char32_array_type_node)
832 charsz = TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT;
833 e_type = char32_type_node;
835 else
837 charsz = TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT;
838 e_type = wchar_type_node;
841 /* This matters only for targets where ssizetype has smaller precision
842 than 32 bits. */
843 if (wi::lts_p (wi::to_wide (TYPE_MAX_VALUE (ssizetype)), length))
845 error ("size of string literal is too large");
846 length = tree_to_shwi (TYPE_MAX_VALUE (ssizetype)) / charsz * charsz;
847 char *str = CONST_CAST (char *, TREE_STRING_POINTER (value));
848 memset (str + length, '\0',
849 MIN (TREE_STRING_LENGTH (value) - length, charsz));
850 TREE_STRING_LENGTH (value) = length;
852 nchars = length / charsz;
854 /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits). The analogous
855 limit in C++98 Annex B is very large (65536) and is not normative,
856 so we do not diagnose it (warn_overlength_strings is forced off
857 in c_common_post_options). */
858 if (warn_overlength_strings)
860 const int nchars_max = flag_isoc99 ? 4095 : 509;
861 const int relevant_std = flag_isoc99 ? 99 : 90;
862 if (nchars - 1 > nchars_max)
863 /* Translators: The %d after 'ISO C' will be 90 or 99. Do not
864 separate the %d from the 'C'. 'ISO' should not be
865 translated, but it may be moved after 'C%d' in languages
866 where modifiers follow nouns. */
867 pedwarn (input_location, OPT_Woverlength_strings,
868 "string length %qd is greater than the length %qd "
869 "ISO C%d compilers are required to support",
870 nchars - 1, nchars_max, relevant_std);
873 /* Create the array type for the string constant. The ISO C++
874 standard says that a string literal has type `const char[N]' or
875 `const wchar_t[N]'. We use the same logic when invoked as a C
876 front-end with -Wwrite-strings.
877 ??? We should change the type of an expression depending on the
878 state of a warning flag. We should just be warning -- see how
879 this is handled in the C++ front-end for the deprecated implicit
880 conversion from string literals to `char*' or `wchar_t*'.
882 The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
883 array type being the unqualified version of that type.
884 Therefore, if we are constructing an array of const char, we must
885 construct the matching unqualified array type first. The C front
886 end does not require this, but it does no harm, so we do it
887 unconditionally. */
888 i_type = build_index_type (size_int (nchars - 1));
889 a_type = build_array_type (e_type, i_type);
890 if (c_dialect_cxx() || warn_write_strings)
891 a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
893 TREE_TYPE (value) = a_type;
894 TREE_CONSTANT (value) = 1;
895 TREE_READONLY (value) = 1;
896 TREE_STATIC (value) = 1;
897 return value;
900 /* Given a string of type STRING_TYPE, determine what kind of string
901 token would give an equivalent execution encoding: CPP_STRING,
902 CPP_STRING16, or CPP_STRING32. Return CPP_OTHER in case of error.
903 This may not be exactly the string token type that initially created
904 the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
905 string type, and CPP_UTF8STRING is indistinguishable from CPP_STRING
906 at this point.
908 This effectively reverses part of the logic in lex_string and
909 fix_string_type. */
911 static enum cpp_ttype
912 get_cpp_ttype_from_string_type (tree string_type)
914 gcc_assert (string_type);
915 if (TREE_CODE (string_type) == POINTER_TYPE)
916 string_type = TREE_TYPE (string_type);
918 if (TREE_CODE (string_type) != ARRAY_TYPE)
919 return CPP_OTHER;
921 tree element_type = TREE_TYPE (string_type);
922 if (TREE_CODE (element_type) != INTEGER_TYPE)
923 return CPP_OTHER;
925 int bits_per_character = TYPE_PRECISION (element_type);
926 switch (bits_per_character)
928 case 8:
929 return CPP_STRING; /* It could have also been CPP_UTF8STRING. */
930 case 16:
931 return CPP_STRING16;
932 case 32:
933 return CPP_STRING32;
936 return CPP_OTHER;
939 /* The global record of string concatentations, for use in
940 extracting locations within string literals. */
942 GTY(()) string_concat_db *g_string_concat_db;
944 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION. */
946 const char *
947 c_get_substring_location (const substring_loc &substr_loc,
948 location_t *out_loc)
950 enum cpp_ttype tok_type
951 = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
952 if (tok_type == CPP_OTHER)
953 return "unrecognized string type";
955 return get_location_within_string (parse_in,
956 global_dc->get_file_cache (),
957 g_string_concat_db,
958 substr_loc.get_fmt_string_loc (),
959 tok_type,
960 substr_loc.get_caret_idx (),
961 substr_loc.get_start_idx (),
962 substr_loc.get_end_idx (),
963 out_loc);
967 /* Return true iff T is a boolean promoted to int. */
969 bool
970 bool_promoted_to_int_p (tree t)
972 return (CONVERT_EXPR_P (t)
973 && TREE_TYPE (t) == integer_type_node
974 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
977 /* vector_targets_convertible_p is used for vector pointer types. The
978 callers perform various checks that the qualifiers are satisfactory,
979 while OTOH vector_targets_convertible_p ignores the number of elements
980 in the vectors. That's fine with vector pointers as we can consider,
981 say, a vector of 8 elements as two consecutive vectors of 4 elements,
982 and that does not require and conversion of the pointer values.
983 In contrast, vector_types_convertible_p and
984 vector_types_compatible_elements_p are used for vector value types. */
985 /* True if pointers to distinct types T1 and T2 can be converted to
986 each other without an explicit cast. Only returns true for opaque
987 vector types. */
988 bool
989 vector_targets_convertible_p (const_tree t1, const_tree t2)
991 if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
992 && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
993 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
994 return true;
996 return false;
999 /* vector_types_convertible_p is used for vector value types.
1000 It could in principle call vector_targets_convertible_p as a subroutine,
1001 but then the check for vector type would be duplicated with its callers,
1002 and also the purpose of vector_targets_convertible_p would become
1003 muddled.
1004 Where vector_types_convertible_p returns true, a conversion might still be
1005 needed to make the types match.
1006 In contrast, vector_targets_convertible_p is used for vector pointer
1007 values, and vector_types_compatible_elements_p is used specifically
1008 in the context for binary operators, as a check if use is possible without
1009 conversion. */
1010 /* True if vector types T1 and T2 can be converted to each other
1011 without an explicit cast. If EMIT_LAX_NOTE is true, and T1 and T2
1012 can only be converted with -flax-vector-conversions yet that is not
1013 in effect, emit a note telling the user about that option if such
1014 a note has not previously been emitted. */
1015 bool
1016 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
1018 static bool emitted_lax_note = false;
1019 bool convertible_lax;
1021 if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
1022 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
1023 return true;
1025 convertible_lax =
1026 (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
1027 && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
1028 || known_eq (TYPE_VECTOR_SUBPARTS (t1),
1029 TYPE_VECTOR_SUBPARTS (t2)))
1030 && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
1031 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
1033 if (!convertible_lax || flag_lax_vector_conversions)
1034 return convertible_lax;
1036 if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
1037 && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1038 return true;
1040 if (emit_lax_note && !emitted_lax_note)
1042 emitted_lax_note = true;
1043 inform (input_location, "use %<-flax-vector-conversions%> to permit "
1044 "conversions between vectors with differing "
1045 "element types or numbers of subparts");
1048 return false;
1051 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
1052 and have vector types, V0 has the same type as V1, and the number of
1053 elements of V0, V1, MASK is the same.
1055 In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
1056 called with two arguments. In this case implementation passes the
1057 first argument twice in order to share the same tree code. This fact
1058 could enable the mask-values being twice the vector length. This is
1059 an implementation accident and this semantics is not guaranteed to
1060 the user. */
1061 tree
1062 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
1063 bool complain)
1065 tree ret;
1066 bool wrap = true;
1067 bool maybe_const = false;
1068 bool two_arguments = false;
1070 if (v1 == NULL_TREE)
1072 two_arguments = true;
1073 v1 = v0;
1076 if (v0 == error_mark_node || v1 == error_mark_node
1077 || mask == error_mark_node)
1078 return error_mark_node;
1080 if (!gnu_vector_type_p (TREE_TYPE (mask))
1081 || !VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
1083 if (complain)
1084 error_at (loc, "%<__builtin_shuffle%> last argument must "
1085 "be an integer vector");
1086 return error_mark_node;
1089 if (!gnu_vector_type_p (TREE_TYPE (v0))
1090 || !gnu_vector_type_p (TREE_TYPE (v1)))
1092 if (complain)
1093 error_at (loc, "%<__builtin_shuffle%> arguments must be vectors");
1094 return error_mark_node;
1097 if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1099 if (complain)
1100 error_at (loc, "%<__builtin_shuffle%> argument vectors must be of "
1101 "the same type");
1102 return error_mark_node;
1105 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1106 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1107 && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1108 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1110 if (complain)
1111 error_at (loc, "%<__builtin_shuffle%> number of elements of the "
1112 "argument vector(s) and the mask vector should "
1113 "be the same");
1114 return error_mark_node;
1117 if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1118 != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1120 if (complain)
1121 error_at (loc, "%<__builtin_shuffle%> argument vector(s) inner type "
1122 "must have the same size as inner type of the mask");
1123 return error_mark_node;
1126 if (!c_dialect_cxx ())
1128 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1129 v0 = c_fully_fold (v0, false, &maybe_const);
1130 wrap &= maybe_const;
1132 if (two_arguments)
1133 v1 = v0 = save_expr (v0);
1134 else
1136 v1 = c_fully_fold (v1, false, &maybe_const);
1137 wrap &= maybe_const;
1140 mask = c_fully_fold (mask, false, &maybe_const);
1141 wrap &= maybe_const;
1143 else if (two_arguments)
1144 v1 = v0 = save_expr (v0);
1146 ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1148 if (!c_dialect_cxx () && !wrap)
1149 ret = c_wrap_maybe_const (ret, true);
1151 return ret;
1154 /* Build a VEC_PERM_EXPR if V0, V1 are not error_mark_nodes
1155 and have vector types, V0 has the same element type as V1, and the
1156 number of elements the result is that of MASK. */
1157 tree
1158 c_build_shufflevector (location_t loc, tree v0, tree v1,
1159 const vec<tree> &mask, bool complain)
1161 tree ret;
1162 bool wrap = true;
1163 bool maybe_const = false;
1165 if (v0 == error_mark_node || v1 == error_mark_node)
1166 return error_mark_node;
1168 if (!gnu_vector_type_p (TREE_TYPE (v0))
1169 || !gnu_vector_type_p (TREE_TYPE (v1)))
1171 if (complain)
1172 error_at (loc, "%<__builtin_shufflevector%> arguments must be vectors");
1173 return error_mark_node;
1176 /* ??? In principle one could select a constant part of a variable size
1177 vector but things get a bit awkward with trying to support this here. */
1178 unsigned HOST_WIDE_INT v0n, v1n;
1179 if (!TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)).is_constant (&v0n)
1180 || !TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)).is_constant (&v1n))
1182 if (complain)
1183 error_at (loc, "%<__builtin_shufflevector%> arguments must be constant"
1184 " size vectors");
1185 return error_mark_node;
1188 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v0)))
1189 != TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v1))))
1191 if (complain)
1192 error_at (loc, "%<__builtin_shufflevector%> argument vectors must "
1193 "have the same element type");
1194 return error_mark_node;
1197 if (!pow2p_hwi (mask.length ()))
1199 if (complain)
1200 error_at (loc, "%<__builtin_shufflevector%> must specify a result "
1201 "with a power of two number of elements");
1202 return error_mark_node;
1205 if (!c_dialect_cxx ())
1207 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1208 v0 = c_fully_fold (v0, false, &maybe_const);
1209 wrap &= maybe_const;
1211 v1 = c_fully_fold (v1, false, &maybe_const);
1212 wrap &= maybe_const;
1215 unsigned HOST_WIDE_INT maskl = MAX (mask.length (), MAX (v0n, v1n));
1216 unsigned HOST_WIDE_INT pad = (v0n < maskl ? maskl - v0n : 0);
1217 vec_perm_builder sel (maskl, maskl, 1);
1218 unsigned i;
1219 for (i = 0; i < mask.length (); ++i)
1221 tree idx = mask[i];
1222 if (!tree_fits_shwi_p (idx))
1224 if (complain)
1225 error_at (loc, "invalid element index %qE to "
1226 "%<__builtin_shufflevector%>", idx);
1227 return error_mark_node;
1229 HOST_WIDE_INT iidx = tree_to_shwi (idx);
1230 if (iidx < -1
1231 || (iidx != -1
1232 && (unsigned HOST_WIDE_INT) iidx >= v0n + v1n))
1234 if (complain)
1235 error_at (loc, "invalid element index %qE to "
1236 "%<__builtin_shufflevector%>", idx);
1237 return error_mark_node;
1239 /* ??? Our VEC_PERM_EXPR does not allow for -1 yet. */
1240 if (iidx == -1)
1241 iidx = i;
1242 /* ??? Our VEC_PERM_EXPR does not allow different sized inputs,
1243 so pad out a smaller v0. */
1244 else if ((unsigned HOST_WIDE_INT) iidx >= v0n)
1245 iidx += pad;
1246 sel.quick_push (iidx);
1248 /* ??? VEC_PERM_EXPR does not support a result that is smaller than
1249 the inputs, so we have to pad id out. */
1250 for (; i < maskl; ++i)
1251 sel.quick_push (i);
1253 vec_perm_indices indices (sel, 2, maskl);
1255 tree ret_type = build_vector_type (TREE_TYPE (TREE_TYPE (v0)), maskl);
1256 tree mask_type = build_vector_type (build_nonstandard_integer_type
1257 (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (ret_type))), 1),
1258 maskl);
1259 /* Pad out arguments to the common vector size. */
1260 if (v0n < maskl)
1262 constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v0)) };
1263 v0 = build_constructor_single (ret_type, NULL_TREE, v0);
1264 for (i = 1; i < maskl / v0n; ++i)
1265 vec_safe_push (CONSTRUCTOR_ELTS (v0), elt);
1267 if (v1n < maskl)
1269 constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v1)) };
1270 v1 = build_constructor_single (ret_type, NULL_TREE, v1);
1271 for (i = 1; i < maskl / v1n; ++i)
1272 vec_safe_push (CONSTRUCTOR_ELTS (v1), elt);
1274 ret = build3_loc (loc, VEC_PERM_EXPR, ret_type, v0, v1,
1275 vec_perm_indices_to_tree (mask_type, indices));
1276 /* Get the lowpart we are interested in. */
1277 if (mask.length () < maskl)
1279 tree lpartt = build_vector_type (TREE_TYPE (ret_type), mask.length ());
1280 ret = build3_loc (loc, BIT_FIELD_REF,
1281 lpartt, ret, TYPE_SIZE (lpartt), bitsize_zero_node);
1282 /* Wrap the lowpart operation in a TARGET_EXPR so it gets a separate
1283 temporary during gimplification. See PR101530 for cases where
1284 we'd otherwise end up with non-toplevel BIT_FIELD_REFs. */
1285 tree tem = create_tmp_var_raw (lpartt);
1286 DECL_CONTEXT (tem) = current_function_decl;
1287 ret = build4 (TARGET_EXPR, lpartt, tem, ret, NULL_TREE, NULL_TREE);
1288 TREE_SIDE_EFFECTS (ret) = 1;
1291 if (!c_dialect_cxx () && !wrap)
1292 ret = c_wrap_maybe_const (ret, true);
1294 return ret;
1297 /* Build a VEC_CONVERT ifn for __builtin_convertvector builtin. */
1299 tree
1300 c_build_vec_convert (location_t loc1, tree expr, location_t loc2, tree type,
1301 bool complain)
1303 if (error_operand_p (type))
1304 return error_mark_node;
1305 if (error_operand_p (expr))
1306 return error_mark_node;
1308 if (!gnu_vector_type_p (TREE_TYPE (expr))
1309 || (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1310 && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (expr))))
1312 if (complain)
1313 error_at (loc1, "%<__builtin_convertvector%> first argument must "
1314 "be an integer or floating vector");
1315 return error_mark_node;
1318 if (!gnu_vector_type_p (type)
1319 || (!VECTOR_INTEGER_TYPE_P (type) && !VECTOR_FLOAT_TYPE_P (type)))
1321 if (complain)
1322 error_at (loc2, "%<__builtin_convertvector%> second argument must "
1323 "be an integer or floating vector type");
1324 return error_mark_node;
1327 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (expr)),
1328 TYPE_VECTOR_SUBPARTS (type)))
1330 if (complain)
1331 error_at (loc1, "%<__builtin_convertvector%> number of elements "
1332 "of the first argument vector and the second argument "
1333 "vector type should be the same");
1334 return error_mark_node;
1337 if ((TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (expr)))
1338 == TYPE_MAIN_VARIANT (TREE_TYPE (type)))
1339 || (VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1340 && VECTOR_INTEGER_TYPE_P (type)
1341 && (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (expr)))
1342 == TYPE_PRECISION (TREE_TYPE (type)))))
1343 return build1_loc (loc1, VIEW_CONVERT_EXPR, type, expr);
1345 bool wrap = true;
1346 bool maybe_const = false;
1347 tree ret;
1348 if (!c_dialect_cxx ())
1350 /* Avoid C_MAYBE_CONST_EXPRs inside of VEC_CONVERT argument. */
1351 expr = c_fully_fold (expr, false, &maybe_const);
1352 wrap &= maybe_const;
1355 ret = build_call_expr_internal_loc (loc1, IFN_VEC_CONVERT, type, 1, expr);
1357 if (!wrap)
1358 ret = c_wrap_maybe_const (ret, true);
1360 return ret;
1363 /* Like tree.cc:get_narrower, but retain conversion from C++0x scoped enum
1364 to integral type. */
1366 tree
1367 c_common_get_narrower (tree op, int *unsignedp_ptr)
1369 op = get_narrower (op, unsignedp_ptr);
1371 if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1372 && ENUM_IS_SCOPED (TREE_TYPE (op)))
1374 /* C++0x scoped enumerations don't implicitly convert to integral
1375 type; if we stripped an explicit conversion to a larger type we
1376 need to replace it so common_type will still work. */
1377 tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1378 TYPE_UNSIGNED (TREE_TYPE (op)));
1379 op = fold_convert (type, op);
1381 return op;
1384 /* This is a helper function of build_binary_op.
1386 For certain operations if both args were extended from the same
1387 smaller type, do the arithmetic in that type and then extend.
1389 BITWISE indicates a bitwise operation.
1390 For them, this optimization is safe only if
1391 both args are zero-extended or both are sign-extended.
1392 Otherwise, we might change the result.
1393 Eg, (short)-1 | (unsigned short)-1 is (int)-1
1394 but calculated in (unsigned short) it would be (unsigned short)-1.
1396 tree
1397 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1399 int unsigned0, unsigned1;
1400 tree arg0, arg1;
1401 int uns;
1402 tree type;
1404 /* Do not shorten vector operations. */
1405 if (VECTOR_TYPE_P (result_type))
1406 return result_type;
1408 /* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
1409 excessive narrowing when we call get_narrower below. For
1410 example, suppose that OP0 is of unsigned int extended
1411 from signed char and that RESULT_TYPE is long long int.
1412 If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1413 like
1415 (long long int) (unsigned int) signed_char
1417 which get_narrower would narrow down to
1419 (unsigned int) signed char
1421 If we do not cast OP0 first, get_narrower would return
1422 signed_char, which is inconsistent with the case of the
1423 explicit cast. */
1424 op0 = convert (result_type, op0);
1425 op1 = convert (result_type, op1);
1427 arg0 = c_common_get_narrower (op0, &unsigned0);
1428 arg1 = c_common_get_narrower (op1, &unsigned1);
1430 /* UNS is 1 if the operation to be done is an unsigned one. */
1431 uns = TYPE_UNSIGNED (result_type);
1433 /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1434 but it *requires* conversion to FINAL_TYPE. */
1436 if ((TYPE_PRECISION (TREE_TYPE (op0))
1437 == TYPE_PRECISION (TREE_TYPE (arg0)))
1438 && TREE_TYPE (op0) != result_type)
1439 unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1440 if ((TYPE_PRECISION (TREE_TYPE (op1))
1441 == TYPE_PRECISION (TREE_TYPE (arg1)))
1442 && TREE_TYPE (op1) != result_type)
1443 unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1445 /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
1447 /* For bitwise operations, signedness of nominal type
1448 does not matter. Consider only how operands were extended. */
1449 if (bitwise)
1450 uns = unsigned0;
1452 /* Note that in all three cases below we refrain from optimizing
1453 an unsigned operation on sign-extended args.
1454 That would not be valid. */
1456 /* Both args variable: if both extended in same way
1457 from same width, do it in that width.
1458 Do it unsigned if args were zero-extended. */
1459 if ((TYPE_PRECISION (TREE_TYPE (arg0))
1460 < TYPE_PRECISION (result_type))
1461 && (TYPE_PRECISION (TREE_TYPE (arg1))
1462 == TYPE_PRECISION (TREE_TYPE (arg0)))
1463 && unsigned0 == unsigned1
1464 && (unsigned0 || !uns))
1466 tree ctype = common_type (TREE_TYPE (arg0), TREE_TYPE (arg1));
1467 if (ctype != error_mark_node)
1468 return c_common_signed_or_unsigned_type (unsigned0, ctype);
1471 else if (TREE_CODE (arg0) == INTEGER_CST
1472 && (unsigned1 || !uns)
1473 && (TYPE_PRECISION (TREE_TYPE (arg1))
1474 < TYPE_PRECISION (result_type))
1475 && (type
1476 = c_common_signed_or_unsigned_type (unsigned1,
1477 TREE_TYPE (arg1)))
1478 && !POINTER_TYPE_P (type)
1479 && int_fits_type_p (arg0, type))
1480 return type;
1482 else if (TREE_CODE (arg1) == INTEGER_CST
1483 && (unsigned0 || !uns)
1484 && (TYPE_PRECISION (TREE_TYPE (arg0))
1485 < TYPE_PRECISION (result_type))
1486 && (type
1487 = c_common_signed_or_unsigned_type (unsigned0,
1488 TREE_TYPE (arg0)))
1489 && !POINTER_TYPE_P (type)
1490 && int_fits_type_p (arg1, type))
1491 return type;
1493 return result_type;
1496 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1497 real of type TO_TYPE. This is a helper function for unsafe_conversion_p. */
1499 static bool
1500 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1502 tree type_low_bound = TYPE_MIN_VALUE (from_type);
1503 tree type_high_bound = TYPE_MAX_VALUE (from_type);
1504 REAL_VALUE_TYPE real_low_bound =
1505 real_value_from_int_cst (0, type_low_bound);
1506 REAL_VALUE_TYPE real_high_bound =
1507 real_value_from_int_cst (0, type_high_bound);
1509 return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1510 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1513 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1514 to the complex/real/integer type TYPE. Function returns non-zero when:
1515 * EXPR is a constant which cannot be exactly converted to TYPE.
1516 * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1517 for EXPR type and TYPE being both integers or both real, or both
1518 complex.
1519 * EXPR is not a constant of complex type and TYPE is a real or
1520 an integer.
1521 * EXPR is not a constant of real type and TYPE is an integer.
1522 * EXPR is not a constant of integer type which cannot be
1523 exactly converted to real type.
1525 Function allows conversions between types of different signedness if
1526 CHECK_SIGN is false and can return SAFE_CONVERSION (zero) in that
1527 case. Function can return UNSAFE_SIGN if CHECK_SIGN is true.
1529 RESULT, when non-null is the result of the conversion. When constant
1530 it is included in the text of diagnostics.
1532 Function allows conversions from complex constants to non-complex types,
1533 provided that imaginary part is zero and real part can be safely converted
1534 to TYPE. */
1536 enum conversion_safety
1537 unsafe_conversion_p (tree type, tree expr, tree result, bool check_sign)
1539 enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1540 tree expr_type = TREE_TYPE (expr);
1542 expr = fold_for_warn (expr);
1544 if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1546 /* If type is complex, we are interested in compatibility with
1547 underlying type. */
1548 if (TREE_CODE (type) == COMPLEX_TYPE)
1549 type = TREE_TYPE (type);
1551 /* Warn for real constant that is not an exact integer converted
1552 to integer type. */
1553 if (SCALAR_FLOAT_TYPE_P (expr_type)
1554 && (TREE_CODE (type) == INTEGER_TYPE
1555 || TREE_CODE (type) == BITINT_TYPE))
1557 if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1558 give_warning = UNSAFE_REAL;
1560 /* Warn for an integer constant that does not fit into integer type. */
1561 else if ((TREE_CODE (expr_type) == INTEGER_TYPE
1562 || TREE_CODE (expr_type) == BITINT_TYPE)
1563 && (TREE_CODE (type) == INTEGER_TYPE
1564 || TREE_CODE (type) == BITINT_TYPE)
1565 && !int_fits_type_p (expr, type))
1567 if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1568 && tree_int_cst_sgn (expr) < 0)
1570 if (check_sign)
1571 give_warning = UNSAFE_SIGN;
1573 else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1575 if (check_sign)
1576 give_warning = UNSAFE_SIGN;
1578 else
1579 give_warning = UNSAFE_OTHER;
1581 else if (SCALAR_FLOAT_TYPE_P (type))
1583 /* Warn for an integer constant that does not fit into real type. */
1584 if (TREE_CODE (expr_type) == INTEGER_TYPE
1585 || TREE_CODE (expr_type) == BITINT_TYPE)
1587 REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1588 if (!exact_real_truncate (TYPE_MODE (type), &a))
1589 give_warning = UNSAFE_REAL;
1591 /* Warn for a real constant that does not fit into a smaller
1592 real type. */
1593 else if (SCALAR_FLOAT_TYPE_P (expr_type)
1594 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1596 REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1597 if (!exact_real_truncate (TYPE_MODE (type), &a))
1598 give_warning = UNSAFE_REAL;
1603 else if (TREE_CODE (expr) == COMPLEX_CST)
1605 tree imag_part = TREE_IMAGPART (expr);
1606 /* Conversion from complex constant with zero imaginary part,
1607 perform check for conversion of real part. */
1608 if ((TREE_CODE (imag_part) == REAL_CST
1609 && real_zerop (imag_part))
1610 || (TREE_CODE (imag_part) == INTEGER_CST
1611 && integer_zerop (imag_part)))
1612 /* Note: in this branch we use recursive call to unsafe_conversion_p
1613 with different type of EXPR, but it is still safe, because when EXPR
1614 is a constant, it's type is not used in text of generated warnings
1615 (otherwise they could sound misleading). */
1616 return unsafe_conversion_p (type, TREE_REALPART (expr), result,
1617 check_sign);
1618 /* Conversion from complex constant with non-zero imaginary part. */
1619 else
1621 /* Conversion to complex type.
1622 Perform checks for both real and imaginary parts. */
1623 if (TREE_CODE (type) == COMPLEX_TYPE)
1625 enum conversion_safety re_safety =
1626 unsafe_conversion_p (type, TREE_REALPART (expr),
1627 result, check_sign);
1628 enum conversion_safety im_safety =
1629 unsafe_conversion_p (type, imag_part, result, check_sign);
1631 /* Merge the results into appropriate single warning. */
1633 /* Note: this case includes SAFE_CONVERSION, i.e. success. */
1634 if (re_safety == im_safety)
1635 give_warning = re_safety;
1636 else if (!re_safety && im_safety)
1637 give_warning = im_safety;
1638 else if (re_safety && !im_safety)
1639 give_warning = re_safety;
1640 else
1641 give_warning = UNSAFE_OTHER;
1643 /* Warn about conversion from complex to real or integer type. */
1644 else
1645 give_warning = UNSAFE_IMAGINARY;
1649 /* Checks for remaining case: EXPR is not constant. */
1650 else
1652 /* Warn for real types converted to integer types. */
1653 if (SCALAR_FLOAT_TYPE_P (expr_type)
1654 && (TREE_CODE (type) == INTEGER_TYPE
1655 || TREE_CODE (type) == BITINT_TYPE))
1656 give_warning = UNSAFE_REAL;
1658 else if ((TREE_CODE (expr_type) == INTEGER_TYPE
1659 || TREE_CODE (expr_type) == BITINT_TYPE)
1660 && (TREE_CODE (type) == INTEGER_TYPE
1661 || TREE_CODE (type) == BITINT_TYPE))
1663 /* Don't warn about unsigned char y = 0xff, x = (int) y; */
1664 expr = get_unwidened (expr, 0);
1665 expr_type = TREE_TYPE (expr);
1667 /* Don't warn for short y; short x = ((int)y & 0xff); */
1668 if (TREE_CODE (expr) == BIT_AND_EXPR
1669 || TREE_CODE (expr) == BIT_IOR_EXPR
1670 || TREE_CODE (expr) == BIT_XOR_EXPR)
1672 /* If both args were extended from a shortest type,
1673 use that type if that is safe. */
1674 expr_type = shorten_binary_op (expr_type,
1675 TREE_OPERAND (expr, 0),
1676 TREE_OPERAND (expr, 1),
1677 /* bitwise */1);
1679 if (TREE_CODE (expr) == BIT_AND_EXPR)
1681 tree op0 = TREE_OPERAND (expr, 0);
1682 tree op1 = TREE_OPERAND (expr, 1);
1683 bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1684 bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1686 /* If one of the operands is a non-negative constant
1687 that fits in the target type, then the type of the
1688 other operand does not matter. */
1689 if ((TREE_CODE (op0) == INTEGER_CST
1690 && int_fits_type_p (op0, c_common_signed_type (type))
1691 && int_fits_type_p (op0, c_common_unsigned_type (type)))
1692 || (TREE_CODE (op1) == INTEGER_CST
1693 && int_fits_type_p (op1, c_common_signed_type (type))
1694 && int_fits_type_p (op1,
1695 c_common_unsigned_type (type))))
1696 return SAFE_CONVERSION;
1697 /* If constant is unsigned and fits in the target
1698 type, then the result will also fit. */
1699 else if ((TREE_CODE (op0) == INTEGER_CST
1700 && unsigned0
1701 && int_fits_type_p (op0, type))
1702 || (TREE_CODE (op1) == INTEGER_CST
1703 && unsigned1
1704 && int_fits_type_p (op1, type)))
1705 return SAFE_CONVERSION;
1708 /* Warn for integer types converted to smaller integer types. */
1709 if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1710 give_warning = UNSAFE_OTHER;
1712 /* When they are the same width but different signedness,
1713 then the value may change. */
1714 else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1715 && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1716 /* Even when converted to a bigger type, if the type is
1717 unsigned but expr is signed, then negative values
1718 will be changed. */
1719 || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1720 && check_sign)
1721 give_warning = UNSAFE_SIGN;
1724 /* Warn for integer types converted to real types if and only if
1725 all the range of values of the integer type cannot be
1726 represented by the real type. */
1727 else if ((TREE_CODE (expr_type) == INTEGER_TYPE
1728 || TREE_CODE (expr_type) == BITINT_TYPE)
1729 && SCALAR_FLOAT_TYPE_P (type))
1731 /* Don't warn about char y = 0xff; float x = (int) y; */
1732 expr = get_unwidened (expr, 0);
1733 expr_type = TREE_TYPE (expr);
1735 if (!int_safely_convertible_to_real_p (expr_type, type))
1736 give_warning = UNSAFE_OTHER;
1739 /* Warn for real types converted to smaller real types. */
1740 else if (SCALAR_FLOAT_TYPE_P (expr_type)
1741 && SCALAR_FLOAT_TYPE_P (type)
1742 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1743 give_warning = UNSAFE_REAL;
1745 /* Check conversion between two complex types. */
1746 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1747 && TREE_CODE (type) == COMPLEX_TYPE)
1749 /* Extract underlying types (i.e., type of real and imaginary
1750 parts) of expr_type and type. */
1751 tree from_type = TREE_TYPE (expr_type);
1752 tree to_type = TREE_TYPE (type);
1754 /* Warn for real types converted to integer types. */
1755 if (SCALAR_FLOAT_TYPE_P (from_type)
1756 && TREE_CODE (to_type) == INTEGER_TYPE)
1757 give_warning = UNSAFE_REAL;
1759 /* Warn for real types converted to smaller real types. */
1760 else if (SCALAR_FLOAT_TYPE_P (from_type)
1761 && SCALAR_FLOAT_TYPE_P (to_type)
1762 && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1763 give_warning = UNSAFE_REAL;
1765 /* Check conversion for complex integer types. Here implementation
1766 is simpler than for real-domain integers because it does not
1767 involve sophisticated cases, such as bitmasks, casts, etc. */
1768 else if (TREE_CODE (from_type) == INTEGER_TYPE
1769 && TREE_CODE (to_type) == INTEGER_TYPE)
1771 /* Warn for integer types converted to smaller integer types. */
1772 if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1773 give_warning = UNSAFE_OTHER;
1775 /* Check for different signedness, see case for real-domain
1776 integers (above) for a more detailed comment. */
1777 else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1778 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1779 || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1780 && check_sign)
1781 give_warning = UNSAFE_SIGN;
1783 else if (TREE_CODE (from_type) == INTEGER_TYPE
1784 && SCALAR_FLOAT_TYPE_P (to_type)
1785 && !int_safely_convertible_to_real_p (from_type, to_type))
1786 give_warning = UNSAFE_OTHER;
1789 /* Warn for complex types converted to real or integer types. */
1790 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1791 && TREE_CODE (type) != COMPLEX_TYPE)
1792 give_warning = UNSAFE_IMAGINARY;
1795 return give_warning;
1799 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1800 Invoke this function on every expression that is converted implicitly,
1801 i.e. because of language rules and not because of an explicit cast.
1802 INIT_CONST is true if the conversion is for arithmetic types for a static
1803 initializer and folding must apply accordingly (discarding floating-point
1804 exceptions and assuming the default rounding mode is in effect). */
1806 tree
1807 convert_and_check (location_t loc, tree type, tree expr, bool init_const)
1809 tree result;
1810 tree expr_for_warning;
1812 /* Convert from a value with possible excess precision rather than
1813 via the semantic type, but do not warn about values not fitting
1814 exactly in the semantic type. */
1815 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1817 tree orig_type = TREE_TYPE (expr);
1818 expr = TREE_OPERAND (expr, 0);
1819 expr_for_warning = (init_const
1820 ? convert_init (orig_type, expr)
1821 : convert (orig_type, expr));
1822 if (orig_type == type)
1823 return expr_for_warning;
1825 else
1826 expr_for_warning = expr;
1828 if (TREE_TYPE (expr) == type)
1829 return expr;
1831 result = init_const ? convert_init (type, expr) : convert (type, expr);
1833 if (c_inhibit_evaluation_warnings == 0
1834 && !TREE_OVERFLOW_P (expr)
1835 && result != error_mark_node
1836 && !c_hardbool_type_attr (type))
1837 warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1839 return result;
1842 /* A node in a list that describes references to variables (EXPR), which are
1843 either read accesses if WRITER is zero, or write accesses, in which case
1844 WRITER is the parent of EXPR. */
1845 struct tlist
1847 struct tlist *next;
1848 tree expr, writer;
1851 /* Used to implement a cache the results of a call to verify_tree. We only
1852 use this for SAVE_EXPRs. */
1853 struct tlist_cache
1855 struct tlist_cache *next;
1856 struct tlist *cache_before_sp;
1857 struct tlist *cache_after_sp;
1858 tree expr;
1861 /* Obstack to use when allocating tlist structures, and corresponding
1862 firstobj. */
1863 static struct obstack tlist_obstack;
1864 static char *tlist_firstobj = 0;
1866 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1867 warnings. */
1868 static struct tlist *warned_ids;
1869 /* SAVE_EXPRs need special treatment. We process them only once and then
1870 cache the results. */
1871 static struct tlist_cache *save_expr_cache;
1873 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1874 static void merge_tlist (struct tlist **, struct tlist *, int);
1875 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1876 static bool warning_candidate_p (tree);
1877 static bool candidate_equal_p (const_tree, const_tree);
1878 static void warn_for_collisions (struct tlist *);
1879 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1880 static struct tlist *new_tlist (struct tlist *, tree, tree);
1882 /* Create a new struct tlist and fill in its fields. */
1883 static struct tlist *
1884 new_tlist (struct tlist *next, tree t, tree writer)
1886 struct tlist *l;
1887 l = XOBNEW (&tlist_obstack, struct tlist);
1888 l->next = next;
1889 l->expr = t;
1890 l->writer = writer;
1891 return l;
1894 /* Add duplicates of the nodes found in ADD to the list *TO. If EXCLUDE_WRITER
1895 is nonnull, we ignore any node we find which has a writer equal to it. */
1897 static void
1898 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1900 while (add)
1902 struct tlist *next = add->next;
1903 if (!copy)
1904 add->next = *to;
1905 if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1906 *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1907 add = next;
1911 /* Merge the nodes of ADD into TO. This merging process is done so that for
1912 each variable that already exists in TO, no new node is added; however if
1913 there is a write access recorded in ADD, and an occurrence on TO is only
1914 a read access, then the occurrence in TO will be modified to record the
1915 write. */
1917 static void
1918 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1920 struct tlist **end = to;
1922 while (*end)
1923 end = &(*end)->next;
1925 while (add)
1927 int found = 0;
1928 struct tlist *tmp2;
1929 struct tlist *next = add->next;
1931 for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1932 if (candidate_equal_p (tmp2->expr, add->expr))
1934 found = 1;
1935 if (!tmp2->writer)
1936 tmp2->writer = add->writer;
1938 if (!found)
1940 *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1941 end = &(*end)->next;
1942 *end = 0;
1944 add = next;
1948 /* WRITTEN is a variable, WRITER is its parent. Warn if any of the variable
1949 references in list LIST conflict with it, excluding reads if ONLY writers
1950 is nonzero. */
1952 static void
1953 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1954 int only_writes)
1956 struct tlist *tmp;
1958 /* Avoid duplicate warnings. */
1959 for (tmp = warned_ids; tmp; tmp = tmp->next)
1960 if (candidate_equal_p (tmp->expr, written))
1961 return;
1963 while (list)
1965 if (candidate_equal_p (list->expr, written)
1966 && !candidate_equal_p (list->writer, writer)
1967 && (!only_writes || list->writer))
1969 warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1970 warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1971 OPT_Wsequence_point, "operation on %qE may be undefined",
1972 list->expr);
1974 list = list->next;
1978 /* Given a list LIST of references to variables, find whether any of these
1979 can cause conflicts due to missing sequence points. */
1981 static void
1982 warn_for_collisions (struct tlist *list)
1984 struct tlist *tmp;
1986 for (tmp = list; tmp; tmp = tmp->next)
1988 if (tmp->writer)
1989 warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1993 /* Return nonzero if X is a tree that can be verified by the sequence point
1994 warnings. */
1996 static bool
1997 warning_candidate_p (tree x)
1999 if (DECL_P (x) && DECL_ARTIFICIAL (x))
2000 return false;
2002 if (TREE_CODE (x) == BLOCK)
2003 return false;
2005 /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.cc
2006 (lvalue_p) crash on TRY/CATCH. */
2007 if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
2008 return false;
2010 if (!lvalue_p (x))
2011 return false;
2013 /* No point to track non-const calls, they will never satisfy
2014 operand_equal_p. */
2015 if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
2016 return false;
2018 if (TREE_CODE (x) == STRING_CST)
2019 return false;
2021 return true;
2024 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
2025 static bool
2026 candidate_equal_p (const_tree x, const_tree y)
2028 return (x == y) || (x && y && operand_equal_p (x, y, 0));
2031 /* Walk the tree X, and record accesses to variables. If X is written by the
2032 parent tree, WRITER is the parent.
2033 We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP. If this
2034 expression or its only operand forces a sequence point, then everything up
2035 to the sequence point is stored in PBEFORE_SP. Everything else gets stored
2036 in PNO_SP.
2037 Once we return, we will have emitted warnings if any subexpression before
2038 such a sequence point could be undefined. On a higher level, however, the
2039 sequence point may not be relevant, and we'll merge the two lists.
2041 Example: (b++, a) + b;
2042 The call that processes the COMPOUND_EXPR will store the increment of B
2043 in PBEFORE_SP, and the use of A in PNO_SP. The higher-level call that
2044 processes the PLUS_EXPR will need to merge the two lists so that
2045 eventually, all accesses end up on the same list (and we'll warn about the
2046 unordered subexpressions b++ and b.
2048 A note on merging. If we modify the former example so that our expression
2049 becomes
2050 (b++, b) + a
2051 care must be taken not simply to add all three expressions into the final
2052 PNO_SP list. The function merge_tlist takes care of that by merging the
2053 before-SP list of the COMPOUND_EXPR into its after-SP list in a special
2054 way, so that no more than one access to B is recorded. */
2056 static void
2057 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
2058 tree writer)
2060 struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
2061 enum tree_code code;
2062 enum tree_code_class cl;
2064 restart:
2065 /* X may be NULL if it is the operand of an empty statement expression
2066 ({ }). */
2067 if (x == NULL)
2068 return;
2070 code = TREE_CODE (x);
2071 cl = TREE_CODE_CLASS (code);
2073 if (warning_candidate_p (x))
2074 *pno_sp = new_tlist (*pno_sp, x, writer);
2076 switch (code)
2078 case CONSTRUCTOR:
2079 case SIZEOF_EXPR:
2080 case PAREN_SIZEOF_EXPR:
2081 return;
2083 case COMPOUND_EXPR:
2084 case TRUTH_ANDIF_EXPR:
2085 case TRUTH_ORIF_EXPR:
2086 sequenced_binary:
2087 tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
2088 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2089 warn_for_collisions (tmp_nosp);
2090 merge_tlist (pbefore_sp, tmp_before, 0);
2091 merge_tlist (pbefore_sp, tmp_nosp, 0);
2092 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
2093 warn_for_collisions (tmp_list2);
2094 merge_tlist (pbefore_sp, tmp_list3, 0);
2095 merge_tlist (pno_sp, tmp_list2, 0);
2096 return;
2098 case COND_EXPR:
2099 tmp_before = tmp_list2 = 0;
2100 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
2101 warn_for_collisions (tmp_list2);
2102 merge_tlist (pbefore_sp, tmp_before, 0);
2103 merge_tlist (pbefore_sp, tmp_list2, 0);
2105 tmp_list3 = tmp_nosp = 0;
2106 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
2107 warn_for_collisions (tmp_nosp);
2108 merge_tlist (pbefore_sp, tmp_list3, 0);
2110 tmp_list3 = tmp_list2 = 0;
2111 verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
2112 warn_for_collisions (tmp_list2);
2113 merge_tlist (pbefore_sp, tmp_list3, 0);
2114 /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
2115 two first, to avoid warning for (a ? b++ : b++). */
2116 merge_tlist (&tmp_nosp, tmp_list2, 0);
2117 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2118 return;
2120 case PREDECREMENT_EXPR:
2121 case PREINCREMENT_EXPR:
2122 case POSTDECREMENT_EXPR:
2123 case POSTINCREMENT_EXPR:
2124 verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
2125 return;
2127 case MODIFY_EXPR:
2128 tmp_before = tmp_nosp = tmp_list3 = 0;
2129 verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
2130 verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
2131 /* Expressions inside the LHS are not ordered wrt. the sequence points
2132 in the RHS. Example:
2133 *a = (a++, 2)
2134 Despite the fact that the modification of "a" is in the before_sp
2135 list (tmp_before), it conflicts with the use of "a" in the LHS.
2136 We can handle this by adding the contents of tmp_list3
2137 to those of tmp_before, and redoing the collision warnings for that
2138 list. */
2139 add_tlist (&tmp_before, tmp_list3, x, 1);
2140 warn_for_collisions (tmp_before);
2141 /* Exclude the LHS itself here; we first have to merge it into the
2142 tmp_nosp list. This is done to avoid warning for "a = a"; if we
2143 didn't exclude the LHS, we'd get it twice, once as a read and once
2144 as a write. */
2145 add_tlist (pno_sp, tmp_list3, x, 0);
2146 warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
2148 merge_tlist (pbefore_sp, tmp_before, 0);
2149 if (warning_candidate_p (TREE_OPERAND (x, 0)))
2150 merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
2151 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
2152 return;
2154 case CALL_EXPR:
2155 /* We need to warn about conflicts among arguments and conflicts between
2156 args and the function address. Side effects of the function address,
2157 however, are not ordered by the sequence point of the call. */
2159 call_expr_arg_iterator iter;
2160 tree arg;
2161 tmp_before = tmp_nosp = 0;
2162 verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
2163 FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
2165 tmp_list2 = tmp_list3 = 0;
2166 verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
2167 merge_tlist (&tmp_list3, tmp_list2, 0);
2168 add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
2170 add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
2171 warn_for_collisions (tmp_before);
2172 add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
2173 return;
2176 case TREE_LIST:
2177 /* Scan all the list, e.g. indices of multi dimensional array. */
2178 while (x)
2180 tmp_before = tmp_nosp = 0;
2181 verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
2182 merge_tlist (&tmp_nosp, tmp_before, 0);
2183 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2184 x = TREE_CHAIN (x);
2186 return;
2188 case SAVE_EXPR:
2190 struct tlist_cache *t;
2191 for (t = save_expr_cache; t; t = t->next)
2192 if (candidate_equal_p (t->expr, x))
2193 break;
2195 if (!t)
2197 t = XOBNEW (&tlist_obstack, struct tlist_cache);
2198 t->next = save_expr_cache;
2199 t->expr = x;
2200 save_expr_cache = t;
2202 tmp_before = tmp_nosp = 0;
2203 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2204 warn_for_collisions (tmp_nosp);
2206 tmp_list3 = 0;
2207 merge_tlist (&tmp_list3, tmp_nosp, 0);
2208 t->cache_before_sp = tmp_before;
2209 t->cache_after_sp = tmp_list3;
2211 merge_tlist (pbefore_sp, t->cache_before_sp, 1);
2212 add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
2213 return;
2216 case ADDR_EXPR:
2217 x = TREE_OPERAND (x, 0);
2218 if (DECL_P (x))
2219 return;
2220 writer = 0;
2221 goto restart;
2223 case VIEW_CONVERT_EXPR:
2224 if (location_wrapper_p (x))
2226 x = TREE_OPERAND (x, 0);
2227 goto restart;
2229 goto do_default;
2231 case LSHIFT_EXPR:
2232 case RSHIFT_EXPR:
2233 case ARRAY_REF:
2234 if (cxx_dialect >= cxx17)
2235 goto sequenced_binary;
2236 goto do_default;
2238 case COMPONENT_REF:
2239 /* Treat as unary, the other operands aren't evaluated. */
2240 x = TREE_OPERAND (x, 0);
2241 writer = 0;
2242 goto restart;
2244 default:
2245 do_default:
2246 /* For other expressions, simply recurse on their operands.
2247 Manual tail recursion for unary expressions.
2248 Other non-expressions need not be processed. */
2249 if (cl == tcc_unary)
2251 x = TREE_OPERAND (x, 0);
2252 writer = 0;
2253 goto restart;
2255 else if (IS_EXPR_CODE_CLASS (cl))
2257 int lp;
2258 int max = TREE_OPERAND_LENGTH (x);
2259 for (lp = 0; lp < max; lp++)
2261 tmp_before = tmp_nosp = 0;
2262 verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
2263 merge_tlist (&tmp_nosp, tmp_before, 0);
2264 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2267 return;
2271 static constexpr size_t verify_sequence_points_limit = 1024;
2273 /* Called from verify_sequence_points via walk_tree. */
2275 static tree
2276 verify_tree_lim_r (tree *tp, int *walk_subtrees, void *data)
2278 if (++*((size_t *) data) > verify_sequence_points_limit)
2279 return integer_zero_node;
2281 if (TYPE_P (*tp))
2282 *walk_subtrees = 0;
2284 return NULL_TREE;
2287 /* Try to warn for undefined behavior in EXPR due to missing sequence
2288 points. */
2290 void
2291 verify_sequence_points (tree expr)
2293 tlist *before_sp = nullptr, *after_sp = nullptr;
2295 /* verify_tree is highly recursive, and merge_tlist is O(n^2),
2296 so we return early if the expression is too big. */
2297 size_t n = 0;
2298 if (walk_tree (&expr, verify_tree_lim_r, &n, nullptr))
2299 return;
2301 warned_ids = nullptr;
2302 save_expr_cache = nullptr;
2303 if (!tlist_firstobj)
2305 gcc_obstack_init (&tlist_obstack);
2306 tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
2309 verify_tree (expr, &before_sp, &after_sp, NULL_TREE);
2310 warn_for_collisions (after_sp);
2311 obstack_free (&tlist_obstack, tlist_firstobj);
2314 /* Validate the expression after `case' and apply default promotions. */
2316 static tree
2317 check_case_value (location_t loc, tree value)
2319 if (value == NULL_TREE)
2320 return value;
2322 if (INTEGRAL_TYPE_P (TREE_TYPE (value))
2323 && TREE_CODE (value) == INTEGER_CST)
2324 /* Promote char or short to int. */
2325 value = perform_integral_promotions (value);
2326 else if (value != error_mark_node)
2328 error_at (loc, "case label does not reduce to an integer constant");
2329 value = error_mark_node;
2332 constant_expression_warning (value);
2334 return value;
2337 /* Return an integer type with BITS bits of precision,
2338 that is unsigned if UNSIGNEDP is nonzero, otherwise signed. */
2340 tree
2341 c_common_type_for_size (unsigned int bits, int unsignedp)
2343 int i;
2345 if (bits == TYPE_PRECISION (integer_type_node))
2346 return unsignedp ? unsigned_type_node : integer_type_node;
2348 if (bits == TYPE_PRECISION (signed_char_type_node))
2349 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2351 if (bits == TYPE_PRECISION (short_integer_type_node))
2352 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2354 if (bits == TYPE_PRECISION (long_integer_type_node))
2355 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2357 if (bits == TYPE_PRECISION (long_long_integer_type_node))
2358 return (unsignedp ? long_long_unsigned_type_node
2359 : long_long_integer_type_node);
2361 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2362 if (int_n_enabled_p[i]
2363 && bits == int_n_data[i].bitsize)
2364 return (unsignedp ? int_n_trees[i].unsigned_type
2365 : int_n_trees[i].signed_type);
2367 if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2368 return (unsignedp ? widest_unsigned_literal_type_node
2369 : widest_integer_literal_type_node);
2371 for (tree t = registered_builtin_types; t; t = TREE_CHAIN (t))
2373 tree type = TREE_VALUE (t);
2374 if (TREE_CODE (type) == INTEGER_TYPE
2375 && bits == TYPE_PRECISION (type)
2376 && !!unsignedp == !!TYPE_UNSIGNED (type))
2377 return type;
2380 if (bits <= TYPE_PRECISION (intQI_type_node))
2381 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2383 if (bits <= TYPE_PRECISION (intHI_type_node))
2384 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2386 if (bits <= TYPE_PRECISION (intSI_type_node))
2387 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2389 if (bits <= TYPE_PRECISION (intDI_type_node))
2390 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2392 if (bits <= TYPE_PRECISION (widest_integer_literal_type_node))
2393 return (unsignedp ? widest_unsigned_literal_type_node
2394 : widest_integer_literal_type_node);
2396 return NULL_TREE;
2399 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2400 that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2401 and saturating if SATP is nonzero, otherwise not saturating. */
2403 tree
2404 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2405 int unsignedp, int satp)
2407 enum mode_class mclass;
2408 if (ibit == 0)
2409 mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2410 else
2411 mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2413 opt_scalar_mode opt_mode;
2414 scalar_mode mode;
2415 FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2417 mode = opt_mode.require ();
2418 if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2419 break;
2422 if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2424 sorry ("GCC cannot support operators with integer types and "
2425 "fixed-point types that have too many integral and "
2426 "fractional bits together");
2427 return NULL_TREE;
2430 return c_common_type_for_mode (mode, satp);
2433 /* Used for communication between c_common_type_for_mode and
2434 c_register_builtin_type. */
2435 tree registered_builtin_types;
2437 /* Return a data type that has machine mode MODE.
2438 If the mode is an integer,
2439 then UNSIGNEDP selects between signed and unsigned types.
2440 If the mode is a fixed-point mode,
2441 then UNSIGNEDP selects between saturating and nonsaturating types. */
2443 tree
2444 c_common_type_for_mode (machine_mode mode, int unsignedp)
2446 tree t;
2447 int i;
2449 if (mode == TYPE_MODE (integer_type_node))
2450 return unsignedp ? unsigned_type_node : integer_type_node;
2452 if (mode == TYPE_MODE (signed_char_type_node))
2453 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2455 if (mode == TYPE_MODE (short_integer_type_node))
2456 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2458 if (mode == TYPE_MODE (long_integer_type_node))
2459 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2461 if (mode == TYPE_MODE (long_long_integer_type_node))
2462 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2464 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2465 if (int_n_enabled_p[i]
2466 && mode == int_n_data[i].m)
2467 return (unsignedp ? int_n_trees[i].unsigned_type
2468 : int_n_trees[i].signed_type);
2470 if (mode == QImode)
2471 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2473 if (mode == HImode)
2474 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2476 if (mode == SImode)
2477 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2479 if (mode == DImode)
2480 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2482 #if HOST_BITS_PER_WIDE_INT >= 64
2483 if (mode == TYPE_MODE (intTI_type_node))
2484 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2485 #endif
2487 if (mode == TYPE_MODE (float_type_node))
2488 return float_type_node;
2490 if (mode == TYPE_MODE (double_type_node))
2491 return double_type_node;
2493 if (mode == TYPE_MODE (long_double_type_node))
2494 return long_double_type_node;
2496 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2497 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2498 && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2499 return FLOATN_NX_TYPE_NODE (i);
2501 if (mode == TYPE_MODE (void_type_node))
2502 return void_type_node;
2504 if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2505 || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2507 unsigned int precision
2508 = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2509 return (unsignedp
2510 ? make_unsigned_type (precision)
2511 : make_signed_type (precision));
2514 if (COMPLEX_MODE_P (mode))
2516 machine_mode inner_mode;
2517 tree inner_type;
2519 if (mode == TYPE_MODE (complex_float_type_node))
2520 return complex_float_type_node;
2521 if (mode == TYPE_MODE (complex_double_type_node))
2522 return complex_double_type_node;
2523 if (mode == TYPE_MODE (complex_long_double_type_node))
2524 return complex_long_double_type_node;
2526 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2527 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2528 && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2529 return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2531 if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2532 return complex_integer_type_node;
2534 inner_mode = GET_MODE_INNER (mode);
2535 inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2536 if (inner_type != NULL_TREE)
2537 return build_complex_type (inner_type);
2539 else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
2540 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2542 unsigned int elem_bits = vector_element_size (GET_MODE_PRECISION (mode),
2543 GET_MODE_NUNITS (mode));
2544 tree bool_type = build_nonstandard_boolean_type (elem_bits);
2545 return build_vector_type_for_mode (bool_type, mode);
2547 else if (VECTOR_MODE_P (mode)
2548 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2550 machine_mode inner_mode = GET_MODE_INNER (mode);
2551 tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2552 if (inner_type != NULL_TREE)
2553 return build_vector_type_for_mode (inner_type, mode);
2556 if (dfloat32_type_node != NULL_TREE
2557 && mode == TYPE_MODE (dfloat32_type_node))
2558 return dfloat32_type_node;
2559 if (dfloat64_type_node != NULL_TREE
2560 && mode == TYPE_MODE (dfloat64_type_node))
2561 return dfloat64_type_node;
2562 if (dfloat128_type_node != NULL_TREE
2563 && mode == TYPE_MODE (dfloat128_type_node))
2564 return dfloat128_type_node;
2566 if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2568 if (mode == TYPE_MODE (short_fract_type_node))
2569 return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2570 if (mode == TYPE_MODE (fract_type_node))
2571 return unsignedp ? sat_fract_type_node : fract_type_node;
2572 if (mode == TYPE_MODE (long_fract_type_node))
2573 return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2574 if (mode == TYPE_MODE (long_long_fract_type_node))
2575 return unsignedp ? sat_long_long_fract_type_node
2576 : long_long_fract_type_node;
2578 if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2579 return unsignedp ? sat_unsigned_short_fract_type_node
2580 : unsigned_short_fract_type_node;
2581 if (mode == TYPE_MODE (unsigned_fract_type_node))
2582 return unsignedp ? sat_unsigned_fract_type_node
2583 : unsigned_fract_type_node;
2584 if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2585 return unsignedp ? sat_unsigned_long_fract_type_node
2586 : unsigned_long_fract_type_node;
2587 if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2588 return unsignedp ? sat_unsigned_long_long_fract_type_node
2589 : unsigned_long_long_fract_type_node;
2591 if (mode == TYPE_MODE (short_accum_type_node))
2592 return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2593 if (mode == TYPE_MODE (accum_type_node))
2594 return unsignedp ? sat_accum_type_node : accum_type_node;
2595 if (mode == TYPE_MODE (long_accum_type_node))
2596 return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2597 if (mode == TYPE_MODE (long_long_accum_type_node))
2598 return unsignedp ? sat_long_long_accum_type_node
2599 : long_long_accum_type_node;
2601 if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2602 return unsignedp ? sat_unsigned_short_accum_type_node
2603 : unsigned_short_accum_type_node;
2604 if (mode == TYPE_MODE (unsigned_accum_type_node))
2605 return unsignedp ? sat_unsigned_accum_type_node
2606 : unsigned_accum_type_node;
2607 if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2608 return unsignedp ? sat_unsigned_long_accum_type_node
2609 : unsigned_long_accum_type_node;
2610 if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2611 return unsignedp ? sat_unsigned_long_long_accum_type_node
2612 : unsigned_long_long_accum_type_node;
2614 if (mode == QQmode)
2615 return unsignedp ? sat_qq_type_node : qq_type_node;
2616 if (mode == HQmode)
2617 return unsignedp ? sat_hq_type_node : hq_type_node;
2618 if (mode == SQmode)
2619 return unsignedp ? sat_sq_type_node : sq_type_node;
2620 if (mode == DQmode)
2621 return unsignedp ? sat_dq_type_node : dq_type_node;
2622 if (mode == TQmode)
2623 return unsignedp ? sat_tq_type_node : tq_type_node;
2625 if (mode == UQQmode)
2626 return unsignedp ? sat_uqq_type_node : uqq_type_node;
2627 if (mode == UHQmode)
2628 return unsignedp ? sat_uhq_type_node : uhq_type_node;
2629 if (mode == USQmode)
2630 return unsignedp ? sat_usq_type_node : usq_type_node;
2631 if (mode == UDQmode)
2632 return unsignedp ? sat_udq_type_node : udq_type_node;
2633 if (mode == UTQmode)
2634 return unsignedp ? sat_utq_type_node : utq_type_node;
2636 if (mode == HAmode)
2637 return unsignedp ? sat_ha_type_node : ha_type_node;
2638 if (mode == SAmode)
2639 return unsignedp ? sat_sa_type_node : sa_type_node;
2640 if (mode == DAmode)
2641 return unsignedp ? sat_da_type_node : da_type_node;
2642 if (mode == TAmode)
2643 return unsignedp ? sat_ta_type_node : ta_type_node;
2645 if (mode == UHAmode)
2646 return unsignedp ? sat_uha_type_node : uha_type_node;
2647 if (mode == USAmode)
2648 return unsignedp ? sat_usa_type_node : usa_type_node;
2649 if (mode == UDAmode)
2650 return unsignedp ? sat_uda_type_node : uda_type_node;
2651 if (mode == UTAmode)
2652 return unsignedp ? sat_uta_type_node : uta_type_node;
2655 for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2657 tree type = TREE_VALUE (t);
2658 if (TYPE_MODE (type) == mode
2659 && VECTOR_TYPE_P (type) == VECTOR_MODE_P (mode)
2660 && !!unsignedp == !!TYPE_UNSIGNED (type))
2661 return type;
2663 return NULL_TREE;
2666 tree
2667 c_common_unsigned_type (tree type)
2669 return c_common_signed_or_unsigned_type (1, type);
2672 /* Return a signed type the same as TYPE in other respects. */
2674 tree
2675 c_common_signed_type (tree type)
2677 return c_common_signed_or_unsigned_type (0, type);
2680 /* Return a type the same as TYPE except unsigned or
2681 signed according to UNSIGNEDP. */
2683 tree
2684 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2686 tree type1;
2687 int i;
2689 /* This block of code emulates the behavior of the old
2690 c_common_unsigned_type. In particular, it returns
2691 long_unsigned_type_node if passed a long, even when a int would
2692 have the same size. This is necessary for warnings to work
2693 correctly in archs where sizeof(int) == sizeof(long) */
2695 type1 = TYPE_MAIN_VARIANT (type);
2696 if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2697 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2698 if (type1 == integer_type_node || type1 == unsigned_type_node)
2699 return unsignedp ? unsigned_type_node : integer_type_node;
2700 if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2701 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2702 if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2703 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2704 if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2705 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2707 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2708 if (int_n_enabled_p[i]
2709 && (type1 == int_n_trees[i].unsigned_type
2710 || type1 == int_n_trees[i].signed_type))
2711 return (unsignedp ? int_n_trees[i].unsigned_type
2712 : int_n_trees[i].signed_type);
2714 #if HOST_BITS_PER_WIDE_INT >= 64
2715 if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2716 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2717 #endif
2718 if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2719 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2720 if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2721 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2722 if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2723 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2724 if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2725 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2727 #define C_COMMON_FIXED_TYPES(NAME) \
2728 if (type1 == short_ ## NAME ## _type_node \
2729 || type1 == unsigned_short_ ## NAME ## _type_node) \
2730 return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2731 : short_ ## NAME ## _type_node; \
2732 if (type1 == NAME ## _type_node \
2733 || type1 == unsigned_ ## NAME ## _type_node) \
2734 return unsignedp ? unsigned_ ## NAME ## _type_node \
2735 : NAME ## _type_node; \
2736 if (type1 == long_ ## NAME ## _type_node \
2737 || type1 == unsigned_long_ ## NAME ## _type_node) \
2738 return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2739 : long_ ## NAME ## _type_node; \
2740 if (type1 == long_long_ ## NAME ## _type_node \
2741 || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2742 return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2743 : long_long_ ## NAME ## _type_node;
2745 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2746 if (type1 == NAME ## _type_node \
2747 || type1 == u ## NAME ## _type_node) \
2748 return unsignedp ? u ## NAME ## _type_node \
2749 : NAME ## _type_node;
2751 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2752 if (type1 == sat_ ## short_ ## NAME ## _type_node \
2753 || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2754 return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2755 : sat_ ## short_ ## NAME ## _type_node; \
2756 if (type1 == sat_ ## NAME ## _type_node \
2757 || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2758 return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2759 : sat_ ## NAME ## _type_node; \
2760 if (type1 == sat_ ## long_ ## NAME ## _type_node \
2761 || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2762 return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2763 : sat_ ## long_ ## NAME ## _type_node; \
2764 if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2765 || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2766 return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2767 : sat_ ## long_long_ ## NAME ## _type_node;
2769 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME) \
2770 if (type1 == sat_ ## NAME ## _type_node \
2771 || type1 == sat_ ## u ## NAME ## _type_node) \
2772 return unsignedp ? sat_ ## u ## NAME ## _type_node \
2773 : sat_ ## NAME ## _type_node;
2775 C_COMMON_FIXED_TYPES (fract);
2776 C_COMMON_FIXED_TYPES_SAT (fract);
2777 C_COMMON_FIXED_TYPES (accum);
2778 C_COMMON_FIXED_TYPES_SAT (accum);
2780 C_COMMON_FIXED_MODE_TYPES (qq);
2781 C_COMMON_FIXED_MODE_TYPES (hq);
2782 C_COMMON_FIXED_MODE_TYPES (sq);
2783 C_COMMON_FIXED_MODE_TYPES (dq);
2784 C_COMMON_FIXED_MODE_TYPES (tq);
2785 C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2786 C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2787 C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2788 C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2789 C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2790 C_COMMON_FIXED_MODE_TYPES (ha);
2791 C_COMMON_FIXED_MODE_TYPES (sa);
2792 C_COMMON_FIXED_MODE_TYPES (da);
2793 C_COMMON_FIXED_MODE_TYPES (ta);
2794 C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2795 C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2796 C_COMMON_FIXED_MODE_TYPES_SAT (da);
2797 C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2799 /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2800 the precision; they have precision set to match their range, but
2801 may use a wider mode to match an ABI. If we change modes, we may
2802 wind up with bad conversions. For INTEGER_TYPEs in C, must check
2803 the precision as well, so as to yield correct results for
2804 bit-field types. C++ does not have these separate bit-field
2805 types, and producing a signed or unsigned variant of an
2806 ENUMERAL_TYPE may cause other problems as well. */
2808 if (!INTEGRAL_TYPE_P (type)
2809 || TYPE_UNSIGNED (type) == unsignedp)
2810 return type;
2812 if (TREE_CODE (type) == BITINT_TYPE
2813 /* signed _BitInt(1) is invalid, avoid creating that. */
2814 && (unsignedp || TYPE_PRECISION (type) > 1))
2815 return build_bitint_type (TYPE_PRECISION (type), unsignedp);
2817 #define TYPE_OK(node) \
2818 (TYPE_MODE (type) == TYPE_MODE (node) \
2819 && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2820 if (TYPE_OK (signed_char_type_node))
2821 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2822 if (TYPE_OK (integer_type_node))
2823 return unsignedp ? unsigned_type_node : integer_type_node;
2824 if (TYPE_OK (short_integer_type_node))
2825 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2826 if (TYPE_OK (long_integer_type_node))
2827 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2828 if (TYPE_OK (long_long_integer_type_node))
2829 return (unsignedp ? long_long_unsigned_type_node
2830 : long_long_integer_type_node);
2832 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2833 if (int_n_enabled_p[i]
2834 && TYPE_MODE (type) == int_n_data[i].m
2835 && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2836 return (unsignedp ? int_n_trees[i].unsigned_type
2837 : int_n_trees[i].signed_type);
2839 #if HOST_BITS_PER_WIDE_INT >= 64
2840 if (TYPE_OK (intTI_type_node))
2841 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2842 #endif
2843 if (TYPE_OK (intDI_type_node))
2844 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2845 if (TYPE_OK (intSI_type_node))
2846 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2847 if (TYPE_OK (intHI_type_node))
2848 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2849 if (TYPE_OK (intQI_type_node))
2850 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2851 #undef TYPE_OK
2853 return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2856 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP. */
2858 tree
2859 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2861 int i;
2863 /* Extended integer types of the same width as a standard type have
2864 lesser rank, so those of the same width as int promote to int or
2865 unsigned int and are valid for printf formats expecting int or
2866 unsigned int. To avoid such special cases, avoid creating
2867 extended integer types for bit-fields if a standard integer type
2868 is available. */
2869 if (width == TYPE_PRECISION (integer_type_node))
2870 return unsignedp ? unsigned_type_node : integer_type_node;
2871 if (width == TYPE_PRECISION (signed_char_type_node))
2872 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2873 if (width == TYPE_PRECISION (short_integer_type_node))
2874 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2875 if (width == TYPE_PRECISION (long_integer_type_node))
2876 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2877 if (width == TYPE_PRECISION (long_long_integer_type_node))
2878 return (unsignedp ? long_long_unsigned_type_node
2879 : long_long_integer_type_node);
2880 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2881 if (int_n_enabled_p[i]
2882 && width == int_n_data[i].bitsize)
2883 return (unsignedp ? int_n_trees[i].unsigned_type
2884 : int_n_trees[i].signed_type);
2885 return build_nonstandard_integer_type (width, unsignedp);
2888 /* The C version of the register_builtin_type langhook. */
2890 void
2891 c_register_builtin_type (tree type, const char* name)
2893 tree decl;
2895 decl = build_decl (UNKNOWN_LOCATION,
2896 TYPE_DECL, get_identifier (name), type);
2897 DECL_ARTIFICIAL (decl) = 1;
2898 if (!TYPE_NAME (type))
2899 TYPE_NAME (type) = decl;
2900 lang_hooks.decls.pushdecl (decl);
2902 registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2905 /* Print an error message for invalid operands to arith operation
2906 CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2907 RICHLOC is a rich location for the message, containing either
2908 three separate locations for each of the operator and operands
2910 lhs op rhs
2911 ~~~ ^~ ~~~
2913 (C FE), or one location ranging over all over them
2915 lhs op rhs
2916 ~~~~^~~~~~
2918 (C++ FE). */
2920 void
2921 binary_op_error (rich_location *richloc, enum tree_code code,
2922 tree type0, tree type1)
2924 const char *opname;
2926 switch (code)
2928 case PLUS_EXPR:
2929 opname = "+"; break;
2930 case MINUS_EXPR:
2931 opname = "-"; break;
2932 case MULT_EXPR:
2933 opname = "*"; break;
2934 case MAX_EXPR:
2935 opname = "max"; break;
2936 case MIN_EXPR:
2937 opname = "min"; break;
2938 case EQ_EXPR:
2939 opname = "=="; break;
2940 case NE_EXPR:
2941 opname = "!="; break;
2942 case LE_EXPR:
2943 opname = "<="; break;
2944 case GE_EXPR:
2945 opname = ">="; break;
2946 case LT_EXPR:
2947 opname = "<"; break;
2948 case GT_EXPR:
2949 opname = ">"; break;
2950 case LSHIFT_EXPR:
2951 opname = "<<"; break;
2952 case RSHIFT_EXPR:
2953 opname = ">>"; break;
2954 case TRUNC_MOD_EXPR:
2955 case FLOOR_MOD_EXPR:
2956 opname = "%"; break;
2957 case TRUNC_DIV_EXPR:
2958 case FLOOR_DIV_EXPR:
2959 opname = "/"; break;
2960 case BIT_AND_EXPR:
2961 opname = "&"; break;
2962 case BIT_IOR_EXPR:
2963 opname = "|"; break;
2964 case TRUTH_ANDIF_EXPR:
2965 opname = "&&"; break;
2966 case TRUTH_ORIF_EXPR:
2967 opname = "||"; break;
2968 case BIT_XOR_EXPR:
2969 opname = "^"; break;
2970 default:
2971 gcc_unreachable ();
2973 pp_markup::element_quoted_type element_0 (type0, highlight_colors::lhs);
2974 pp_markup::element_quoted_type element_1 (type1, highlight_colors::rhs);
2975 error_at (richloc,
2976 "invalid operands to binary %s (have %e and %e)",
2977 opname, &element_0, &element_1);
2980 /* Given an expression as a tree, return its original type. Do this
2981 by stripping any conversion that preserves the sign and precision. */
2982 static tree
2983 expr_original_type (tree expr)
2985 STRIP_SIGN_NOPS (expr);
2986 return TREE_TYPE (expr);
2989 /* Subroutine of build_binary_op, used for comparison operations.
2990 See if the operands have both been converted from subword integer types
2991 and, if so, perhaps change them both back to their original type.
2992 This function is also responsible for converting the two operands
2993 to the proper common type for comparison.
2995 The arguments of this function are all pointers to local variables
2996 of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2997 RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2999 LOC is the location of the comparison.
3001 If this function returns non-NULL_TREE, it means that the comparison has
3002 a constant value. What this function returns is an expression for
3003 that value. */
3005 tree
3006 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
3007 tree *restype_ptr, enum tree_code *rescode_ptr)
3009 tree type;
3010 tree op0 = *op0_ptr;
3011 tree op1 = *op1_ptr;
3012 int unsignedp0, unsignedp1;
3013 int real1, real2;
3014 tree primop0, primop1;
3015 enum tree_code code = *rescode_ptr;
3017 /* Throw away any conversions to wider types
3018 already present in the operands. */
3020 primop0 = c_common_get_narrower (op0, &unsignedp0);
3021 primop1 = c_common_get_narrower (op1, &unsignedp1);
3023 /* If primopN is first sign-extended from primopN's precision to opN's
3024 precision, then zero-extended from opN's precision to
3025 *restype_ptr precision, shortenings might be invalid. */
3026 if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
3027 && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
3028 && !unsignedp0
3029 && TYPE_UNSIGNED (TREE_TYPE (op0)))
3030 primop0 = op0;
3031 if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
3032 && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
3033 && !unsignedp1
3034 && TYPE_UNSIGNED (TREE_TYPE (op1)))
3035 primop1 = op1;
3037 /* Handle the case that OP0 does not *contain* a conversion
3038 but it *requires* conversion to FINAL_TYPE. */
3040 if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
3041 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
3042 if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
3043 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
3045 /* If one of the operands must be floated, we cannot optimize. */
3046 real1 = SCALAR_FLOAT_TYPE_P (TREE_TYPE (primop0));
3047 real2 = SCALAR_FLOAT_TYPE_P (TREE_TYPE (primop1));
3049 /* If first arg is constant, swap the args (changing operation
3050 so value is preserved), for canonicalization. Don't do this if
3051 the second arg is 0. */
3053 if (TREE_CONSTANT (primop0)
3054 && !integer_zerop (primop1) && !real_zerop (primop1)
3055 && !fixed_zerop (primop1))
3057 std::swap (primop0, primop1);
3058 std::swap (op0, op1);
3059 *op0_ptr = op0;
3060 *op1_ptr = op1;
3061 std::swap (unsignedp0, unsignedp1);
3062 std::swap (real1, real2);
3064 switch (code)
3066 case LT_EXPR:
3067 code = GT_EXPR;
3068 break;
3069 case GT_EXPR:
3070 code = LT_EXPR;
3071 break;
3072 case LE_EXPR:
3073 code = GE_EXPR;
3074 break;
3075 case GE_EXPR:
3076 code = LE_EXPR;
3077 break;
3078 default:
3079 break;
3081 *rescode_ptr = code;
3084 /* If comparing an integer against a constant more bits wide,
3085 maybe we can deduce a value of 1 or 0 independent of the data.
3086 Or else truncate the constant now
3087 rather than extend the variable at run time.
3089 This is only interesting if the constant is the wider arg.
3090 Also, it is not safe if the constant is unsigned and the
3091 variable arg is signed, since in this case the variable
3092 would be sign-extended and then regarded as unsigned.
3093 Our technique fails in this case because the lowest/highest
3094 possible unsigned results don't follow naturally from the
3095 lowest/highest possible values of the variable operand.
3096 For just EQ_EXPR and NE_EXPR there is another technique that
3097 could be used: see if the constant can be faithfully represented
3098 in the other operand's type, by truncating it and reextending it
3099 and see if that preserves the constant's value. */
3101 if (!real1 && !real2
3102 && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
3103 && TREE_CODE (primop1) == INTEGER_CST
3104 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
3106 int min_gt, max_gt, min_lt, max_lt;
3107 tree maxval, minval;
3108 /* 1 if comparison is nominally unsigned. */
3109 int unsignedp = TYPE_UNSIGNED (*restype_ptr);
3110 tree val;
3112 type = c_common_signed_or_unsigned_type (unsignedp0,
3113 TREE_TYPE (primop0));
3115 maxval = TYPE_MAX_VALUE (type);
3116 minval = TYPE_MIN_VALUE (type);
3118 if (unsignedp && !unsignedp0)
3119 *restype_ptr = c_common_signed_type (*restype_ptr);
3121 if (TREE_TYPE (primop1) != *restype_ptr)
3123 /* Convert primop1 to target type, but do not introduce
3124 additional overflow. We know primop1 is an int_cst. */
3125 primop1 = force_fit_type (*restype_ptr,
3126 wi::to_wide
3127 (primop1,
3128 TYPE_PRECISION (*restype_ptr)),
3129 0, TREE_OVERFLOW (primop1));
3131 if (type != *restype_ptr)
3133 minval = convert (*restype_ptr, minval);
3134 maxval = convert (*restype_ptr, maxval);
3137 min_gt = tree_int_cst_lt (primop1, minval);
3138 max_gt = tree_int_cst_lt (primop1, maxval);
3139 min_lt = tree_int_cst_lt (minval, primop1);
3140 max_lt = tree_int_cst_lt (maxval, primop1);
3142 val = 0;
3143 /* This used to be a switch, but Genix compiler can't handle that. */
3144 if (code == NE_EXPR)
3146 if (max_lt || min_gt)
3147 val = truthvalue_true_node;
3149 else if (code == EQ_EXPR)
3151 if (max_lt || min_gt)
3152 val = truthvalue_false_node;
3154 else if (code == LT_EXPR)
3156 if (max_lt)
3157 val = truthvalue_true_node;
3158 if (!min_lt)
3159 val = truthvalue_false_node;
3161 else if (code == GT_EXPR)
3163 if (min_gt)
3164 val = truthvalue_true_node;
3165 if (!max_gt)
3166 val = truthvalue_false_node;
3168 else if (code == LE_EXPR)
3170 if (!max_gt)
3171 val = truthvalue_true_node;
3172 if (min_gt)
3173 val = truthvalue_false_node;
3175 else if (code == GE_EXPR)
3177 if (!min_lt)
3178 val = truthvalue_true_node;
3179 if (max_lt)
3180 val = truthvalue_false_node;
3183 /* If primop0 was sign-extended and unsigned comparison specd,
3184 we did a signed comparison above using the signed type bounds.
3185 But the comparison we output must be unsigned.
3187 Also, for inequalities, VAL is no good; but if the signed
3188 comparison had *any* fixed result, it follows that the
3189 unsigned comparison just tests the sign in reverse
3190 (positive values are LE, negative ones GE).
3191 So we can generate an unsigned comparison
3192 against an extreme value of the signed type. */
3194 if (unsignedp && !unsignedp0)
3196 if (val != 0)
3197 switch (code)
3199 case LT_EXPR:
3200 case GE_EXPR:
3201 primop1 = TYPE_MIN_VALUE (type);
3202 val = 0;
3203 break;
3205 case LE_EXPR:
3206 case GT_EXPR:
3207 primop1 = TYPE_MAX_VALUE (type);
3208 val = 0;
3209 break;
3211 default:
3212 break;
3214 type = c_common_unsigned_type (type);
3217 if (TREE_CODE (primop0) != INTEGER_CST
3218 /* Don't warn if it's from a (non-system) macro. */
3219 && !(from_macro_expansion_at
3220 (expansion_point_location_if_in_system_header
3221 (EXPR_LOCATION (primop0)))))
3223 if (val == truthvalue_false_node)
3224 warning_at (loc, OPT_Wtype_limits,
3225 "comparison is always false due to limited range of data type");
3226 if (val == truthvalue_true_node)
3227 warning_at (loc, OPT_Wtype_limits,
3228 "comparison is always true due to limited range of data type");
3231 if (val != 0)
3233 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3234 if (TREE_SIDE_EFFECTS (primop0))
3235 return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
3236 return val;
3239 /* Value is not predetermined, but do the comparison
3240 in the type of the operand that is not constant.
3241 TYPE is already properly set. */
3244 /* If either arg is decimal float and the other is float, find the
3245 proper common type to use for comparison. */
3246 else if (real1 && real2
3247 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3248 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
3249 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3251 /* If either arg is decimal float and the other is float, fail. */
3252 else if (real1 && real2
3253 && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3254 || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
3256 type = *restype_ptr;
3257 primop0 = op0;
3258 primop1 = op1;
3261 else if (real1 && real2
3262 && (TYPE_PRECISION (TREE_TYPE (primop0))
3263 == TYPE_PRECISION (TREE_TYPE (primop1))))
3264 type = TREE_TYPE (primop0);
3266 /* If args' natural types are both narrower than nominal type
3267 and both extend in the same manner, compare them
3268 in the type of the wider arg.
3269 Otherwise must actually extend both to the nominal
3270 common type lest different ways of extending
3271 alter the result.
3272 (eg, (short)-1 == (unsigned short)-1 should be 0.) */
3274 else if (unsignedp0 == unsignedp1 && real1 == real2
3275 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
3276 && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr)
3277 && (type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1)))
3278 != error_mark_node)
3280 type = c_common_signed_or_unsigned_type (unsignedp0
3281 || TYPE_UNSIGNED (*restype_ptr),
3282 type);
3283 /* Make sure shorter operand is extended the right way
3284 to match the longer operand. */
3285 primop0
3286 = convert (c_common_signed_or_unsigned_type (unsignedp0,
3287 TREE_TYPE (primop0)),
3288 primop0);
3289 primop1
3290 = convert (c_common_signed_or_unsigned_type (unsignedp1,
3291 TREE_TYPE (primop1)),
3292 primop1);
3294 else
3296 /* Here we must do the comparison on the nominal type
3297 using the args exactly as we received them. */
3298 type = *restype_ptr;
3299 primop0 = op0;
3300 primop1 = op1;
3302 /* We want to fold unsigned comparisons of >= and < against zero.
3303 For these, we may also issue a warning if we have a non-constant
3304 compared against zero, where the zero was spelled as "0" (rather
3305 than merely folding to it).
3306 If we have at least one constant, then op1 is constant
3307 and we may have a non-constant expression as op0. */
3308 if (!real1 && !real2 && integer_zerop (primop1)
3309 && TYPE_UNSIGNED (*restype_ptr))
3311 tree value = NULL_TREE;
3312 /* All unsigned values are >= 0, so we warn. However,
3313 if OP0 is a constant that is >= 0, the signedness of
3314 the comparison isn't an issue, so suppress the
3315 warning. */
3316 tree folded_op0 = fold_for_warn (op0);
3317 bool warn =
3318 warn_type_limits && !in_system_header_at (loc)
3319 && !(TREE_CODE (folded_op0) == INTEGER_CST
3320 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3321 folded_op0)))
3322 /* Do not warn for enumeration types. */
3323 && (TREE_CODE (expr_original_type (folded_op0)) != ENUMERAL_TYPE);
3325 switch (code)
3327 case GE_EXPR:
3328 if (warn)
3329 warning_at (loc, OPT_Wtype_limits,
3330 "comparison of unsigned expression in %<>= 0%> "
3331 "is always true");
3332 value = truthvalue_true_node;
3333 break;
3335 case LT_EXPR:
3336 if (warn)
3337 warning_at (loc, OPT_Wtype_limits,
3338 "comparison of unsigned expression in %<< 0%> "
3339 "is always false");
3340 value = truthvalue_false_node;
3341 break;
3343 default:
3344 break;
3347 if (value != NULL_TREE)
3349 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3350 if (TREE_SIDE_EFFECTS (primop0))
3351 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3352 primop0, value);
3353 return value;
3358 *op0_ptr = convert (type, primop0);
3359 *op1_ptr = convert (type, primop1);
3361 *restype_ptr = truthvalue_type_node;
3363 return NULL_TREE;
3366 /* Return a tree for the sum or difference (RESULTCODE says which)
3367 of pointer PTROP and integer INTOP. */
3369 tree
3370 pointer_int_sum (location_t loc, enum tree_code resultcode,
3371 tree ptrop, tree intop, bool complain)
3373 tree size_exp, ret;
3375 /* The result is a pointer of the same type that is being added. */
3376 tree result_type = TREE_TYPE (ptrop);
3378 if (VOID_TYPE_P (TREE_TYPE (result_type)))
3380 if (complain && warn_pointer_arith)
3381 pedwarn (loc, OPT_Wpointer_arith,
3382 "pointer of type %<void *%> used in arithmetic");
3383 else if (!complain)
3384 return error_mark_node;
3385 size_exp = integer_one_node;
3387 else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3389 if (complain && warn_pointer_arith)
3390 pedwarn (loc, OPT_Wpointer_arith,
3391 "pointer to a function used in arithmetic");
3392 else if (!complain)
3393 return error_mark_node;
3394 size_exp = integer_one_node;
3396 else if (!verify_type_context (loc, TCTX_POINTER_ARITH,
3397 TREE_TYPE (result_type)))
3398 size_exp = integer_one_node;
3399 else
3401 if (!complain && !COMPLETE_TYPE_P (TREE_TYPE (result_type)))
3402 return error_mark_node;
3403 size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3404 /* Wrap the pointer expression in a SAVE_EXPR to make sure it
3405 is evaluated first when the size expression may depend
3406 on it for VM types. */
3407 if (TREE_SIDE_EFFECTS (size_exp)
3408 && TREE_SIDE_EFFECTS (ptrop)
3409 && variably_modified_type_p (TREE_TYPE (ptrop), NULL))
3411 ptrop = save_expr (ptrop);
3412 size_exp = build2 (COMPOUND_EXPR, TREE_TYPE (intop), ptrop, size_exp);
3416 /* We are manipulating pointer values, so we don't need to warn
3417 about relying on undefined signed overflow. We disable the
3418 warning here because we use integer types so fold won't know that
3419 they are really pointers. */
3420 fold_defer_overflow_warnings ();
3422 /* If what we are about to multiply by the size of the elements
3423 contains a constant term, apply distributive law
3424 and multiply that constant term separately.
3425 This helps produce common subexpressions. */
3426 if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3427 && !TREE_CONSTANT (intop)
3428 && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3429 && TREE_CONSTANT (size_exp)
3430 /* If the constant comes from pointer subtraction,
3431 skip this optimization--it would cause an error. */
3432 && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3433 /* If the constant is unsigned, and smaller than the pointer size,
3434 then we must skip this optimization. This is because it could cause
3435 an overflow error if the constant is negative but INTOP is not. */
3436 && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (intop))
3437 || (TYPE_PRECISION (TREE_TYPE (intop))
3438 == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3440 enum tree_code subcode = resultcode;
3441 tree int_type = TREE_TYPE (intop);
3442 if (TREE_CODE (intop) == MINUS_EXPR)
3443 subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3444 /* Convert both subexpression types to the type of intop,
3445 because weird cases involving pointer arithmetic
3446 can result in a sum or difference with different type args. */
3447 ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3448 subcode, ptrop,
3449 convert (int_type, TREE_OPERAND (intop, 1)),
3450 true);
3451 intop = convert (int_type, TREE_OPERAND (intop, 0));
3454 /* Convert the integer argument to a type the same size as sizetype
3455 so the multiply won't overflow spuriously. */
3456 if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3457 || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3458 intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3459 TYPE_UNSIGNED (sizetype)), intop);
3461 /* Replace the integer argument with a suitable product by the object size.
3462 Do this multiplication as signed, then convert to the appropriate type
3463 for the pointer operation and disregard an overflow that occurred only
3464 because of the sign-extension change in the latter conversion. */
3466 tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3467 convert (TREE_TYPE (intop), size_exp));
3468 intop = convert (sizetype, t);
3469 if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3470 intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3473 /* Create the sum or difference. */
3474 if (resultcode == MINUS_EXPR)
3475 intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3477 ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3479 fold_undefer_and_ignore_overflow_warnings ();
3481 return ret;
3484 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3485 and if NON_CONST is known not to be permitted in an evaluated part
3486 of a constant expression. */
3488 tree
3489 c_wrap_maybe_const (tree expr, bool non_const)
3491 location_t loc = EXPR_LOCATION (expr);
3493 /* This should never be called for C++. */
3494 if (c_dialect_cxx ())
3495 gcc_unreachable ();
3497 /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING. */
3498 STRIP_TYPE_NOPS (expr);
3499 expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3500 C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3501 protected_set_expr_location (expr, loc);
3503 return expr;
3506 /* Return whether EXPR is a declaration whose address can never be NULL.
3507 The address of the first struct member could be NULL only if it were
3508 accessed through a NULL pointer, and such an access would be invalid.
3509 The address of a weak symbol may be null unless it has a definition. */
3511 bool
3512 decl_with_nonnull_addr_p (const_tree expr)
3514 if (!DECL_P (expr))
3515 return false;
3517 if (TREE_CODE (expr) == FIELD_DECL
3518 || TREE_CODE (expr) == PARM_DECL
3519 || TREE_CODE (expr) == LABEL_DECL)
3520 return true;
3522 if (!VAR_OR_FUNCTION_DECL_P (expr))
3523 return false;
3525 if (!DECL_WEAK (expr))
3526 /* Ordinary (non-weak) symbols have nonnull addresses. */
3527 return true;
3529 if (DECL_INITIAL (expr) && DECL_INITIAL (expr) != error_mark_node)
3530 /* Initialized weak symbols have nonnull addresses. */
3531 return true;
3533 if (DECL_EXTERNAL (expr) || !TREE_STATIC (expr))
3534 /* Uninitialized extern weak symbols and weak symbols with no
3535 allocated storage might have a null address. */
3536 return false;
3538 tree attribs = DECL_ATTRIBUTES (expr);
3539 if (lookup_attribute ("weakref", attribs))
3540 /* Weakref symbols might have a null address unless their referent
3541 is known not to. Don't bother following weakref targets here. */
3542 return false;
3544 return true;
3547 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3548 or for an `if' or `while' statement or ?..: exp. It should already
3549 have been validated to be of suitable type; otherwise, a bad
3550 diagnostic may result.
3552 The EXPR is located at LOCATION.
3554 This preparation consists of taking the ordinary
3555 representation of an expression expr and producing a valid tree
3556 boolean expression describing whether expr is nonzero. We could
3557 simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3558 but we optimize comparisons, &&, ||, and !.
3560 The resulting type should always be `truthvalue_type_node'. */
3562 tree
3563 c_common_truthvalue_conversion (location_t location, tree expr)
3565 STRIP_ANY_LOCATION_WRAPPER (expr);
3566 switch (TREE_CODE (expr))
3568 case EQ_EXPR: case NE_EXPR: case UNEQ_EXPR: case LTGT_EXPR:
3569 case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
3570 case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3571 case ORDERED_EXPR: case UNORDERED_EXPR:
3572 if (TREE_TYPE (expr) == truthvalue_type_node)
3573 return expr;
3574 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3575 TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3576 goto ret;
3578 case TRUTH_ANDIF_EXPR:
3579 case TRUTH_ORIF_EXPR:
3580 case TRUTH_AND_EXPR:
3581 case TRUTH_OR_EXPR:
3582 case TRUTH_XOR_EXPR:
3583 if (TREE_TYPE (expr) == truthvalue_type_node)
3584 return expr;
3585 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3586 c_common_truthvalue_conversion (location,
3587 TREE_OPERAND (expr, 0)),
3588 c_common_truthvalue_conversion (location,
3589 TREE_OPERAND (expr, 1)));
3590 goto ret;
3592 case TRUTH_NOT_EXPR:
3593 if (TREE_TYPE (expr) == truthvalue_type_node)
3594 return expr;
3595 expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3596 c_common_truthvalue_conversion (location,
3597 TREE_OPERAND (expr, 0)));
3598 goto ret;
3600 case ERROR_MARK:
3601 return expr;
3603 case INTEGER_CST:
3604 if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3605 && !integer_zerop (expr)
3606 && !integer_onep (expr))
3607 warning_at (location, OPT_Wint_in_bool_context,
3608 "enum constant in boolean context");
3609 return integer_zerop (expr) ? truthvalue_false_node
3610 : truthvalue_true_node;
3612 case REAL_CST:
3613 return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3614 ? truthvalue_true_node
3615 : truthvalue_false_node;
3617 case FIXED_CST:
3618 return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3619 &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3620 ? truthvalue_true_node
3621 : truthvalue_false_node;
3623 case FUNCTION_DECL:
3624 expr = build_unary_op (location, ADDR_EXPR, expr, false);
3625 /* Fall through. */
3627 case ADDR_EXPR:
3629 tree inner = TREE_OPERAND (expr, 0);
3630 if (decl_with_nonnull_addr_p (inner)
3631 /* Check both EXPR and INNER for suppression. */
3632 && !warning_suppressed_p (expr, OPT_Waddress)
3633 && !warning_suppressed_p (inner, OPT_Waddress))
3635 /* Common Ada programmer's mistake. */
3636 warning_at (location,
3637 OPT_Waddress,
3638 "the address of %qD will always evaluate as %<true%>",
3639 inner);
3640 suppress_warning (inner, OPT_Waddress);
3641 return truthvalue_true_node;
3643 break;
3646 case COMPLEX_EXPR:
3647 expr = build_binary_op (EXPR_LOCATION (expr),
3648 (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3649 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3650 c_common_truthvalue_conversion (location,
3651 TREE_OPERAND (expr, 0)),
3652 c_common_truthvalue_conversion (location,
3653 TREE_OPERAND (expr, 1)),
3654 false);
3655 goto ret;
3657 case NEGATE_EXPR:
3658 case ABS_EXPR:
3659 case ABSU_EXPR:
3660 case FLOAT_EXPR:
3661 case EXCESS_PRECISION_EXPR:
3662 /* These don't change whether an object is nonzero or zero. */
3663 return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3665 case LROTATE_EXPR:
3666 case RROTATE_EXPR:
3667 /* These don't change whether an object is zero or nonzero, but
3668 we can't ignore them if their second arg has side-effects. */
3669 if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3671 expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3672 TREE_OPERAND (expr, 1),
3673 c_common_truthvalue_conversion
3674 (location, TREE_OPERAND (expr, 0)));
3675 goto ret;
3677 else
3678 return c_common_truthvalue_conversion (location,
3679 TREE_OPERAND (expr, 0));
3681 case MULT_EXPR:
3682 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3683 "%<*%> in boolean context, suggest %<&&%> instead");
3684 break;
3686 case LSHIFT_EXPR:
3687 /* We will only warn on signed shifts here, because the majority of
3688 false positive warnings happen in code where unsigned arithmetic
3689 was used in anticipation of a possible overflow.
3690 Furthermore, if we see an unsigned type here we know that the
3691 result of the shift is not subject to integer promotion rules. */
3692 if ((TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3693 || TREE_CODE (TREE_TYPE (expr)) == BITINT_TYPE)
3694 && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3695 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3696 "%<<<%> in boolean context, did you mean %<<%>?");
3697 break;
3699 case COND_EXPR:
3700 if (warn_int_in_bool_context
3701 && !from_macro_definition_at (EXPR_LOCATION (expr)))
3703 tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3704 tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3705 if (TREE_CODE (val1) == INTEGER_CST
3706 && TREE_CODE (val2) == INTEGER_CST
3707 && !integer_zerop (val1)
3708 && !integer_zerop (val2)
3709 && (!integer_onep (val1)
3710 || !integer_onep (val2)))
3711 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3712 "%<?:%> using integer constants in boolean context, "
3713 "the expression will always evaluate to %<true%>");
3714 else if ((TREE_CODE (val1) == INTEGER_CST
3715 && !integer_zerop (val1)
3716 && !integer_onep (val1))
3717 || (TREE_CODE (val2) == INTEGER_CST
3718 && !integer_zerop (val2)
3719 && !integer_onep (val2)))
3720 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3721 "%<?:%> using integer constants in boolean context");
3723 /* Distribute the conversion into the arms of a COND_EXPR. */
3724 if (c_dialect_cxx ())
3725 /* Avoid premature folding. */
3726 break;
3727 else
3729 int w = warn_int_in_bool_context;
3730 warn_int_in_bool_context = 0;
3731 /* Folding will happen later for C. */
3732 expr = build3 (COND_EXPR, truthvalue_type_node,
3733 TREE_OPERAND (expr, 0),
3734 c_common_truthvalue_conversion (location,
3735 TREE_OPERAND (expr, 1)),
3736 c_common_truthvalue_conversion (location,
3737 TREE_OPERAND (expr, 2)));
3738 warn_int_in_bool_context = w;
3739 goto ret;
3742 CASE_CONVERT:
3744 tree totype = TREE_TYPE (expr);
3745 tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3747 if (POINTER_TYPE_P (totype)
3748 && !c_inhibit_evaluation_warnings
3749 && TREE_CODE (fromtype) == REFERENCE_TYPE)
3751 tree inner = expr;
3752 STRIP_NOPS (inner);
3754 if (DECL_P (inner))
3755 warning_at (location,
3756 OPT_Waddress,
3757 "the compiler can assume that the address of "
3758 "%qD will always evaluate to %<true%>",
3759 inner);
3762 /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3763 since that affects how `default_conversion' will behave. */
3764 if (TREE_CODE (totype) == REFERENCE_TYPE
3765 || TREE_CODE (fromtype) == REFERENCE_TYPE)
3766 break;
3767 /* Don't strip a conversion from C++0x scoped enum, since they
3768 don't implicitly convert to other types. */
3769 if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3770 && ENUM_IS_SCOPED (fromtype))
3771 break;
3772 /* If this isn't narrowing the argument, we can ignore it. */
3773 if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3775 tree op0 = TREE_OPERAND (expr, 0);
3776 if ((TREE_CODE (fromtype) == POINTER_TYPE
3777 && (TREE_CODE (totype) == INTEGER_TYPE
3778 || TREE_CODE (totype) == BITINT_TYPE))
3779 || warning_suppressed_p (expr, OPT_Waddress))
3780 /* Suppress -Waddress for casts to intptr_t, propagating
3781 any suppression from the enclosing expression to its
3782 operand. */
3783 suppress_warning (op0, OPT_Waddress);
3784 return c_common_truthvalue_conversion (location, op0);
3787 break;
3789 case MODIFY_EXPR:
3790 if (!warning_suppressed_p (expr, OPT_Wparentheses)
3791 && warn_parentheses
3792 && warning_at (location, OPT_Wparentheses,
3793 "suggest parentheses around assignment used as "
3794 "truth value"))
3795 suppress_warning (expr, OPT_Wparentheses);
3796 break;
3798 case CONST_DECL:
3800 tree folded_expr = fold_for_warn (expr);
3801 if (folded_expr != expr)
3802 return c_common_truthvalue_conversion (location, folded_expr);
3804 break;
3806 default:
3807 break;
3810 if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3812 tree t = save_expr (expr);
3813 expr = (build_binary_op
3814 (EXPR_LOCATION (expr),
3815 (TREE_SIDE_EFFECTS (expr)
3816 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3817 c_common_truthvalue_conversion
3818 (location,
3819 build_unary_op (location, REALPART_EXPR, t, false)),
3820 c_common_truthvalue_conversion
3821 (location,
3822 build_unary_op (location, IMAGPART_EXPR, t, false)),
3823 false));
3824 goto ret;
3827 if (FIXED_POINT_TYPE_P (TREE_TYPE (expr)))
3829 tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3830 FCONST0 (TYPE_MODE
3831 (TREE_TYPE (expr))));
3832 return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3834 else
3835 return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3837 ret:
3838 protected_set_expr_location (expr, location);
3839 return expr;
3842 static void def_builtin_1 (enum built_in_function fncode,
3843 const char *name,
3844 enum built_in_class fnclass,
3845 tree fntype, tree libtype,
3846 bool both_p, bool fallback_p, bool nonansi_p,
3847 tree fnattrs, bool implicit_p);
3850 /* Apply the TYPE_QUALS to the new DECL. */
3852 void
3853 c_apply_type_quals_to_decl (int type_quals, tree decl)
3855 tree type = TREE_TYPE (decl);
3857 if (type == error_mark_node)
3858 return;
3860 if ((type_quals & TYPE_QUAL_CONST)
3861 || (type && TREE_CODE (type) == REFERENCE_TYPE))
3862 /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3863 constructor can produce constant init, so rely on cp_finish_decl to
3864 clear TREE_READONLY if the variable has non-constant init. */
3865 TREE_READONLY (decl) = 1;
3866 if (type_quals & TYPE_QUAL_VOLATILE)
3868 TREE_SIDE_EFFECTS (decl) = 1;
3869 TREE_THIS_VOLATILE (decl) = 1;
3871 if (type_quals & TYPE_QUAL_RESTRICT)
3873 while (type && TREE_CODE (type) == ARRAY_TYPE)
3874 /* Allow 'restrict' on arrays of pointers.
3875 FIXME currently we just ignore it. */
3876 type = TREE_TYPE (type);
3877 if (!type
3878 || !POINTER_TYPE_P (type)
3879 || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3880 error ("invalid use of %<restrict%>");
3884 /* Return the typed-based alias set for T, which may be an expression
3885 or a type. Return -1 if we don't do anything special. */
3887 alias_set_type
3888 c_common_get_alias_set (tree t)
3890 /* For VLAs, use the alias set of the element type rather than the
3891 default of alias set 0 for types compared structurally. */
3892 if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3894 if (TREE_CODE (t) == ARRAY_TYPE)
3895 return get_alias_set (TREE_TYPE (t));
3896 return -1;
3899 /* That's all the expressions we handle specially. */
3900 if (!TYPE_P (t))
3901 return -1;
3903 /* Unlike char, char8_t doesn't alias in C++. (In C, char8_t is not
3904 a distinct type.) */
3905 if (flag_char8_t && t == char8_type_node && c_dialect_cxx ())
3906 return -1;
3908 /* The C standard guarantees that any object may be accessed via an
3909 lvalue that has narrow character type. */
3910 if (t == char_type_node
3911 || t == signed_char_type_node
3912 || t == unsigned_char_type_node)
3913 return 0;
3915 /* The C standard specifically allows aliasing between signed and
3916 unsigned variants of the same type. We treat the signed
3917 variant as canonical. */
3918 if ((TREE_CODE (t) == INTEGER_TYPE || TREE_CODE (t) == BITINT_TYPE)
3919 && TYPE_UNSIGNED (t))
3921 tree t1 = c_common_signed_type (t);
3923 /* t1 == t can happen for boolean nodes which are always unsigned. */
3924 if (t1 != t)
3925 return get_alias_set (t1);
3928 return -1;
3931 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3932 the IS_SIZEOF parameter indicates which operator is being applied.
3933 The COMPLAIN flag controls whether we should diagnose possibly
3934 ill-formed constructs or not. LOC is the location of the SIZEOF or
3935 TYPEOF operator. If MIN_ALIGNOF, the least alignment required for
3936 a type in any context should be returned, rather than the normal
3937 alignment for that type. */
3939 tree
3940 c_sizeof_or_alignof_type (location_t loc,
3941 tree type, bool is_sizeof, bool min_alignof,
3942 int complain)
3944 const char *op_name;
3945 tree value = NULL;
3946 enum tree_code type_code = TREE_CODE (type);
3948 op_name = is_sizeof ? "sizeof" : "__alignof__";
3950 if (type_code == FUNCTION_TYPE)
3952 if (is_sizeof)
3954 if (complain && warn_pointer_arith)
3955 pedwarn (loc, OPT_Wpointer_arith,
3956 "invalid application of %<sizeof%> to a function type");
3957 else if (!complain)
3958 return error_mark_node;
3959 value = size_one_node;
3961 else
3963 if (complain)
3965 if (c_dialect_cxx ())
3966 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3967 "%<alignof%> applied to a function type");
3968 else
3969 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3970 "%<_Alignof%> applied to a function type");
3972 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3975 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3977 if (type_code == VOID_TYPE
3978 && complain && warn_pointer_arith)
3979 pedwarn (loc, OPT_Wpointer_arith,
3980 "invalid application of %qs to a void type", op_name);
3981 else if (!complain)
3982 return error_mark_node;
3983 value = size_one_node;
3985 else if (!COMPLETE_TYPE_P (type)
3986 && ((!c_dialect_cxx () && !flag_isoc2y)
3987 || is_sizeof
3988 || type_code != ARRAY_TYPE))
3990 if (complain)
3991 error_at (loc, "invalid application of %qs to incomplete type %qT",
3992 op_name, type);
3993 return error_mark_node;
3995 else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3996 && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3998 if (complain)
3999 error_at (loc, "invalid application of %qs to array type %qT of "
4000 "incomplete element type", op_name, type);
4001 return error_mark_node;
4003 else if (!verify_type_context (loc, is_sizeof ? TCTX_SIZEOF : TCTX_ALIGNOF,
4004 type, !complain))
4006 if (!complain)
4007 return error_mark_node;
4008 value = size_one_node;
4010 else
4012 if (is_sizeof)
4013 /* Convert in case a char is more than one unit. */
4014 value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
4015 size_int (TYPE_PRECISION (char_type_node)
4016 / BITS_PER_UNIT));
4017 else if (min_alignof)
4018 value = size_int (min_align_of_type (type));
4019 else
4020 value = size_int (TYPE_ALIGN_UNIT (type));
4023 /* VALUE will have the middle-end integer type sizetype.
4024 However, we should really return a value of type `size_t',
4025 which is just a typedef for an ordinary integer type. */
4026 value = fold_convert_loc (loc, size_type_node, value);
4028 return value;
4031 /* Implement the __alignof keyword: Return the minimum required
4032 alignment of EXPR, measured in bytes. For VAR_DECLs,
4033 FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
4034 from an "aligned" __attribute__ specification). LOC is the
4035 location of the ALIGNOF operator. */
4037 tree
4038 c_alignof_expr (location_t loc, tree expr)
4040 tree t;
4042 if (!verify_type_context (loc, TCTX_ALIGNOF, TREE_TYPE (expr)))
4043 t = size_one_node;
4045 else if (VAR_OR_FUNCTION_DECL_P (expr))
4046 t = size_int (DECL_ALIGN_UNIT (expr));
4048 else if (TREE_CODE (expr) == COMPONENT_REF
4049 && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
4051 error_at (loc, "%<__alignof%> applied to a bit-field");
4052 t = size_one_node;
4054 else if (TREE_CODE (expr) == COMPONENT_REF
4055 && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
4056 t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
4058 else if (INDIRECT_REF_P (expr))
4060 tree t = TREE_OPERAND (expr, 0);
4061 tree best = t;
4062 int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
4064 while (CONVERT_EXPR_P (t)
4065 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
4067 int thisalign;
4069 t = TREE_OPERAND (t, 0);
4070 thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
4071 if (thisalign > bestalign)
4072 best = t, bestalign = thisalign;
4074 return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
4076 else
4077 return c_alignof (loc, TREE_TYPE (expr));
4079 return fold_convert_loc (loc, size_type_node, t);
4082 /* Handle C and C++ default attributes. */
4084 enum built_in_attribute
4086 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
4087 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
4088 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
4089 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
4090 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
4091 #include "builtin-attrs.def"
4092 #undef DEF_ATTR_NULL_TREE
4093 #undef DEF_ATTR_INT
4094 #undef DEF_ATTR_STRING
4095 #undef DEF_ATTR_IDENT
4096 #undef DEF_ATTR_TREE_LIST
4097 ATTR_LAST
4100 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
4102 static void c_init_attributes (void);
4104 enum c_builtin_type
4106 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
4107 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
4108 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
4109 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
4110 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4111 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4112 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
4113 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4114 ARG6) NAME,
4115 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4116 ARG6, ARG7) NAME,
4117 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4118 ARG6, ARG7, ARG8) NAME,
4119 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4120 ARG6, ARG7, ARG8, ARG9) NAME,
4121 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4122 ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
4123 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4124 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
4125 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
4126 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
4127 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
4128 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4129 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4130 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4131 NAME,
4132 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4133 ARG6) NAME,
4134 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4135 ARG6, ARG7) NAME,
4136 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
4137 #include "builtin-types.def"
4138 #undef DEF_PRIMITIVE_TYPE
4139 #undef DEF_FUNCTION_TYPE_0
4140 #undef DEF_FUNCTION_TYPE_1
4141 #undef DEF_FUNCTION_TYPE_2
4142 #undef DEF_FUNCTION_TYPE_3
4143 #undef DEF_FUNCTION_TYPE_4
4144 #undef DEF_FUNCTION_TYPE_5
4145 #undef DEF_FUNCTION_TYPE_6
4146 #undef DEF_FUNCTION_TYPE_7
4147 #undef DEF_FUNCTION_TYPE_8
4148 #undef DEF_FUNCTION_TYPE_9
4149 #undef DEF_FUNCTION_TYPE_10
4150 #undef DEF_FUNCTION_TYPE_11
4151 #undef DEF_FUNCTION_TYPE_VAR_0
4152 #undef DEF_FUNCTION_TYPE_VAR_1
4153 #undef DEF_FUNCTION_TYPE_VAR_2
4154 #undef DEF_FUNCTION_TYPE_VAR_3
4155 #undef DEF_FUNCTION_TYPE_VAR_4
4156 #undef DEF_FUNCTION_TYPE_VAR_5
4157 #undef DEF_FUNCTION_TYPE_VAR_6
4158 #undef DEF_FUNCTION_TYPE_VAR_7
4159 #undef DEF_POINTER_TYPE
4160 BT_LAST
4163 typedef enum c_builtin_type builtin_type;
4165 /* A temporary array for c_common_nodes_and_builtins. Used in
4166 communication with def_fn_type. */
4167 static tree builtin_types[(int) BT_LAST + 1];
4169 /* A helper function for c_common_nodes_and_builtins. Build function type
4170 for DEF with return type RET and N arguments. If VAR is true, then the
4171 function should be variadic after those N arguments, or, if N is zero,
4172 unprototyped.
4174 Takes special care not to ICE if any of the types involved are
4175 error_mark_node, which indicates that said type is not in fact available
4176 (see builtin_type_for_size). In which case the function type as a whole
4177 should be error_mark_node. */
4179 static void
4180 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
4182 tree t;
4183 tree *args = XALLOCAVEC (tree, n);
4184 va_list list;
4185 int i;
4187 va_start (list, n);
4188 for (i = 0; i < n; ++i)
4190 builtin_type a = (builtin_type) va_arg (list, int);
4191 t = builtin_types[a];
4192 if (t == error_mark_node)
4193 goto egress;
4194 args[i] = t;
4197 t = builtin_types[ret];
4198 if (t == error_mark_node)
4199 goto egress;
4200 if (var)
4201 if (n == 0)
4202 t = build_function_type (t, NULL_TREE);
4203 else
4204 t = build_varargs_function_type_array (t, n, args);
4205 else
4206 t = build_function_type_array (t, n, args);
4208 egress:
4209 builtin_types[def] = t;
4210 va_end (list);
4213 /* Build builtin functions common to both C and C++ language
4214 frontends. */
4216 static void
4217 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
4219 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
4220 builtin_types[ENUM] = VALUE;
4221 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
4222 def_fn_type (ENUM, RETURN, 0, 0);
4223 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
4224 def_fn_type (ENUM, RETURN, 0, 1, ARG1);
4225 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
4226 def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
4227 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4228 def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
4229 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4230 def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
4231 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4232 def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4233 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4234 ARG6) \
4235 def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4236 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4237 ARG6, ARG7) \
4238 def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4239 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4240 ARG6, ARG7, ARG8) \
4241 def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4242 ARG7, ARG8);
4243 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4244 ARG6, ARG7, ARG8, ARG9) \
4245 def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4246 ARG7, ARG8, ARG9);
4247 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4248 ARG6, ARG7, ARG8, ARG9, ARG10) \
4249 def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4250 ARG7, ARG8, ARG9, ARG10);
4251 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4252 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
4253 def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4254 ARG7, ARG8, ARG9, ARG10, ARG11);
4255 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
4256 def_fn_type (ENUM, RETURN, 1, 0);
4257 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
4258 def_fn_type (ENUM, RETURN, 1, 1, ARG1);
4259 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
4260 def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
4261 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4262 def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
4263 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4264 def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
4265 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4266 def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4267 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4268 ARG6) \
4269 def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4270 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4271 ARG6, ARG7) \
4272 def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4273 #define DEF_POINTER_TYPE(ENUM, TYPE) \
4274 builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
4276 #include "builtin-types.def"
4278 #undef DEF_PRIMITIVE_TYPE
4279 #undef DEF_FUNCTION_TYPE_0
4280 #undef DEF_FUNCTION_TYPE_1
4281 #undef DEF_FUNCTION_TYPE_2
4282 #undef DEF_FUNCTION_TYPE_3
4283 #undef DEF_FUNCTION_TYPE_4
4284 #undef DEF_FUNCTION_TYPE_5
4285 #undef DEF_FUNCTION_TYPE_6
4286 #undef DEF_FUNCTION_TYPE_7
4287 #undef DEF_FUNCTION_TYPE_8
4288 #undef DEF_FUNCTION_TYPE_9
4289 #undef DEF_FUNCTION_TYPE_10
4290 #undef DEF_FUNCTION_TYPE_11
4291 #undef DEF_FUNCTION_TYPE_VAR_0
4292 #undef DEF_FUNCTION_TYPE_VAR_1
4293 #undef DEF_FUNCTION_TYPE_VAR_2
4294 #undef DEF_FUNCTION_TYPE_VAR_3
4295 #undef DEF_FUNCTION_TYPE_VAR_4
4296 #undef DEF_FUNCTION_TYPE_VAR_5
4297 #undef DEF_FUNCTION_TYPE_VAR_6
4298 #undef DEF_FUNCTION_TYPE_VAR_7
4299 #undef DEF_POINTER_TYPE
4300 builtin_types[(int) BT_LAST] = NULL_TREE;
4302 c_init_attributes ();
4304 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
4305 NONANSI_P, ATTRS, IMPLICIT, COND) \
4306 if (NAME && COND) \
4307 def_builtin_1 (ENUM, NAME, CLASS, \
4308 builtin_types[(int) TYPE], \
4309 builtin_types[(int) LIBTYPE], \
4310 BOTH_P, FALLBACK_P, NONANSI_P, \
4311 built_in_attributes[(int) ATTRS], IMPLICIT);
4312 #include "builtins.def"
4314 targetm.init_builtins ();
4316 build_common_builtin_nodes ();
4319 /* Like get_identifier, but avoid warnings about null arguments when
4320 the argument may be NULL for targets where GCC lacks stdint.h type
4321 information. */
4323 static inline tree
4324 c_get_ident (const char *id)
4326 return get_identifier (id);
4329 /* Build tree nodes and builtin functions common to both C and C++ language
4330 frontends. */
4332 void
4333 c_common_nodes_and_builtins (void)
4335 int char8_type_size;
4336 int char16_type_size;
4337 int char32_type_size;
4338 int wchar_type_size;
4339 tree array_domain_type;
4340 tree va_list_ref_type_node;
4341 tree va_list_arg_type_node;
4342 int i;
4344 build_common_tree_nodes (flag_signed_char);
4346 /* Define `int' and `char' first so that dbx will output them first. */
4347 record_builtin_type (RID_INT, NULL, integer_type_node);
4348 record_builtin_type (RID_CHAR, "char", char_type_node);
4350 /* `signed' is the same as `int'. FIXME: the declarations of "signed",
4351 "unsigned long", "long long unsigned" and "unsigned short" were in C++
4352 but not C. Are the conditionals here needed? */
4353 if (c_dialect_cxx ())
4354 record_builtin_type (RID_SIGNED, NULL, integer_type_node);
4355 record_builtin_type (RID_LONG, "long int", long_integer_type_node);
4356 record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
4357 record_builtin_type (RID_MAX, "long unsigned int",
4358 long_unsigned_type_node);
4360 for (i = 0; i < NUM_INT_N_ENTS; i ++)
4362 char name[25];
4364 sprintf (name, "__int%d", int_n_data[i].bitsize);
4365 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4366 int_n_trees[i].signed_type);
4367 sprintf (name, "__int%d__", int_n_data[i].bitsize);
4368 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4369 int_n_trees[i].signed_type);
4370 ridpointers[RID_FIRST_INT_N + i]
4371 = DECL_NAME (TYPE_NAME (int_n_trees[i].signed_type));
4373 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
4374 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4375 sprintf (name, "__int%d__ unsigned", int_n_data[i].bitsize);
4376 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4379 if (c_dialect_cxx ())
4380 record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
4381 record_builtin_type (RID_MAX, "long long int",
4382 long_long_integer_type_node);
4383 record_builtin_type (RID_MAX, "long long unsigned int",
4384 long_long_unsigned_type_node);
4385 if (c_dialect_cxx ())
4386 record_builtin_type (RID_MAX, "long long unsigned",
4387 long_long_unsigned_type_node);
4388 record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4389 record_builtin_type (RID_MAX, "short unsigned int",
4390 short_unsigned_type_node);
4391 if (c_dialect_cxx ())
4392 record_builtin_type (RID_MAX, "unsigned short",
4393 short_unsigned_type_node);
4395 /* Define both `signed char' and `unsigned char'. */
4396 record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4397 record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4399 /* These are types that c_common_type_for_size and
4400 c_common_type_for_mode use. */
4401 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4402 TYPE_DECL, NULL_TREE,
4403 intQI_type_node));
4404 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4405 TYPE_DECL, NULL_TREE,
4406 intHI_type_node));
4407 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4408 TYPE_DECL, NULL_TREE,
4409 intSI_type_node));
4410 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4411 TYPE_DECL, NULL_TREE,
4412 intDI_type_node));
4413 #if HOST_BITS_PER_WIDE_INT >= 64
4414 /* Note that this is different than the __int128 type that's part of
4415 the generic __intN support. */
4416 if (targetm.scalar_mode_supported_p (TImode))
4417 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4418 TYPE_DECL,
4419 get_identifier ("__int128_t"),
4420 intTI_type_node));
4421 #endif
4422 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4423 TYPE_DECL, NULL_TREE,
4424 unsigned_intQI_type_node));
4425 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4426 TYPE_DECL, NULL_TREE,
4427 unsigned_intHI_type_node));
4428 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4429 TYPE_DECL, NULL_TREE,
4430 unsigned_intSI_type_node));
4431 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4432 TYPE_DECL, NULL_TREE,
4433 unsigned_intDI_type_node));
4434 #if HOST_BITS_PER_WIDE_INT >= 64
4435 if (targetm.scalar_mode_supported_p (TImode))
4436 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4437 TYPE_DECL,
4438 get_identifier ("__uint128_t"),
4439 unsigned_intTI_type_node));
4440 #endif
4442 /* Create the widest literal types. */
4443 if (targetm.scalar_mode_supported_p (TImode))
4445 widest_integer_literal_type_node = intTI_type_node;
4446 widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4448 else
4450 widest_integer_literal_type_node = intDI_type_node;
4451 widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4454 signed_size_type_node = c_common_signed_type (size_type_node);
4456 pid_type_node =
4457 TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4459 record_builtin_type (RID_FLOAT, NULL, float_type_node);
4460 record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4461 record_builtin_type (RID_MAX, "long double", long_double_type_node);
4463 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4465 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4466 record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4467 FLOATN_NX_TYPE_NODE (i));
4470 /* For C, let float128t_type_node (__float128 in some backends) be the
4471 same type as float128_type_node (_Float128), for C++ let those
4472 be distinct types that mangle and behave differently. */
4473 if (c_dialect_cxx ())
4474 float128t_type_node = NULL_TREE;
4476 /* Only supported decimal floating point extension if the target
4477 actually supports underlying modes. */
4478 if (targetm.scalar_mode_supported_p (SDmode)
4479 && targetm.scalar_mode_supported_p (DDmode)
4480 && targetm.scalar_mode_supported_p (TDmode))
4482 record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4483 record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4484 record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4485 record_builtin_type (RID_DFLOAT64X, NULL, dfloat64x_type_node);
4488 if (targetm.fixed_point_supported_p ())
4490 record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4491 record_builtin_type (RID_FRACT, NULL, fract_type_node);
4492 record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4493 record_builtin_type (RID_MAX, "long long _Fract",
4494 long_long_fract_type_node);
4495 record_builtin_type (RID_MAX, "unsigned short _Fract",
4496 unsigned_short_fract_type_node);
4497 record_builtin_type (RID_MAX, "unsigned _Fract",
4498 unsigned_fract_type_node);
4499 record_builtin_type (RID_MAX, "unsigned long _Fract",
4500 unsigned_long_fract_type_node);
4501 record_builtin_type (RID_MAX, "unsigned long long _Fract",
4502 unsigned_long_long_fract_type_node);
4503 record_builtin_type (RID_MAX, "_Sat short _Fract",
4504 sat_short_fract_type_node);
4505 record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4506 record_builtin_type (RID_MAX, "_Sat long _Fract",
4507 sat_long_fract_type_node);
4508 record_builtin_type (RID_MAX, "_Sat long long _Fract",
4509 sat_long_long_fract_type_node);
4510 record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4511 sat_unsigned_short_fract_type_node);
4512 record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4513 sat_unsigned_fract_type_node);
4514 record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4515 sat_unsigned_long_fract_type_node);
4516 record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4517 sat_unsigned_long_long_fract_type_node);
4518 record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4519 record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4520 record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4521 record_builtin_type (RID_MAX, "long long _Accum",
4522 long_long_accum_type_node);
4523 record_builtin_type (RID_MAX, "unsigned short _Accum",
4524 unsigned_short_accum_type_node);
4525 record_builtin_type (RID_MAX, "unsigned _Accum",
4526 unsigned_accum_type_node);
4527 record_builtin_type (RID_MAX, "unsigned long _Accum",
4528 unsigned_long_accum_type_node);
4529 record_builtin_type (RID_MAX, "unsigned long long _Accum",
4530 unsigned_long_long_accum_type_node);
4531 record_builtin_type (RID_MAX, "_Sat short _Accum",
4532 sat_short_accum_type_node);
4533 record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4534 record_builtin_type (RID_MAX, "_Sat long _Accum",
4535 sat_long_accum_type_node);
4536 record_builtin_type (RID_MAX, "_Sat long long _Accum",
4537 sat_long_long_accum_type_node);
4538 record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4539 sat_unsigned_short_accum_type_node);
4540 record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4541 sat_unsigned_accum_type_node);
4542 record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4543 sat_unsigned_long_accum_type_node);
4544 record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4545 sat_unsigned_long_long_accum_type_node);
4549 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4550 TYPE_DECL,
4551 get_identifier ("complex int"),
4552 complex_integer_type_node));
4553 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4554 TYPE_DECL,
4555 get_identifier ("complex float"),
4556 complex_float_type_node));
4557 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4558 TYPE_DECL,
4559 get_identifier ("complex double"),
4560 complex_double_type_node));
4561 lang_hooks.decls.pushdecl
4562 (build_decl (UNKNOWN_LOCATION,
4563 TYPE_DECL, get_identifier ("complex long double"),
4564 complex_long_double_type_node));
4566 if (!c_dialect_cxx ())
4567 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4568 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4570 char buf[30];
4571 sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4572 floatn_nx_types[i].extended ? "x" : "");
4573 lang_hooks.decls.pushdecl
4574 (build_decl (UNKNOWN_LOCATION,
4575 TYPE_DECL,
4576 get_identifier (buf),
4577 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4580 /* Make fileptr_type_node a distinct void * type until
4581 FILE type is defined. Likewise for const struct tm*. */
4582 for (unsigned i = 0; i < ARRAY_SIZE (builtin_structptr_types); ++i)
4583 builtin_structptr_types[i].node
4584 = build_variant_type_copy (builtin_structptr_types[i].base);
4586 record_builtin_type (RID_VOID, NULL, void_type_node);
4588 /* Set the TYPE_NAME for any variants that were built before
4589 record_builtin_type gave names to the built-in types. */
4591 tree void_name = TYPE_NAME (void_type_node);
4592 TYPE_NAME (void_type_node) = NULL_TREE;
4593 TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4594 = void_name;
4595 TYPE_NAME (void_type_node) = void_name;
4598 /* Make a type to be the domain of a few array types
4599 whose domains don't really matter.
4600 200 is small enough that it always fits in size_t
4601 and large enough that it can hold most function names for the
4602 initializations of __FUNCTION__ and __PRETTY_FUNCTION__. */
4603 array_domain_type = build_index_type (size_int (200));
4605 /* Make a type for arrays of characters.
4606 With luck nothing will ever really depend on the length of this
4607 array type. */
4608 char_array_type_node
4609 = build_array_type (char_type_node, array_domain_type);
4611 string_type_node = build_pointer_type (char_type_node);
4612 const_string_type_node
4613 = build_pointer_type (build_qualified_type
4614 (char_type_node, TYPE_QUAL_CONST));
4616 /* This is special for C++ so functions can be overloaded. */
4617 wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4618 wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4619 wchar_type_size = TYPE_PRECISION (wchar_type_node);
4620 underlying_wchar_type_node = wchar_type_node;
4621 if (c_dialect_cxx ())
4623 if (TYPE_UNSIGNED (wchar_type_node))
4624 wchar_type_node = make_unsigned_type (wchar_type_size);
4625 else
4626 wchar_type_node = make_signed_type (wchar_type_size);
4627 record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4630 /* This is for wide string constants. */
4631 wchar_array_type_node
4632 = build_array_type (wchar_type_node, array_domain_type);
4634 /* Define 'char8_t'. */
4635 char8_type_node = get_identifier (CHAR8_TYPE);
4636 char8_type_node = TREE_TYPE (identifier_global_value (char8_type_node));
4637 char8_type_size = TYPE_PRECISION (char8_type_node);
4638 if (c_dialect_cxx ())
4640 char8_type_node = make_unsigned_type (char8_type_size);
4641 TYPE_STRING_FLAG (char8_type_node) = true;
4643 if (flag_char8_t)
4644 record_builtin_type (RID_CHAR8, "char8_t", char8_type_node);
4647 /* This is for UTF-8 string constants. */
4648 char8_array_type_node
4649 = build_array_type (char8_type_node, array_domain_type);
4651 /* Define 'char16_t'. */
4652 char16_type_node = get_identifier (CHAR16_TYPE);
4653 char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4654 char16_type_size = TYPE_PRECISION (char16_type_node);
4655 if (c_dialect_cxx ())
4657 char16_type_node = make_unsigned_type (char16_type_size);
4659 if (cxx_dialect >= cxx11)
4660 record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4663 /* This is for UTF-16 string constants. */
4664 char16_array_type_node
4665 = build_array_type (char16_type_node, array_domain_type);
4667 /* Define 'char32_t'. */
4668 char32_type_node = get_identifier (CHAR32_TYPE);
4669 char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4670 char32_type_size = TYPE_PRECISION (char32_type_node);
4671 if (c_dialect_cxx ())
4673 char32_type_node = make_unsigned_type (char32_type_size);
4675 if (cxx_dialect >= cxx11)
4676 record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4679 /* This is for UTF-32 string constants. */
4680 char32_array_type_node
4681 = build_array_type (char32_type_node, array_domain_type);
4683 if (strcmp (WINT_TYPE, "wchar_t") == 0)
4684 wint_type_node = wchar_type_node;
4685 else
4686 wint_type_node =
4687 TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4689 intmax_type_node =
4690 TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4691 uintmax_type_node =
4692 TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4694 if (SIG_ATOMIC_TYPE)
4695 sig_atomic_type_node =
4696 TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4697 if (INT8_TYPE)
4698 int8_type_node =
4699 TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4700 if (INT16_TYPE)
4701 int16_type_node =
4702 TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4703 if (INT32_TYPE)
4704 int32_type_node =
4705 TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4706 if (INT64_TYPE)
4707 int64_type_node =
4708 TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4709 if (UINT8_TYPE)
4710 uint8_type_node =
4711 TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4712 if (UINT16_TYPE)
4713 c_uint16_type_node = uint16_type_node =
4714 TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4715 if (UINT32_TYPE)
4716 c_uint32_type_node = uint32_type_node =
4717 TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4718 if (UINT64_TYPE)
4719 c_uint64_type_node = uint64_type_node =
4720 TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4721 if (INT_LEAST8_TYPE)
4722 int_least8_type_node =
4723 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4724 if (INT_LEAST16_TYPE)
4725 int_least16_type_node =
4726 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4727 if (INT_LEAST32_TYPE)
4728 int_least32_type_node =
4729 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4730 if (INT_LEAST64_TYPE)
4731 int_least64_type_node =
4732 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4733 if (UINT_LEAST8_TYPE)
4734 uint_least8_type_node =
4735 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4736 if (UINT_LEAST16_TYPE)
4737 uint_least16_type_node =
4738 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4739 if (UINT_LEAST32_TYPE)
4740 uint_least32_type_node =
4741 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4742 if (UINT_LEAST64_TYPE)
4743 uint_least64_type_node =
4744 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4745 if (INT_FAST8_TYPE)
4746 int_fast8_type_node =
4747 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4748 if (INT_FAST16_TYPE)
4749 int_fast16_type_node =
4750 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4751 if (INT_FAST32_TYPE)
4752 int_fast32_type_node =
4753 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4754 if (INT_FAST64_TYPE)
4755 int_fast64_type_node =
4756 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4757 if (UINT_FAST8_TYPE)
4758 uint_fast8_type_node =
4759 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4760 if (UINT_FAST16_TYPE)
4761 uint_fast16_type_node =
4762 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4763 if (UINT_FAST32_TYPE)
4764 uint_fast32_type_node =
4765 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4766 if (UINT_FAST64_TYPE)
4767 uint_fast64_type_node =
4768 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4769 if (INTPTR_TYPE)
4770 intptr_type_node =
4771 TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4772 if (UINTPTR_TYPE)
4773 uintptr_type_node =
4774 TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4776 default_function_type = build_function_type (integer_type_node, NULL_TREE);
4777 unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4779 lang_hooks.decls.pushdecl
4780 (build_decl (UNKNOWN_LOCATION,
4781 TYPE_DECL, get_identifier ("__builtin_va_list"),
4782 va_list_type_node));
4783 if (targetm.enum_va_list_p)
4785 int l;
4786 const char *pname;
4787 tree ptype;
4789 for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4791 lang_hooks.decls.pushdecl
4792 (build_decl (UNKNOWN_LOCATION,
4793 TYPE_DECL, get_identifier (pname),
4794 ptype));
4799 if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4801 va_list_arg_type_node = va_list_ref_type_node =
4802 build_pointer_type (TREE_TYPE (va_list_type_node));
4804 else
4806 va_list_arg_type_node = va_list_type_node;
4807 va_list_ref_type_node = build_reference_type (va_list_type_node);
4810 c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4812 main_identifier_node = get_identifier ("main");
4814 /* Create the built-in __null node. It is important that this is
4815 not shared. */
4816 null_node = make_int_cst (1, 1);
4817 TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4819 /* Create the built-in nullptr node. This part of its initialization is
4820 common to C and C++. The front ends can further adjust its definition
4821 in {c,cxx}_init_decl_processing. In particular, we aren't setting the
4822 alignment here for C++ backward ABI bug compatibility. */
4823 nullptr_type_node = make_node (NULLPTR_TYPE);
4824 TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4825 TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4826 TYPE_UNSIGNED (nullptr_type_node) = 1;
4827 TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4828 SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4829 nullptr_node = build_int_cst (nullptr_type_node, 0);
4831 /* Since builtin_types isn't gc'ed, don't export these nodes. */
4832 memset (builtin_types, 0, sizeof (builtin_types));
4835 /* The number of named compound-literals generated thus far. */
4836 static GTY(()) int compound_literal_number;
4838 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal. */
4840 void
4841 set_compound_literal_name (tree decl)
4843 char *name;
4844 ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4845 compound_literal_number);
4846 compound_literal_number++;
4847 DECL_NAME (decl) = get_identifier (name);
4850 /* build_va_arg helper function. Return a VA_ARG_EXPR with location LOC, type
4851 TYPE and operand OP. */
4853 static tree
4854 build_va_arg_1 (location_t loc, tree type, tree op)
4856 tree expr = build1 (VA_ARG_EXPR, type, op);
4857 SET_EXPR_LOCATION (expr, loc);
4858 return expr;
4861 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4862 va_arg (EXPR, TYPE) at source location LOC. */
4864 tree
4865 build_va_arg (location_t loc, tree expr, tree type)
4867 tree va_type = TREE_TYPE (expr);
4868 tree canon_va_type = (va_type == error_mark_node
4869 ? error_mark_node
4870 : targetm.canonical_va_list_type (va_type));
4872 if (va_type == error_mark_node
4873 || canon_va_type == NULL_TREE)
4875 if (canon_va_type == NULL_TREE)
4876 error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4878 /* Let's handle things neutrally, if expr:
4879 - has undeclared type, or
4880 - is not an va_list type. */
4881 return build_va_arg_1 (loc, type, error_mark_node);
4884 if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4886 /* Case 1: Not an array type. */
4888 /* Take the address, to get '&ap'. Note that &ap is not a va_list
4889 type. */
4890 c_common_mark_addressable_vec (expr);
4891 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4893 return build_va_arg_1 (loc, type, expr);
4896 /* Case 2: Array type.
4898 Background:
4900 For contrast, let's start with the simple case (case 1). If
4901 canon_va_type is not an array type, but say a char *, then when
4902 passing-by-value a va_list, the type of the va_list param decl is
4903 the same as for another va_list decl (all ap's are char *):
4905 f2_1 (char * ap)
4906 D.1815 = VA_ARG (&ap, 0B, 1);
4907 return D.1815;
4909 f2 (int i)
4910 char * ap.0;
4911 char * ap;
4912 __builtin_va_start (&ap, 0);
4913 ap.0 = ap;
4914 res = f2_1 (ap.0);
4915 __builtin_va_end (&ap);
4916 D.1812 = res;
4917 return D.1812;
4919 However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4920 va_list the type of the va_list param decl (case 2b, struct * ap) is not
4921 the same as for another va_list decl (case 2a, struct ap[1]).
4923 f2_1 (struct * ap)
4924 D.1844 = VA_ARG (ap, 0B, 0);
4925 return D.1844;
4927 f2 (int i)
4928 struct ap[1];
4929 __builtin_va_start (&ap, 0);
4930 res = f2_1 (&ap);
4931 __builtin_va_end (&ap);
4932 D.1841 = res;
4933 return D.1841;
4935 Case 2b is different because:
4936 - on the callee side, the parm decl has declared type va_list, but
4937 grokdeclarator changes the type of the parm decl to a pointer to the
4938 array elem type.
4939 - on the caller side, the pass-by-value uses &ap.
4941 We unify these two cases (case 2a: va_list is array type,
4942 case 2b: va_list is pointer to array elem type), by adding '&' for the
4943 array type case, such that we have a pointer to array elem in both
4944 cases. */
4946 if (TREE_CODE (va_type) == ARRAY_TYPE)
4948 /* Case 2a: va_list is array type. */
4950 /* Take the address, to get '&ap'. Make sure it's a pointer to array
4951 elem type. */
4952 c_common_mark_addressable_vec (expr);
4953 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4954 expr);
4956 /* Verify that &ap is still recognized as having va_list type. */
4957 tree canon_expr_type
4958 = targetm.canonical_va_list_type (TREE_TYPE (expr));
4959 gcc_assert (canon_expr_type != NULL_TREE);
4961 else
4963 /* Case 2b: va_list is pointer to array elem type. */
4964 gcc_assert (POINTER_TYPE_P (va_type));
4966 /* Comparison as in std_canonical_va_list_type. */
4967 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4968 == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4970 /* Don't take the address. We've already got '&ap'. */
4974 return build_va_arg_1 (loc, type, expr);
4978 /* Linked list of disabled built-in functions. */
4980 struct disabled_builtin
4982 const char *name;
4983 struct disabled_builtin *next;
4985 static disabled_builtin *disabled_builtins = NULL;
4987 static bool builtin_function_disabled_p (const char *);
4989 /* Disable a built-in function specified by -fno-builtin-NAME. If NAME
4990 begins with "__builtin_", give an error. */
4992 void
4993 disable_builtin_function (const char *name)
4995 if (startswith (name, "__builtin_"))
4996 error ("cannot disable built-in function %qs", name);
4997 else
4999 disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
5000 new_disabled_builtin->name = name;
5001 new_disabled_builtin->next = disabled_builtins;
5002 disabled_builtins = new_disabled_builtin;
5007 /* Return true if the built-in function NAME has been disabled, false
5008 otherwise. */
5010 static bool
5011 builtin_function_disabled_p (const char *name)
5013 disabled_builtin *p;
5014 for (p = disabled_builtins; p != NULL; p = p->next)
5016 if (strcmp (name, p->name) == 0)
5017 return true;
5019 return false;
5023 /* Worker for DEF_BUILTIN.
5024 Possibly define a builtin function with one or two names.
5025 Does not declare a non-__builtin_ function if flag_no_builtin, or if
5026 nonansi_p and flag_no_nonansi_builtin. */
5028 static void
5029 def_builtin_1 (enum built_in_function fncode,
5030 const char *name,
5031 enum built_in_class fnclass,
5032 tree fntype, tree libtype,
5033 bool both_p, bool fallback_p, bool nonansi_p,
5034 tree fnattrs, bool implicit_p)
5036 tree decl;
5037 const char *libname;
5039 if (fntype == error_mark_node)
5040 return;
5042 gcc_assert ((!both_p && !fallback_p)
5043 || startswith (name, "__builtin_"));
5045 libname = name + strlen ("__builtin_");
5046 decl = add_builtin_function (name, fntype, fncode, fnclass,
5047 (fallback_p ? libname : NULL),
5048 fnattrs);
5050 set_builtin_decl (fncode, decl, implicit_p);
5052 if (both_p
5053 && !flag_no_builtin && !builtin_function_disabled_p (libname)
5054 && !(nonansi_p && flag_no_nonansi_builtin))
5055 add_builtin_function (libname, libtype, fncode, fnclass,
5056 NULL, fnattrs);
5059 /* Nonzero if the type T promotes to int. This is (nearly) the
5060 integral promotions defined in ISO C99 6.3.1.1/2. */
5062 bool
5063 c_promoting_integer_type_p (const_tree t)
5065 switch (TREE_CODE (t))
5067 case INTEGER_TYPE:
5068 return (TYPE_MAIN_VARIANT (t) == char_type_node
5069 || TYPE_MAIN_VARIANT (t) == signed_char_type_node
5070 || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
5071 || TYPE_MAIN_VARIANT (t) == short_integer_type_node
5072 || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
5073 || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
5075 case ENUMERAL_TYPE:
5076 /* ??? Technically all enumerations not larger than an int
5077 promote to an int. But this is used along code paths
5078 that only want to notice a size change. */
5079 return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
5081 case BOOLEAN_TYPE:
5082 return true;
5084 default:
5085 return false;
5089 /* Return 1 if PARMS specifies a fixed number of parameters
5090 and none of their types is affected by default promotions. */
5092 bool
5093 self_promoting_args_p (const_tree parms)
5095 const_tree t;
5096 for (t = parms; t; t = TREE_CHAIN (t))
5098 tree type = TREE_VALUE (t);
5100 if (type == error_mark_node)
5101 continue;
5103 if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
5104 return false;
5106 if (type == NULL_TREE)
5107 return false;
5109 if (TYPE_MAIN_VARIANT (type) == float_type_node)
5110 return false;
5112 if (c_promoting_integer_type_p (type))
5113 return false;
5115 return true;
5118 /* Recursively remove any '*' or '&' operator from TYPE. */
5119 tree
5120 strip_pointer_operator (tree t)
5122 while (POINTER_TYPE_P (t))
5123 t = TREE_TYPE (t);
5124 return t;
5127 /* Recursively remove pointer or array type from TYPE. */
5128 tree
5129 strip_pointer_or_array_types (tree t)
5131 while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
5132 t = TREE_TYPE (t);
5133 return t;
5136 /* Used to compare case labels. K1 and K2 are actually tree nodes
5137 representing case labels, or NULL_TREE for a `default' label.
5138 Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
5139 K2, and 0 if K1 and K2 are equal. */
5142 case_compare (splay_tree_key k1, splay_tree_key k2)
5144 /* Consider a NULL key (such as arises with a `default' label) to be
5145 smaller than anything else. */
5146 if (!k1)
5147 return k2 ? -1 : 0;
5148 else if (!k2)
5149 return k1 ? 1 : 0;
5151 return tree_int_cst_compare ((tree) k1, (tree) k2);
5154 /* Process a case label, located at LOC, for the range LOW_VALUE
5155 ... HIGH_VALUE. If LOW_VALUE and HIGH_VALUE are both NULL_TREE
5156 then this case label is actually a `default' label. If only
5157 HIGH_VALUE is NULL_TREE, then case label was declared using the
5158 usual C/C++ syntax, rather than the GNU case range extension.
5159 CASES is a tree containing all the case ranges processed so far;
5160 COND is the condition for the switch-statement itself.
5161 Returns the CASE_LABEL_EXPR created, or ERROR_MARK_NODE if no
5162 CASE_LABEL_EXPR is created. ATTRS are the attributes to be applied
5163 to the label. */
5165 tree
5166 c_add_case_label (location_t loc, splay_tree cases, tree cond,
5167 tree low_value, tree high_value, tree attrs)
5169 tree type;
5170 tree label;
5171 tree case_label;
5172 splay_tree_node node;
5174 /* Create the LABEL_DECL itself. */
5175 label = create_artificial_label (loc);
5176 decl_attributes (&label, attrs, 0);
5178 /* If there was an error processing the switch condition, bail now
5179 before we get more confused. */
5180 if (!cond || cond == error_mark_node)
5181 goto error_out;
5183 if ((low_value && TREE_TYPE (low_value)
5184 && POINTER_TYPE_P (TREE_TYPE (low_value)))
5185 || (high_value && TREE_TYPE (high_value)
5186 && POINTER_TYPE_P (TREE_TYPE (high_value))))
5188 error_at (loc, "pointers are not permitted as case values");
5189 goto error_out;
5192 /* Case ranges are a GNU extension. */
5193 if (high_value)
5195 if (c_dialect_cxx ())
5196 pedwarn (loc, OPT_Wpedantic,
5197 "range expressions in switch statements are non-standard");
5198 else if (warn_c23_c2y_compat > 0)
5200 if (pedantic && !flag_isoc2y)
5201 pedwarn (loc, OPT_Wc23_c2y_compat,
5202 "ISO C does not support range expressions in switch "
5203 "statements before C2Y");
5204 else
5205 warning_at (loc, OPT_Wc23_c2y_compat,
5206 "ISO C does not support range expressions in switch "
5207 "statements before C2Y");
5209 else if (warn_c23_c2y_compat && pedantic && !flag_isoc2y)
5210 pedwarn (loc, OPT_Wpedantic,
5211 "ISO C does not support range expressions in switch "
5212 "statements before C2Y");
5215 type = TREE_TYPE (cond);
5216 if (low_value)
5218 low_value = check_case_value (loc, low_value);
5219 tree tem = NULL_TREE;
5220 if (high_value
5221 && !c_dialect_cxx ()
5222 && low_value != error_mark_node
5223 && !int_fits_type_p (low_value, type)
5224 && pedwarn (loc, OPT_Wpedantic,
5225 "conversion of %qE to %qT in range expression changes "
5226 "value to %qE", low_value, type,
5227 (tem = fold_convert (type, low_value))))
5228 low_value = tem;
5229 low_value = convert_and_check (loc, type, low_value);
5230 low_value = fold (low_value);
5231 if (low_value == error_mark_node)
5232 goto error_out;
5234 if (high_value)
5236 high_value = check_case_value (loc, high_value);
5237 tree tem = NULL_TREE;
5238 if (!c_dialect_cxx ()
5239 && high_value != error_mark_node
5240 && !int_fits_type_p (high_value, type)
5241 && pedwarn (loc, OPT_Wpedantic,
5242 "conversion of %qE to %qT in range expression changes "
5243 "value to %qE", high_value, type,
5244 (tem = fold_convert (type, high_value))))
5245 high_value = tem;
5246 high_value = convert_and_check (loc, type, high_value);
5247 high_value = fold (high_value);
5248 if (high_value == error_mark_node)
5249 goto error_out;
5252 if (low_value && high_value)
5254 /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
5255 really a case range, even though it was written that way.
5256 Remove the HIGH_VALUE to simplify later processing. */
5257 if (tree_int_cst_equal (low_value, high_value))
5258 high_value = NULL_TREE;
5259 else if (!tree_int_cst_lt (low_value, high_value))
5261 warning_at (loc, 0, "empty range specified");
5262 goto error_out;
5266 /* Look up the LOW_VALUE in the table of case labels we already
5267 have. */
5268 node = splay_tree_lookup (cases, (splay_tree_key) low_value);
5269 /* If there was not an exact match, check for overlapping ranges.
5270 There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
5271 that's a `default' label and the only overlap is an exact match. */
5272 if (!node && (low_value || high_value))
5274 splay_tree_node low_bound;
5275 splay_tree_node high_bound;
5277 /* Even though there wasn't an exact match, there might be an
5278 overlap between this case range and another case range.
5279 Since we've (inductively) not allowed any overlapping case
5280 ranges, we simply need to find the greatest low case label
5281 that is smaller that LOW_VALUE, and the smallest low case
5282 label that is greater than LOW_VALUE. If there is an overlap
5283 it will occur in one of these two ranges. */
5284 low_bound = splay_tree_predecessor (cases,
5285 (splay_tree_key) low_value);
5286 high_bound = splay_tree_successor (cases,
5287 (splay_tree_key) low_value);
5289 /* Check to see if the LOW_BOUND overlaps. It is smaller than
5290 the LOW_VALUE, so there is no need to check unless the
5291 LOW_BOUND is in fact itself a case range. */
5292 if (low_bound
5293 && CASE_HIGH ((tree) low_bound->value)
5294 && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
5295 low_value) >= 0)
5296 node = low_bound;
5297 /* Check to see if the HIGH_BOUND overlaps. The low end of that
5298 range is bigger than the low end of the current range, so we
5299 are only interested if the current range is a real range, and
5300 not an ordinary case label. */
5301 else if (high_bound
5302 && high_value
5303 && (tree_int_cst_compare ((tree) high_bound->key,
5304 high_value)
5305 <= 0))
5306 node = high_bound;
5308 /* If there was an overlap, issue an error. */
5309 if (node)
5311 tree duplicate = CASE_LABEL ((tree) node->value);
5313 if (high_value)
5315 error_at (loc, "duplicate (or overlapping) case value");
5316 inform (DECL_SOURCE_LOCATION (duplicate),
5317 "this is the first entry overlapping that value");
5319 else if (low_value)
5321 error_at (loc, "duplicate case value") ;
5322 inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
5324 else
5326 error_at (loc, "multiple default labels in one switch");
5327 inform (DECL_SOURCE_LOCATION (duplicate),
5328 "this is the first default label");
5330 goto error_out;
5333 /* Add a CASE_LABEL to the statement-tree. */
5334 case_label = add_stmt (build_case_label (low_value, high_value, label));
5335 /* Register this case label in the splay tree. */
5336 splay_tree_insert (cases,
5337 (splay_tree_key) low_value,
5338 (splay_tree_value) case_label);
5340 return case_label;
5342 error_out:
5343 /* Add a label so that the back-end doesn't think that the beginning of
5344 the switch is unreachable. Note that we do not add a case label, as
5345 that just leads to duplicates and thence to failure later on. */
5346 if (!cases->root)
5348 tree t = create_artificial_label (loc);
5349 add_stmt (build_stmt (loc, LABEL_EXPR, t));
5351 return error_mark_node;
5354 /* Subroutine of c_switch_covers_all_cases_p, called via
5355 splay_tree_foreach. Return 1 if it doesn't cover all the cases.
5356 ARGS[0] is initially NULL and after the first iteration is the
5357 so far highest case label. ARGS[1] is the minimum of SWITCH_COND's
5358 type. */
5360 static int
5361 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
5363 tree label = (tree) node->value;
5364 tree *args = (tree *) data;
5366 /* If there is a default case, we shouldn't have called this. */
5367 gcc_assert (CASE_LOW (label));
5369 if (args[0] == NULL_TREE)
5371 if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
5372 return 1;
5374 else if (wi::add (wi::to_widest (args[0]), 1)
5375 != wi::to_widest (CASE_LOW (label)))
5376 return 1;
5377 if (CASE_HIGH (label))
5378 args[0] = CASE_HIGH (label);
5379 else
5380 args[0] = CASE_LOW (label);
5381 return 0;
5384 /* Return true if switch with CASES and switch condition with type
5385 covers all possible values in the case labels. */
5387 bool
5388 c_switch_covers_all_cases_p (splay_tree cases, tree type)
5390 /* If there is default:, this is always the case. */
5391 splay_tree_node default_node
5392 = splay_tree_lookup (cases, (splay_tree_key) NULL);
5393 if (default_node)
5394 return true;
5396 if (!INTEGRAL_TYPE_P (type))
5397 return false;
5399 tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
5400 if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
5401 return false;
5403 /* If there are no cases at all, or if the highest case label
5404 is smaller than TYPE_MAX_VALUE, return false. */
5405 if (args[0] == NULL_TREE
5406 || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
5407 return false;
5409 return true;
5412 /* Return true if stmt can fall through. Used by block_may_fallthru
5413 default case. */
5415 bool
5416 c_block_may_fallthru (const_tree stmt)
5418 switch (TREE_CODE (stmt))
5420 case SWITCH_STMT:
5421 return (!SWITCH_STMT_ALL_CASES_P (stmt)
5422 || !SWITCH_STMT_NO_BREAK_P (stmt)
5423 || block_may_fallthru (SWITCH_STMT_BODY (stmt)));
5425 default:
5426 return true;
5430 /* Finish an expression taking the address of LABEL (an
5431 IDENTIFIER_NODE). Returns an expression for the address.
5433 LOC is the location for the expression returned. */
5435 tree
5436 finish_label_address_expr (tree label, location_t loc)
5438 tree result;
5440 pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
5442 if (label == error_mark_node)
5443 return error_mark_node;
5445 label = lookup_label (label);
5446 if (label == NULL_TREE)
5447 result = null_pointer_node;
5448 else
5450 TREE_USED (label) = 1;
5451 result = build1 (ADDR_EXPR, ptr_type_node, label);
5452 /* The current function is not necessarily uninlinable.
5453 Computed gotos are incompatible with inlining, but the value
5454 here could be used only in a diagnostic, for example. */
5455 protected_set_expr_location (result, loc);
5458 return result;
5462 /* Given a boolean expression ARG, return a tree representing an increment
5463 or decrement (as indicated by CODE) of ARG. The front end must check for
5464 invalid cases (e.g., decrement in C++). */
5465 tree
5466 boolean_increment (enum tree_code code, tree arg)
5468 tree val;
5469 tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5471 arg = stabilize_reference (arg);
5472 switch (code)
5474 case PREINCREMENT_EXPR:
5475 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5476 break;
5477 case POSTINCREMENT_EXPR:
5478 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5479 arg = save_expr (arg);
5480 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5481 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5482 break;
5483 case PREDECREMENT_EXPR:
5484 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5485 invert_truthvalue_loc (input_location, arg));
5486 break;
5487 case POSTDECREMENT_EXPR:
5488 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5489 invert_truthvalue_loc (input_location, arg));
5490 arg = save_expr (arg);
5491 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5492 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5493 break;
5494 default:
5495 gcc_unreachable ();
5497 TREE_SIDE_EFFECTS (val) = 1;
5498 return val;
5501 /* Built-in macros for stddef.h and stdint.h, that require macros
5502 defined in this file. */
5503 void
5504 c_stddef_cpp_builtins(void)
5506 builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5507 builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5508 builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5509 /* C++ has wchar_t as a builtin type, C doesn't, so if WINT_TYPE
5510 maps to wchar_t, define it to the underlying WCHAR_TYPE in C, and
5511 to wchar_t in C++, so the desired type equivalence holds. */
5512 if (!c_dialect_cxx ()
5513 && strcmp (WINT_TYPE, "wchar_t") == 0)
5514 builtin_define_with_value ("__WINT_TYPE__", WCHAR_TYPE, 0);
5515 else
5516 builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5517 builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5518 builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5519 if (flag_char8_t)
5520 builtin_define_with_value ("__CHAR8_TYPE__", CHAR8_TYPE, 0);
5521 builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5522 builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5523 if (SIG_ATOMIC_TYPE)
5524 builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5525 if (INT8_TYPE)
5526 builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5527 if (INT16_TYPE)
5528 builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5529 if (INT32_TYPE)
5530 builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5531 if (INT64_TYPE)
5532 builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5533 if (UINT8_TYPE)
5534 builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5535 if (UINT16_TYPE)
5536 builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5537 if (UINT32_TYPE)
5538 builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5539 if (UINT64_TYPE)
5540 builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5541 if (INT_LEAST8_TYPE)
5542 builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5543 if (INT_LEAST16_TYPE)
5544 builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5545 if (INT_LEAST32_TYPE)
5546 builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5547 if (INT_LEAST64_TYPE)
5548 builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5549 if (UINT_LEAST8_TYPE)
5550 builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5551 if (UINT_LEAST16_TYPE)
5552 builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5553 if (UINT_LEAST32_TYPE)
5554 builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5555 if (UINT_LEAST64_TYPE)
5556 builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5557 if (INT_FAST8_TYPE)
5558 builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5559 if (INT_FAST16_TYPE)
5560 builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5561 if (INT_FAST32_TYPE)
5562 builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5563 if (INT_FAST64_TYPE)
5564 builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5565 if (UINT_FAST8_TYPE)
5566 builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5567 if (UINT_FAST16_TYPE)
5568 builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5569 if (UINT_FAST32_TYPE)
5570 builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5571 if (UINT_FAST64_TYPE)
5572 builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5573 if (INTPTR_TYPE)
5574 builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5575 if (UINTPTR_TYPE)
5576 builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5577 /* GIMPLE FE testcases need access to the GCC internal 'sizetype'.
5578 Expose it as __SIZETYPE__. */
5579 if (flag_gimple)
5580 builtin_define_with_value ("__SIZETYPE__", SIZETYPE, 0);
5583 static void
5584 c_init_attributes (void)
5586 /* Fill in the built_in_attributes array. */
5587 #define DEF_ATTR_NULL_TREE(ENUM) \
5588 built_in_attributes[(int) ENUM] = NULL_TREE;
5589 #define DEF_ATTR_INT(ENUM, VALUE) \
5590 built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5591 #define DEF_ATTR_STRING(ENUM, VALUE) \
5592 built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5593 #define DEF_ATTR_IDENT(ENUM, STRING) \
5594 built_in_attributes[(int) ENUM] = get_identifier (STRING);
5595 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5596 built_in_attributes[(int) ENUM] \
5597 = tree_cons (built_in_attributes[(int) PURPOSE], \
5598 built_in_attributes[(int) VALUE], \
5599 built_in_attributes[(int) CHAIN]);
5600 #include "builtin-attrs.def"
5601 #undef DEF_ATTR_NULL_TREE
5602 #undef DEF_ATTR_INT
5603 #undef DEF_ATTR_IDENT
5604 #undef DEF_ATTR_TREE_LIST
5607 /* Check whether the byte alignment ALIGN is a valid user-specified
5608 alignment less than the supported maximum. If so, return ALIGN's
5609 base-2 log; if not, output an error and return -1. If OBJFILE
5610 then reject alignments greater than MAX_OFILE_ALIGNMENT when
5611 converted to bits. Otherwise, consider valid only alignments
5612 that are less than HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT.
5613 Zero is not considered a valid argument (and results in -1 on
5614 return) but it only triggers a warning when WARN_ZERO is set. */
5617 check_user_alignment (const_tree align, bool objfile, bool warn_zero)
5619 if (error_operand_p (align))
5620 return -1;
5622 if (TREE_CODE (align) != INTEGER_CST
5623 || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5625 error ("requested alignment is not an integer constant");
5626 return -1;
5629 if (integer_zerop (align))
5631 if (warn_zero)
5632 warning (OPT_Wattributes,
5633 "requested alignment %qE is not a positive power of 2",
5634 align);
5635 return -1;
5638 /* Log2 of the byte alignment ALIGN. */
5639 int log2align;
5640 if (tree_int_cst_sgn (align) == -1
5641 || (log2align = tree_log2 (align)) == -1)
5643 error ("requested alignment %qE is not a positive power of 2",
5644 align);
5645 return -1;
5648 if (objfile)
5650 unsigned maxalign = MAX_OFILE_ALIGNMENT / BITS_PER_UNIT;
5651 if (!tree_fits_uhwi_p (align) || tree_to_uhwi (align) > maxalign)
5653 error ("requested alignment %qE exceeds object file maximum %u",
5654 align, maxalign);
5655 return -1;
5659 if (log2align >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5661 error ("requested alignment %qE exceeds maximum %u",
5662 align, 1U << (HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT - 1));
5663 return -1;
5666 return log2align;
5669 /* Determine the ELF symbol visibility for DECL, which is either a
5670 variable or a function. It is an error to use this function if a
5671 definition of DECL is not available in this translation unit.
5672 Returns true if the final visibility has been determined by this
5673 function; false if the caller is free to make additional
5674 modifications. */
5676 bool
5677 c_determine_visibility (tree decl)
5679 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5681 /* If the user explicitly specified the visibility with an
5682 attribute, honor that. DECL_VISIBILITY will have been set during
5683 the processing of the attribute. We check for an explicit
5684 attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5685 to distinguish the use of an attribute from the use of a "#pragma
5686 GCC visibility push(...)"; in the latter case we still want other
5687 considerations to be able to overrule the #pragma. */
5688 if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5689 || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5690 && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5691 || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5692 return true;
5694 /* Set default visibility to whatever the user supplied with
5695 visibility_specified depending on #pragma GCC visibility. */
5696 if (!DECL_VISIBILITY_SPECIFIED (decl))
5698 if (visibility_options.inpragma
5699 || DECL_VISIBILITY (decl) != default_visibility)
5701 DECL_VISIBILITY (decl) = default_visibility;
5702 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5703 /* If visibility changed and DECL already has DECL_RTL, ensure
5704 symbol flags are updated. */
5705 if (((VAR_P (decl) && TREE_STATIC (decl))
5706 || TREE_CODE (decl) == FUNCTION_DECL)
5707 && DECL_RTL_SET_P (decl))
5708 make_decl_rtl (decl);
5711 return false;
5714 /* Data to communicate through check_function_arguments_recurse between
5715 check_function_nonnull and check_nonnull_arg. */
5717 struct nonnull_arg_ctx
5719 /* Location of the call. */
5720 location_t loc;
5721 /* The function whose arguments are being checked and its type (used
5722 for calls through function pointers). */
5723 const_tree fndecl, fntype;
5724 /* True if a warning has been issued. */
5725 bool warned_p;
5728 /* Check the argument list of a function call to CTX.FNDECL of CTX.FNTYPE
5729 for null in argument slots that are marked as requiring a non-null
5730 pointer argument. The NARGS arguments are passed in the array ARGARRAY.
5731 Return true if we have warned. */
5733 static bool
5734 check_function_nonnull (nonnull_arg_ctx &ctx, int nargs, tree *argarray)
5736 int firstarg = 0;
5737 if (TREE_CODE (ctx.fntype) == METHOD_TYPE)
5739 bool closure = false;
5740 if (ctx.fndecl)
5742 /* For certain lambda expressions the C++ front end emits calls
5743 that pass a null this pointer as an argument named __closure
5744 to the member operator() of empty function. Detect those
5745 and avoid checking them, but proceed to check the remaining
5746 arguments. */
5747 tree arg0 = DECL_ARGUMENTS (ctx.fndecl);
5748 if (tree arg0name = DECL_NAME (arg0))
5749 closure = id_equal (arg0name, "__closure");
5752 /* In calls to C++ non-static member functions check the this
5753 pointer regardless of whether the function is declared with
5754 attribute nonnull. */
5755 firstarg = 1;
5756 if (!closure)
5757 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[0],
5758 firstarg, OPT_Wnonnull);
5761 tree attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (ctx.fntype));
5762 if (attrs == NULL_TREE)
5763 return ctx.warned_p;
5765 tree a = attrs;
5766 /* See if any of the nonnull attributes has no arguments. If so,
5767 then every pointer argument is checked (in which case the check
5768 for pointer type is done in check_nonnull_arg). */
5769 if (TREE_VALUE (a) != NULL_TREE)
5771 a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5772 while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5774 if (a != NULL_TREE)
5775 for (int i = firstarg; i < nargs; i++)
5776 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5777 i + 1, OPT_Wnonnull);
5778 else
5780 /* Walk the argument list. If we encounter an argument number we
5781 should check for non-null, do it. */
5782 for (int i = firstarg; i < nargs; i++)
5784 for (a = attrs; ; a = TREE_CHAIN (a))
5786 a = lookup_attribute ("nonnull", a);
5787 if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5788 break;
5791 if (a != NULL_TREE)
5792 check_function_arguments_recurse (check_nonnull_arg, &ctx,
5793 argarray[i], i + 1,
5794 OPT_Wnonnull);
5797 return ctx.warned_p;
5800 /* Check that the Nth argument of a function call (counting backwards
5801 from the end) is a (pointer)0. The NARGS arguments are passed in the
5802 array ARGARRAY. */
5804 static void
5805 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5807 tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5809 if (attr)
5811 int len = 0;
5812 int pos = 0;
5813 tree sentinel;
5814 function_args_iterator iter;
5815 tree t;
5817 /* Skip over the named arguments. */
5818 FOREACH_FUNCTION_ARGS (fntype, t, iter)
5820 if (len == nargs)
5821 break;
5822 len++;
5825 if (TREE_VALUE (attr))
5827 tree p = TREE_VALUE (TREE_VALUE (attr));
5828 pos = TREE_INT_CST_LOW (p);
5831 /* The sentinel must be one of the varargs, i.e.
5832 in position >= the number of fixed arguments. */
5833 if ((nargs - 1 - pos) < len)
5835 warning (OPT_Wformat_,
5836 "not enough variable arguments to fit a sentinel");
5837 return;
5840 /* Validate the sentinel. */
5841 sentinel = fold_for_warn (argarray[nargs - 1 - pos]);
5842 if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5843 || !integer_zerop (sentinel))
5844 && TREE_CODE (TREE_TYPE (sentinel)) != NULLPTR_TYPE
5845 /* Although __null (in C++) is only an integer we allow it
5846 nevertheless, as we are guaranteed that it's exactly
5847 as wide as a pointer, and we don't want to force
5848 users to cast the NULL they have written there.
5849 We warn with -Wstrict-null-sentinel, though. */
5850 && (warn_strict_null_sentinel || null_node != sentinel))
5851 warning (OPT_Wformat_, "missing sentinel in function call");
5855 /* Check that the same argument isn't passed to two or more
5856 restrict-qualified formal and issue a -Wrestrict warning
5857 if it is. Return true if a warning has been issued. */
5859 static bool
5860 check_function_restrict (const_tree fndecl, const_tree fntype,
5861 int nargs, tree *unfolded_argarray)
5863 int i;
5864 tree parms = TYPE_ARG_TYPES (fntype);
5866 /* Call fold_for_warn on all of the arguments. */
5867 auto_vec<tree> argarray (nargs);
5868 for (i = 0; i < nargs; i++)
5869 argarray.quick_push (fold_for_warn (unfolded_argarray[i]));
5871 if (fndecl
5872 && TREE_CODE (fndecl) == FUNCTION_DECL)
5874 /* Avoid diagnosing calls built-ins with a zero size/bound
5875 here. They are checked in more detail elsewhere. */
5876 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
5877 && nargs == 3
5878 && TREE_CODE (argarray[2]) == INTEGER_CST
5879 && integer_zerop (argarray[2]))
5880 return false;
5882 if (DECL_ARGUMENTS (fndecl))
5883 parms = DECL_ARGUMENTS (fndecl);
5886 for (i = 0; i < nargs; i++)
5887 TREE_VISITED (argarray[i]) = 0;
5889 bool warned = false;
5891 for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5893 tree type;
5894 if (TREE_CODE (parms) == PARM_DECL)
5896 type = TREE_TYPE (parms);
5897 parms = DECL_CHAIN (parms);
5899 else
5901 type = TREE_VALUE (parms);
5902 parms = TREE_CHAIN (parms);
5904 if (POINTER_TYPE_P (type)
5905 && TYPE_RESTRICT (type)
5906 && !TYPE_READONLY (TREE_TYPE (type)))
5907 warned |= warn_for_restrict (i, argarray.address (), nargs);
5910 for (i = 0; i < nargs; i++)
5911 TREE_VISITED (argarray[i]) = 0;
5913 return warned;
5916 /* Helper for check_function_nonnull; given a list of operands which
5917 must be non-null in ARGS, determine if operand PARAM_NUM should be
5918 checked. */
5920 static bool
5921 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5923 unsigned HOST_WIDE_INT arg_num = 0;
5925 for (; args; args = TREE_CHAIN (args))
5927 bool found = get_attribute_operand (TREE_VALUE (args), &arg_num);
5929 gcc_assert (found);
5931 if (arg_num == param_num)
5932 return true;
5934 return false;
5937 /* Check that the function argument PARAM (which is operand number
5938 PARAM_NUM) is non-null. This is called by check_function_nonnull
5939 via check_function_arguments_recurse. */
5941 static void
5942 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5944 struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5946 /* Just skip checking the argument if it's not a pointer. This can
5947 happen if the "nonnull" attribute was given without an operand
5948 list (which means to check every pointer argument). */
5950 tree paramtype = TREE_TYPE (param);
5951 if (TREE_CODE (paramtype) != POINTER_TYPE
5952 && TREE_CODE (paramtype) != NULLPTR_TYPE)
5953 return;
5955 /* Diagnose the simple cases of null arguments. */
5956 if (!integer_zerop (fold_for_warn (param)))
5957 return;
5959 auto_diagnostic_group adg;
5961 const location_t loc = EXPR_LOC_OR_LOC (param, pctx->loc);
5963 if (TREE_CODE (pctx->fntype) == METHOD_TYPE)
5964 --param_num;
5966 bool warned;
5967 if (param_num == 0)
5969 warned = warning_at (loc, OPT_Wnonnull,
5970 "%qs pointer is null", "this");
5971 if (warned && pctx->fndecl)
5972 inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5973 "in a call to non-static member function %qD",
5974 pctx->fndecl);
5976 else
5978 warned = warning_at (loc, OPT_Wnonnull,
5979 "argument %u null where non-null expected",
5980 (unsigned) param_num);
5981 if (warned && pctx->fndecl)
5982 inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5983 "in a call to function %qD declared %qs",
5984 pctx->fndecl, "nonnull");
5987 if (warned)
5988 pctx->warned_p = true;
5991 /* Helper for attribute handling; fetch the operand number from
5992 the attribute argument list. */
5994 bool
5995 get_attribute_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5997 /* Verify the arg number is a small constant. */
5998 if (tree_fits_uhwi_p (arg_num_expr))
6000 *valp = tree_to_uhwi (arg_num_expr);
6001 return true;
6003 else
6004 return false;
6007 /* Arguments being collected for optimization. */
6008 typedef const char *const_char_p; /* For DEF_VEC_P. */
6009 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
6012 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
6013 options in ARGS. ATTR_P is true if this is for attribute(optimize), and
6014 false for #pragma GCC optimize. */
6016 bool
6017 parse_optimize_options (tree args, bool attr_p)
6019 bool ret = true;
6020 unsigned opt_argc;
6021 unsigned i;
6022 const char **opt_argv;
6023 struct cl_decoded_option *decoded_options;
6024 unsigned int decoded_options_count;
6025 tree ap;
6027 /* Build up argv vector. Just in case the string is stored away, use garbage
6028 collected strings. */
6029 vec_safe_truncate (optimize_args, 0);
6030 vec_safe_push (optimize_args, (const char *) NULL);
6032 for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
6034 tree value = TREE_VALUE (ap);
6036 if (TREE_CODE (value) == INTEGER_CST)
6038 char buffer[HOST_BITS_PER_LONG / 3 + 4];
6039 sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
6040 vec_safe_push (optimize_args, ggc_strdup (buffer));
6043 else if (TREE_CODE (value) == STRING_CST)
6045 /* Split string into multiple substrings. */
6046 size_t len = TREE_STRING_LENGTH (value);
6047 char *p = ASTRDUP (TREE_STRING_POINTER (value));
6048 char *end = p + len;
6049 char *comma;
6050 char *next_p = p;
6052 while (next_p != NULL)
6054 size_t len2;
6055 char *q, *r;
6057 p = next_p;
6058 comma = strchr (p, ',');
6059 if (comma)
6061 len2 = comma - p;
6062 *comma = '\0';
6063 next_p = comma+1;
6065 else
6067 len2 = end - p;
6068 next_p = NULL;
6071 /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
6072 options. */
6073 if (*p == '-' && p[1] != 'O' && p[1] != 'f')
6075 ret = false;
6076 if (attr_p)
6077 warning (OPT_Wattributes,
6078 "bad option %qs to attribute %<optimize%>", p);
6079 else
6080 warning (OPT_Wpragmas,
6081 "bad option %qs to pragma %<optimize%>", p);
6082 continue;
6085 /* Can't use GC memory here, see PR88007. */
6086 r = q = XOBNEWVEC (&opts_obstack, char, len2 + 3);
6088 if (*p != '-')
6090 *r++ = '-';
6092 /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
6093 itself is -Os, and any other switch begins with a -f. */
6094 if ((*p >= '0' && *p <= '9')
6095 || (p[0] == 's' && p[1] == '\0'))
6096 *r++ = 'O';
6097 else if (*p != 'O')
6098 *r++ = 'f';
6101 memcpy (r, p, len2);
6102 r[len2] = '\0';
6103 vec_safe_push (optimize_args, (const char *) q);
6109 opt_argc = optimize_args->length ();
6110 opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
6112 for (i = 1; i < opt_argc; i++)
6113 opt_argv[i] = (*optimize_args)[i];
6115 /* Now parse the options. */
6116 decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
6117 &decoded_options,
6118 &decoded_options_count);
6119 /* Drop non-Optimization options. */
6120 unsigned j = 1;
6121 for (i = 1; i < decoded_options_count; ++i)
6123 if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
6125 ret = false;
6126 if (attr_p)
6127 warning (OPT_Wattributes,
6128 "bad option %qs to attribute %<optimize%>",
6129 decoded_options[i].orig_option_with_args_text);
6130 else
6131 warning (OPT_Wpragmas,
6132 "bad option %qs to pragma %<optimize%>",
6133 decoded_options[i].orig_option_with_args_text);
6134 continue;
6136 if (i != j)
6137 decoded_options[j] = decoded_options[i];
6138 j++;
6140 decoded_options_count = j;
6142 /* Merge the decoded options with save_decoded_options. */
6143 unsigned save_opt_count = save_opt_decoded_options->length ();
6144 unsigned merged_decoded_options_count
6145 = save_opt_count + decoded_options_count;
6146 cl_decoded_option *merged_decoded_options
6147 = XNEWVEC (cl_decoded_option, merged_decoded_options_count);
6149 /* Note the first decoded_options is used for the program name. */
6150 for (unsigned i = 0; i < save_opt_count; ++i)
6151 merged_decoded_options[i + 1] = (*save_opt_decoded_options)[i];
6152 for (unsigned i = 1; i < decoded_options_count; ++i)
6153 merged_decoded_options[save_opt_count + i] = decoded_options[i];
6155 /* And apply them. */
6156 decode_options (&global_options, &global_options_set,
6157 merged_decoded_options, merged_decoded_options_count,
6158 input_location, global_dc, NULL);
6159 free (decoded_options);
6161 targetm.override_options_after_change();
6163 optimize_args->truncate (0);
6164 return ret;
6167 /* Check whether ATTR is a valid attribute fallthrough. */
6169 bool
6170 attribute_fallthrough_p (tree attr)
6172 if (attr == error_mark_node)
6173 return false;
6174 tree t = lookup_attribute ("", "fallthrough", attr);
6175 if (t == NULL_TREE)
6176 return false;
6177 /* It is no longer true that "this attribute shall appear at most once in
6178 each attribute-list", but we still give a warning. */
6179 if (lookup_attribute ("", "fallthrough", TREE_CHAIN (t)))
6180 warning (OPT_Wattributes, "attribute %<fallthrough%> specified multiple "
6181 "times");
6182 /* No attribute-argument-clause shall be present. */
6183 else if (TREE_VALUE (t) != NULL_TREE)
6184 warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
6185 "a parameter");
6186 /* Warn if other attributes are found. */
6187 for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
6189 tree name = get_attribute_name (t);
6190 if (!is_attribute_p ("fallthrough", name)
6191 || !is_attribute_namespace_p ("", t))
6193 if (!c_dialect_cxx () && get_attribute_namespace (t) == NULL_TREE)
6194 /* The specifications of standard attributes in C mean
6195 this is a constraint violation. */
6196 pedwarn (input_location, OPT_Wattributes, "%qE attribute ignored",
6197 get_attribute_name (t));
6198 else
6199 warning (OPT_Wattributes, "%qE attribute ignored", name);
6202 return true;
6206 /* Check for valid arguments being passed to a function with FNTYPE.
6207 There are NARGS arguments in the array ARGARRAY. LOC should be used
6208 for diagnostics. Return true if either -Wnonnull or -Wrestrict has
6209 been issued.
6211 The arguments in ARGARRAY may not have been folded yet (e.g. for C++,
6212 to preserve location wrappers); checks that require folded arguments
6213 should call fold_for_warn on them.
6215 Use the frontend-supplied COMP_TYPES when determining if
6216 one type is a subclass of another. */
6218 bool
6219 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
6220 int nargs, tree *argarray, vec<location_t> *arglocs,
6221 bool (*comp_types) (tree, tree))
6223 bool warned_p = false;
6225 /* Check for null being passed in a pointer argument that must be
6226 non-null. In C++, this includes the this pointer. We also need
6227 to do this if format checking is enabled. */
6228 if (warn_nonnull)
6230 nonnull_arg_ctx ctx = { loc, fndecl, fntype, false };
6231 warned_p = check_function_nonnull (ctx, nargs, argarray);
6234 /* Check for errors in format strings. */
6236 if (warn_format || warn_suggest_attribute_format)
6237 check_function_format (fndecl ? fndecl : fntype, TYPE_ATTRIBUTES (fntype), nargs,
6238 argarray, arglocs, comp_types);
6240 if (warn_format)
6241 check_function_sentinel (fntype, nargs, argarray);
6243 if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
6245 switch (DECL_FUNCTION_CODE (fndecl))
6247 case BUILT_IN_SPRINTF:
6248 case BUILT_IN_SPRINTF_CHK:
6249 case BUILT_IN_SNPRINTF:
6250 case BUILT_IN_SNPRINTF_CHK:
6251 /* Let the sprintf pass handle these. */
6252 return warned_p;
6254 default:
6255 break;
6259 /* check_function_restrict sets the DECL_READ_P for arguments
6260 so it must be called unconditionally. */
6261 warned_p |= check_function_restrict (fndecl, fntype, nargs, argarray);
6263 return warned_p;
6266 /* Generic argument checking recursion routine. PARAM is the argument to
6267 be checked. PARAM_NUM is the number of the argument. CALLBACK is invoked
6268 once the argument is resolved. CTX is context for the callback.
6269 OPT is the warning for which this is done. */
6270 void
6271 check_function_arguments_recurse (void (*callback)
6272 (void *, tree, unsigned HOST_WIDE_INT),
6273 void *ctx, tree param,
6274 unsigned HOST_WIDE_INT param_num,
6275 opt_code opt)
6277 if (opt != OPT_Wformat_ && warning_suppressed_p (param))
6278 return;
6280 if (CONVERT_EXPR_P (param)
6281 && (TYPE_PRECISION (TREE_TYPE (param))
6282 == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
6284 /* Strip coercion. */
6285 check_function_arguments_recurse (callback, ctx,
6286 TREE_OPERAND (param, 0), param_num,
6287 opt);
6288 return;
6291 if (TREE_CODE (param) == CALL_EXPR && CALL_EXPR_FN (param))
6293 tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
6294 tree attrs;
6295 bool found_format_arg = false;
6297 /* See if this is a call to a known internationalization function
6298 that modifies a format arg. Such a function may have multiple
6299 format_arg attributes (for example, ngettext). */
6301 for (attrs = TYPE_ATTRIBUTES (type);
6302 attrs;
6303 attrs = TREE_CHAIN (attrs))
6304 if (is_attribute_p ("format_arg", get_attribute_name (attrs)))
6306 tree inner_arg;
6307 tree format_num_expr;
6308 int format_num;
6309 int i;
6310 call_expr_arg_iterator iter;
6312 /* Extract the argument number, which was previously checked
6313 to be valid. */
6314 format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
6316 format_num = tree_to_uhwi (format_num_expr);
6318 for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
6319 inner_arg != NULL_TREE;
6320 inner_arg = next_call_expr_arg (&iter), i++)
6321 if (i == format_num)
6323 check_function_arguments_recurse (callback, ctx,
6324 inner_arg, param_num,
6325 opt);
6326 found_format_arg = true;
6327 break;
6331 /* If we found a format_arg attribute and did a recursive check,
6332 we are done with checking this argument. Otherwise, we continue
6333 and this will be considered a non-literal. */
6334 if (found_format_arg)
6335 return;
6338 if (TREE_CODE (param) == COND_EXPR)
6340 /* Simplify to avoid warning for an impossible case. */
6341 param = fold_for_warn (param);
6342 if (TREE_CODE (param) == COND_EXPR)
6344 /* Check both halves of the conditional expression. */
6345 check_function_arguments_recurse (callback, ctx,
6346 TREE_OPERAND (param, 1),
6347 param_num, opt);
6348 check_function_arguments_recurse (callback, ctx,
6349 TREE_OPERAND (param, 2),
6350 param_num, opt);
6351 return;
6355 (*callback) (ctx, param, param_num);
6358 /* Checks for a builtin function FNDECL that the number of arguments
6359 NARGS against the required number REQUIRED and issues an error if
6360 there is a mismatch. Returns true if the number of arguments is
6361 correct, otherwise false. LOC is the location of FNDECL. */
6363 static bool
6364 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
6365 int required)
6367 if (nargs < required)
6369 error_at (loc, "too few arguments to function %qE", fndecl);
6370 return false;
6372 else if (nargs > required)
6374 error_at (loc, "too many arguments to function %qE", fndecl);
6375 return false;
6377 return true;
6380 /* Helper macro for check_builtin_function_arguments. */
6381 #define ARG_LOCATION(N) \
6382 (arg_loc.is_empty () \
6383 ? EXPR_LOC_OR_LOC (args[(N)], input_location) \
6384 : expansion_point_location (arg_loc[(N)]))
6386 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
6387 Returns false if there was an error, otherwise true. LOC is the
6388 location of the function; ARG_LOC is a vector of locations of the
6389 arguments. If FNDECL is the result of resolving an overloaded
6390 target built-in, ORIG_FNDECL is the original function decl,
6391 otherwise it is null. */
6393 bool
6394 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
6395 tree fndecl, tree orig_fndecl,
6396 int nargs, tree *args)
6398 if (!fndecl_built_in_p (fndecl))
6399 return true;
6401 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6402 return (!targetm.check_builtin_call
6403 || targetm.check_builtin_call (loc, arg_loc, fndecl,
6404 orig_fndecl, nargs, args));
6406 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_FRONTEND)
6407 return true;
6409 gcc_assert (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL);
6410 switch (DECL_FUNCTION_CODE (fndecl))
6412 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
6413 if (!tree_fits_uhwi_p (args[2]))
6415 error_at (ARG_LOCATION (2),
6416 "third argument to function %qE must be a constant integer",
6417 fndecl);
6418 return false;
6420 /* fall through */
6422 case BUILT_IN_ALLOCA_WITH_ALIGN:
6424 /* Get the requested alignment (in bits) if it's a constant
6425 integer expression. */
6426 unsigned HOST_WIDE_INT align
6427 = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
6429 /* Determine if the requested alignment is a power of 2. */
6430 if ((align & (align - 1)))
6431 align = 0;
6433 /* The maximum alignment in bits corresponding to the same
6434 maximum in bytes enforced in check_user_alignment(). */
6435 unsigned maxalign = (UINT_MAX >> 1) + 1;
6437 /* Reject invalid alignments. */
6438 if (align < BITS_PER_UNIT || maxalign < align)
6440 error_at (ARG_LOCATION (1),
6441 "second argument to function %qE must be a constant "
6442 "integer power of 2 between %qi and %qu bits",
6443 fndecl, BITS_PER_UNIT, maxalign);
6444 return false;
6446 return true;
6449 case BUILT_IN_CONSTANT_P:
6450 return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
6452 case BUILT_IN_ISFINITE:
6453 case BUILT_IN_ISINF:
6454 case BUILT_IN_ISINF_SIGN:
6455 case BUILT_IN_ISNAN:
6456 case BUILT_IN_ISNORMAL:
6457 case BUILT_IN_ISSIGNALING:
6458 case BUILT_IN_SIGNBIT:
6459 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6461 if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
6463 error_at (ARG_LOCATION (0), "non-floating-point argument in "
6464 "call to function %qE", fndecl);
6465 return false;
6467 return true;
6469 return false;
6471 case BUILT_IN_ISGREATER:
6472 case BUILT_IN_ISGREATEREQUAL:
6473 case BUILT_IN_ISLESS:
6474 case BUILT_IN_ISLESSEQUAL:
6475 case BUILT_IN_ISLESSGREATER:
6476 case BUILT_IN_ISUNORDERED:
6477 case BUILT_IN_ISEQSIG:
6478 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
6480 enum tree_code code0, code1;
6481 code0 = TREE_CODE (TREE_TYPE (args[0]));
6482 code1 = TREE_CODE (TREE_TYPE (args[1]));
6483 if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
6484 || (code0 == REAL_TYPE
6485 && (code1 == INTEGER_TYPE || code1 == BITINT_TYPE))
6486 || ((code0 == INTEGER_TYPE || code0 == BITINT_TYPE)
6487 && code1 == REAL_TYPE)))
6489 error_at (loc, "non-floating-point arguments in call to "
6490 "function %qE", fndecl);
6491 return false;
6493 return true;
6495 return false;
6497 case BUILT_IN_FPCLASSIFY:
6498 if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
6500 for (unsigned int i = 0; i < 5; i++)
6501 if (TREE_CODE (args[i]) != INTEGER_CST)
6503 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
6504 "call to function %qE", i + 1, fndecl);
6505 return false;
6508 if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
6510 error_at (ARG_LOCATION (5), "non-floating-point argument in "
6511 "call to function %qE", fndecl);
6512 return false;
6514 return true;
6516 return false;
6518 case BUILT_IN_ASSUME_ALIGNED:
6519 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
6521 if (nargs >= 3
6522 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE
6523 && TREE_CODE (TREE_TYPE (args[2])) != BITINT_TYPE)
6525 error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
6526 "function %qE", fndecl);
6527 return false;
6529 return true;
6531 return false;
6533 case BUILT_IN_ADD_OVERFLOW:
6534 case BUILT_IN_SUB_OVERFLOW:
6535 case BUILT_IN_MUL_OVERFLOW:
6536 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6538 unsigned i;
6539 for (i = 0; i < 2; i++)
6540 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6542 error_at (ARG_LOCATION (i), "argument %u in call to function "
6543 "%qE does not have integral type", i + 1, fndecl);
6544 return false;
6546 if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
6547 || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
6549 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6550 "does not have pointer to integral type", fndecl);
6551 return false;
6553 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
6555 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6556 "has pointer to enumerated type", fndecl);
6557 return false;
6559 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
6561 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6562 "has pointer to boolean type", fndecl);
6563 return false;
6565 else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[2]))))
6567 error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6568 "has pointer to %qs type (%qT)", 3, fndecl, "const",
6569 TREE_TYPE (args[2]));
6570 return false;
6572 else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[2]))))
6574 error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6575 "has pointer to %qs type (%qT)", 3, fndecl,
6576 "_Atomic", TREE_TYPE (args[2]));
6577 return false;
6579 return true;
6581 return false;
6583 case BUILT_IN_ADD_OVERFLOW_P:
6584 case BUILT_IN_SUB_OVERFLOW_P:
6585 case BUILT_IN_MUL_OVERFLOW_P:
6586 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6588 unsigned i;
6589 for (i = 0; i < 3; i++)
6590 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6592 error_at (ARG_LOCATION (i), "argument %u in call to function "
6593 "%qE does not have integral type", i + 1, fndecl);
6594 return false;
6596 if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
6598 error_at (ARG_LOCATION (2), "argument %u in call to function "
6599 "%qE has enumerated type", 3, fndecl);
6600 return false;
6602 else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
6604 error_at (ARG_LOCATION (2), "argument %u in call to function "
6605 "%qE has boolean type", 3, fndecl);
6606 return false;
6608 return true;
6610 return false;
6612 case BUILT_IN_CLEAR_PADDING:
6613 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6615 if (!POINTER_TYPE_P (TREE_TYPE (args[0])))
6617 error_at (ARG_LOCATION (0), "argument %u in call to function "
6618 "%qE does not have pointer type", 1, fndecl);
6619 return false;
6621 else if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (args[0]))))
6623 error_at (ARG_LOCATION (0), "argument %u in call to function "
6624 "%qE points to incomplete type", 1, fndecl);
6625 return false;
6627 else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[0]))))
6629 error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6630 "has pointer to %qs type (%qT)", 1, fndecl, "const",
6631 TREE_TYPE (args[0]));
6632 return false;
6634 else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[0]))))
6636 error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6637 "has pointer to %qs type (%qT)", 1, fndecl,
6638 "_Atomic", TREE_TYPE (args[0]));
6639 return false;
6641 return true;
6643 return false;
6645 case BUILT_IN_CLZG:
6646 case BUILT_IN_CTZG:
6647 case BUILT_IN_CLRSBG:
6648 case BUILT_IN_FFSG:
6649 case BUILT_IN_PARITYG:
6650 case BUILT_IN_POPCOUNTG:
6651 if (nargs == 2
6652 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CLZG
6653 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CTZG))
6655 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[1])))
6657 error_at (ARG_LOCATION (1), "argument %u in call to function "
6658 "%qE does not have integral type", 2, fndecl);
6659 return false;
6661 if ((TYPE_PRECISION (TREE_TYPE (args[1]))
6662 > TYPE_PRECISION (integer_type_node))
6663 || (TYPE_PRECISION (TREE_TYPE (args[1]))
6664 == TYPE_PRECISION (integer_type_node)
6665 && TYPE_UNSIGNED (TREE_TYPE (args[1]))))
6667 error_at (ARG_LOCATION (1), "argument %u in call to function "
6668 "%qE does not have %<int%> type", 2, fndecl);
6669 return false;
6672 else if (!builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6673 return false;
6675 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[0])))
6677 error_at (ARG_LOCATION (0), "argument %u in call to function "
6678 "%qE does not have integral type", 1, fndecl);
6679 return false;
6681 if (TREE_CODE (TREE_TYPE (args[0])) == ENUMERAL_TYPE)
6683 error_at (ARG_LOCATION (0), "argument %u in call to function "
6684 "%qE has enumerated type", 1, fndecl);
6685 return false;
6687 if (TREE_CODE (TREE_TYPE (args[0])) == BOOLEAN_TYPE)
6689 error_at (ARG_LOCATION (0), "argument %u in call to function "
6690 "%qE has boolean type", 1, fndecl);
6691 return false;
6693 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FFSG
6694 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CLRSBG)
6696 if (TYPE_UNSIGNED (TREE_TYPE (args[0])))
6698 error_at (ARG_LOCATION (0), "argument 1 in call to function "
6699 "%qE has unsigned type", fndecl);
6700 return false;
6703 else if (!TYPE_UNSIGNED (TREE_TYPE (args[0])))
6705 error_at (ARG_LOCATION (0), "argument 1 in call to function "
6706 "%qE has signed type", fndecl);
6707 return false;
6709 return true;
6711 default:
6712 return true;
6716 /* Subroutine of c_parse_error.
6717 Return the result of concatenating LHS and RHS. RHS is really
6718 a string literal, its first character is indicated by RHS_START and
6719 RHS_SIZE is its length (including the terminating NUL character).
6721 The caller is responsible for deleting the returned pointer. */
6723 static char *
6724 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
6726 const size_t lhs_size = strlen (lhs);
6727 char *result = XNEWVEC (char, lhs_size + rhs_size);
6728 memcpy (result, lhs, lhs_size);
6729 memcpy (result + lhs_size, rhs_start, rhs_size);
6730 return result;
6733 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
6734 before TOKEN, which had the associated VALUE. */
6736 void
6737 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
6738 tree value, unsigned char token_flags,
6739 rich_location *richloc)
6741 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
6743 char *message = NULL;
6745 if (token_type == CPP_EOF)
6746 message = catenate_messages (gmsgid, " at end of input");
6747 else if (token_type == CPP_CHAR
6748 || token_type == CPP_WCHAR
6749 || token_type == CPP_CHAR16
6750 || token_type == CPP_CHAR32
6751 || token_type == CPP_UTF8CHAR)
6753 unsigned int val = TREE_INT_CST_LOW (value);
6754 const char *prefix;
6756 switch (token_type)
6758 default:
6759 prefix = "";
6760 break;
6761 case CPP_WCHAR:
6762 prefix = "L";
6763 break;
6764 case CPP_CHAR16:
6765 prefix = "u";
6766 break;
6767 case CPP_CHAR32:
6768 prefix = "U";
6769 break;
6770 case CPP_UTF8CHAR:
6771 prefix = "u8";
6772 break;
6775 if (val <= UCHAR_MAX && ISGRAPH (val))
6776 message = catenate_messages (gmsgid, " before %s'%c'");
6777 else
6778 message = catenate_messages (gmsgid, " before %s'\\x%x'");
6780 error_at (richloc, message, prefix, val);
6781 free (message);
6782 message = NULL;
6784 else if (token_type == CPP_CHAR_USERDEF
6785 || token_type == CPP_WCHAR_USERDEF
6786 || token_type == CPP_CHAR16_USERDEF
6787 || token_type == CPP_CHAR32_USERDEF
6788 || token_type == CPP_UTF8CHAR_USERDEF)
6789 message = catenate_messages (gmsgid,
6790 " before user-defined character literal");
6791 else if (token_type == CPP_STRING_USERDEF
6792 || token_type == CPP_WSTRING_USERDEF
6793 || token_type == CPP_STRING16_USERDEF
6794 || token_type == CPP_STRING32_USERDEF
6795 || token_type == CPP_UTF8STRING_USERDEF)
6796 message = catenate_messages (gmsgid, " before user-defined string literal");
6797 else if (token_type == CPP_STRING
6798 || token_type == CPP_WSTRING
6799 || token_type == CPP_STRING16
6800 || token_type == CPP_STRING32
6801 || token_type == CPP_UTF8STRING)
6802 message = catenate_messages (gmsgid, " before string constant");
6803 else if (token_type == CPP_NUMBER)
6804 message = catenate_messages (gmsgid, " before numeric constant");
6805 else if (token_type == CPP_NAME)
6807 message = catenate_messages (gmsgid, " before %qE");
6808 error_at (richloc, message, value);
6809 free (message);
6810 message = NULL;
6812 else if (token_type == CPP_PRAGMA)
6813 message = catenate_messages (gmsgid, " before %<#pragma%>");
6814 else if (token_type == CPP_PRAGMA_EOL)
6815 message = catenate_messages (gmsgid, " before end of line");
6816 else if (token_type == CPP_DECLTYPE)
6817 message = catenate_messages (gmsgid, " before %<decltype%>");
6818 else if (token_type == CPP_EMBED)
6819 message = catenate_messages (gmsgid, " before %<#embed%>");
6820 else if (token_type < N_TTYPES)
6822 message = catenate_messages (gmsgid, " before %qs token");
6823 error_at (richloc, message, cpp_type2name (token_type, token_flags));
6824 free (message);
6825 message = NULL;
6827 else
6828 error_at (richloc, gmsgid);
6830 if (message)
6832 error_at (richloc, message);
6833 free (message);
6835 #undef catenate_messages
6838 /* Return the gcc option code associated with the reason for a cpp
6839 message, or 0 if none. */
6841 static diagnostic_option_id
6842 c_option_controlling_cpp_diagnostic (enum cpp_warning_reason reason)
6844 const struct cpp_reason_option_codes_t *entry;
6846 for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6848 if (entry->reason == reason)
6849 return entry->option_code;
6851 return 0;
6854 /* Return TRUE if the given option index corresponds to a diagnostic
6855 issued by libcpp. Linear search seems fine for now. */
6856 bool
6857 c_option_is_from_cpp_diagnostics (int option_index)
6859 for (auto entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE;
6860 ++entry)
6862 if (entry->option_code == option_index)
6863 return true;
6865 return false;
6868 /* Callback from cpp_diagnostic for PFILE to print diagnostics from the
6869 preprocessor. The diagnostic is of type LEVEL, with REASON set
6870 to the reason code if LEVEL is represents a warning, at location
6871 RICHLOC unless this is after lexing and the compiler's location
6872 should be used instead; MSG is the translated message and AP
6873 the arguments. Returns true if a diagnostic was emitted, false
6874 otherwise. */
6876 bool
6877 c_cpp_diagnostic (cpp_reader *pfile ATTRIBUTE_UNUSED,
6878 enum cpp_diagnostic_level level,
6879 enum cpp_warning_reason reason,
6880 rich_location *richloc,
6881 const char *msg, va_list *ap)
6883 diagnostic_info diagnostic;
6884 diagnostic_t dlevel;
6885 bool save_warn_system_headers = global_dc->m_warn_system_headers;
6886 bool ret;
6888 switch (level)
6890 case CPP_DL_WARNING_SYSHDR:
6891 if (flag_no_output)
6892 return false;
6893 global_dc->m_warn_system_headers = 1;
6894 /* Fall through. */
6895 case CPP_DL_WARNING:
6896 if (flag_no_output)
6897 return false;
6898 dlevel = DK_WARNING;
6899 break;
6900 case CPP_DL_PEDWARN:
6901 if (flag_no_output && !flag_pedantic_errors)
6902 return false;
6903 dlevel = DK_PEDWARN;
6904 break;
6905 case CPP_DL_ERROR:
6906 dlevel = DK_ERROR;
6907 break;
6908 case CPP_DL_ICE:
6909 dlevel = DK_ICE;
6910 break;
6911 case CPP_DL_NOTE:
6912 dlevel = DK_NOTE;
6913 break;
6914 case CPP_DL_FATAL:
6915 dlevel = DK_FATAL;
6916 break;
6917 default:
6918 gcc_unreachable ();
6920 if (override_libcpp_locations)
6921 richloc->set_range (0, input_location, SHOW_RANGE_WITH_CARET);
6922 diagnostic_set_info_translated (&diagnostic, msg, ap,
6923 richloc, dlevel);
6924 diagnostic_set_option_id (&diagnostic,
6925 c_option_controlling_cpp_diagnostic (reason));
6926 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6927 if (level == CPP_DL_WARNING_SYSHDR)
6928 global_dc->m_warn_system_headers = save_warn_system_headers;
6929 return ret;
6932 /* Convert a character from the host to the target execution character
6933 set. cpplib handles this, mostly. */
6935 HOST_WIDE_INT
6936 c_common_to_target_charset (HOST_WIDE_INT c)
6938 /* Character constants in GCC proper are sign-extended under -fsigned-char,
6939 zero-extended under -fno-signed-char. cpplib insists that characters
6940 and character constants are always unsigned. Hence we must convert
6941 back and forth. */
6942 cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6944 uc = cpp_host_to_exec_charset (parse_in, uc);
6946 if (flag_signed_char)
6947 return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6948 >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6949 else
6950 return uc;
6953 /* Fold an offsetof-like expression. EXPR is a nested sequence of component
6954 references with an INDIRECT_REF of a constant at the bottom; much like the
6955 traditional rendering of offsetof as a macro. TYPE is the desired type of
6956 the whole expression. Return the folded result. */
6958 tree
6959 fold_offsetof (tree expr, tree type, enum tree_code ctx)
6961 tree base, off, t;
6962 tree_code code = TREE_CODE (expr);
6963 switch (code)
6965 case ERROR_MARK:
6966 return expr;
6968 case VAR_DECL:
6969 error ("cannot apply %<offsetof%> to static data member %qD", expr);
6970 return error_mark_node;
6972 case CALL_EXPR:
6973 case TARGET_EXPR:
6974 error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6975 return error_mark_node;
6977 case NOP_EXPR:
6978 case INDIRECT_REF:
6979 if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6981 error ("cannot apply %<offsetof%> to a non constant address");
6982 return error_mark_node;
6984 return convert (type, TREE_OPERAND (expr, 0));
6986 case COMPONENT_REF:
6987 base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6988 if (base == error_mark_node)
6989 return base;
6991 t = TREE_OPERAND (expr, 1);
6992 if (DECL_C_BIT_FIELD (t))
6994 error ("attempt to take address of bit-field structure "
6995 "member %qD", t);
6996 return error_mark_node;
6998 off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6999 size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
7000 / BITS_PER_UNIT));
7001 break;
7003 case ARRAY_REF:
7004 base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
7005 if (base == error_mark_node)
7006 return base;
7008 t = TREE_OPERAND (expr, 1);
7009 STRIP_ANY_LOCATION_WRAPPER (t);
7011 /* Check if the offset goes beyond the upper bound of the array. */
7012 if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
7014 tree upbound = array_ref_up_bound (expr);
7015 if (upbound != NULL_TREE
7016 && TREE_CODE (upbound) == INTEGER_CST
7017 && !tree_int_cst_equal (upbound,
7018 TYPE_MAX_VALUE (TREE_TYPE (upbound))))
7020 if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
7021 upbound = size_binop (PLUS_EXPR, upbound,
7022 build_int_cst (TREE_TYPE (upbound), 1));
7023 if (tree_int_cst_lt (upbound, t))
7025 tree v;
7027 for (v = TREE_OPERAND (expr, 0);
7028 TREE_CODE (v) == COMPONENT_REF;
7029 v = TREE_OPERAND (v, 0))
7030 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
7031 == RECORD_TYPE)
7033 tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
7034 for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
7035 if (TREE_CODE (fld_chain) == FIELD_DECL)
7036 break;
7038 if (fld_chain)
7039 break;
7041 /* Don't warn if the array might be considered a poor
7042 man's flexible array member with a very permissive
7043 definition thereof. */
7044 if (TREE_CODE (v) == ARRAY_REF
7045 || TREE_CODE (v) == COMPONENT_REF)
7046 warning (OPT_Warray_bounds_,
7047 "index %E denotes an offset "
7048 "greater than size of %qT",
7049 t, TREE_TYPE (TREE_OPERAND (expr, 0)));
7054 t = convert (sizetype, t);
7055 off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
7056 break;
7058 case COMPOUND_EXPR:
7059 /* Handle static members of volatile structs. */
7060 t = TREE_OPERAND (expr, 1);
7061 gcc_checking_assert (VAR_P (get_base_address (t)));
7062 return fold_offsetof (t, type);
7064 default:
7065 gcc_unreachable ();
7068 if (!POINTER_TYPE_P (type))
7069 return size_binop (PLUS_EXPR, base, convert (type, off));
7070 return fold_build_pointer_plus (base, off);
7073 /* *PTYPE is an incomplete array. Complete it with a domain based on
7074 INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
7075 is true. Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
7076 2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty. */
7079 complete_array_type (tree *ptype, tree initial_value, bool do_default)
7081 tree maxindex, type, main_type, elt, unqual_elt;
7082 int failure = 0, quals;
7083 bool overflow_p = false;
7085 maxindex = size_zero_node;
7086 if (initial_value)
7088 STRIP_ANY_LOCATION_WRAPPER (initial_value);
7090 if (TREE_CODE (initial_value) == STRING_CST)
7092 int eltsize
7093 = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
7094 maxindex = size_int (TREE_STRING_LENGTH (initial_value) / eltsize
7095 - 1);
7097 else if (TREE_CODE (initial_value) == CONSTRUCTOR)
7099 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
7101 if (vec_safe_is_empty (v))
7103 if (pedantic)
7104 failure = 3;
7105 maxindex = ssize_int (-1);
7107 else
7109 tree curindex;
7110 unsigned HOST_WIDE_INT cnt = 1;
7111 constructor_elt *ce;
7112 bool fold_p = false;
7114 if ((*v)[0].index)
7115 maxindex = (*v)[0].index, fold_p = true;
7116 if (TREE_CODE ((*v)[0].value) == RAW_DATA_CST)
7117 cnt = 0;
7119 curindex = maxindex;
7121 for (; vec_safe_iterate (v, cnt, &ce); cnt++)
7123 bool curfold_p = false;
7124 if (ce->index)
7125 curindex = ce->index, curfold_p = true;
7126 if (!ce->index || TREE_CODE (ce->value) == RAW_DATA_CST)
7128 if (fold_p || curfold_p)
7130 /* Since we treat size types now as ordinary
7131 unsigned types, we need an explicit overflow
7132 check. */
7133 tree orig = curindex;
7134 curindex = fold_convert (sizetype, curindex);
7135 overflow_p |= tree_int_cst_lt (curindex, orig);
7136 curfold_p = false;
7138 if (TREE_CODE (ce->value) == RAW_DATA_CST)
7139 curindex
7140 = size_binop (PLUS_EXPR, curindex,
7141 size_int (RAW_DATA_LENGTH (ce->value)
7142 - ((ce->index || !cnt)
7143 ? 1 : 0)));
7144 else
7145 curindex = size_binop (PLUS_EXPR, curindex,
7146 size_one_node);
7148 if (tree_int_cst_lt (maxindex, curindex))
7149 maxindex = curindex, fold_p = curfold_p;
7151 if (fold_p)
7153 tree orig = maxindex;
7154 maxindex = fold_convert (sizetype, maxindex);
7155 overflow_p |= tree_int_cst_lt (maxindex, orig);
7159 else
7161 /* Make an error message unless that happened already. */
7162 if (initial_value != error_mark_node)
7163 failure = 1;
7166 else
7168 failure = 2;
7169 if (!do_default)
7170 return failure;
7173 type = *ptype;
7174 elt = TREE_TYPE (type);
7175 quals = TYPE_QUALS (strip_array_types (elt));
7176 if (quals == 0)
7177 unqual_elt = elt;
7178 else
7179 unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
7181 /* Using build_distinct_type_copy and modifying things afterward instead
7182 of using build_array_type to create a new type preserves all of the
7183 TYPE_LANG_FLAG_? bits that the front end may have set. */
7184 main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
7185 TREE_TYPE (main_type) = unqual_elt;
7186 TYPE_DOMAIN (main_type)
7187 = build_range_type (TREE_TYPE (maxindex),
7188 build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
7189 TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
7190 layout_type (main_type);
7192 /* Set TYPE_STRUCTURAL_EQUALITY_P early. */
7193 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
7194 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
7195 SET_TYPE_STRUCTURAL_EQUALITY (main_type);
7196 else
7197 TYPE_CANONICAL (main_type) = main_type;
7199 /* Make sure we have the canonical MAIN_TYPE. */
7200 hashval_t hashcode = type_hash_canon_hash (main_type);
7201 main_type = type_hash_canon (hashcode, main_type);
7203 /* Fix the canonical type. */
7204 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
7205 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
7206 gcc_assert (TYPE_STRUCTURAL_EQUALITY_P (main_type));
7207 else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
7208 || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
7209 != TYPE_DOMAIN (main_type)))
7210 TYPE_CANONICAL (main_type)
7211 = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
7212 TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
7213 TYPE_TYPELESS_STORAGE (main_type));
7215 if (quals == 0)
7216 type = main_type;
7217 else
7218 type = c_build_qualified_type (main_type, quals);
7220 if (COMPLETE_TYPE_P (type)
7221 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
7222 && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
7224 error ("size of array is too large");
7225 /* If we proceed with the array type as it is, we'll eventually
7226 crash in tree_to_[su]hwi(). */
7227 type = error_mark_node;
7230 *ptype = type;
7231 return failure;
7234 /* INIT is an constructor of a structure with a flexible array member.
7235 Complete the flexible array member with a domain based on it's value. */
7236 void
7237 complete_flexible_array_elts (tree init)
7239 tree elt, type;
7241 if (init == NULL_TREE || TREE_CODE (init) != CONSTRUCTOR)
7242 return;
7244 if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
7245 return;
7247 elt = CONSTRUCTOR_ELTS (init)->last ().value;
7248 type = TREE_TYPE (elt);
7249 if (TREE_CODE (type) == ARRAY_TYPE
7250 && TYPE_SIZE (type) == NULL_TREE)
7251 complete_array_type (&TREE_TYPE (elt), elt, false);
7252 else
7253 complete_flexible_array_elts (elt);
7256 /* Like c_mark_addressable but don't check register qualifier. */
7257 void
7258 c_common_mark_addressable_vec (tree t)
7260 while (handled_component_p (t) || TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7262 if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7263 t = C_MAYBE_CONST_EXPR_EXPR (t);
7264 else
7265 t = TREE_OPERAND (t, 0);
7267 if (!VAR_P (t)
7268 && TREE_CODE (t) != PARM_DECL
7269 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR
7270 && TREE_CODE (t) != TARGET_EXPR)
7271 return;
7272 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
7273 TREE_ADDRESSABLE (t) = 1;
7274 if (TREE_CODE (t) == COMPOUND_LITERAL_EXPR)
7275 TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (t)) = 1;
7276 else if (TREE_CODE (t) == TARGET_EXPR)
7277 TREE_ADDRESSABLE (TARGET_EXPR_SLOT (t)) = 1;
7282 /* Used to help initialize the builtin-types.def table. When a type of
7283 the correct size doesn't exist, use error_mark_node instead of NULL.
7284 The later results in segfaults even when a decl using the type doesn't
7285 get invoked. */
7287 tree
7288 builtin_type_for_size (int size, bool unsignedp)
7290 tree type = c_common_type_for_size (size, unsignedp);
7291 return type ? type : error_mark_node;
7294 /* Work out the size of the first argument of a call to
7295 __builtin_speculation_safe_value. Only pointers and integral types
7296 are permitted. Return -1 if the argument type is not supported or
7297 the size is too large; 0 if the argument type is a pointer or the
7298 size if it is integral. */
7299 static enum built_in_function
7300 speculation_safe_value_resolve_call (tree function, vec<tree, va_gc> *params)
7302 /* Type of the argument. */
7303 tree type;
7304 int size;
7306 if (vec_safe_is_empty (params))
7308 error ("too few arguments to function %qE", function);
7309 return BUILT_IN_NONE;
7312 type = TREE_TYPE ((*params)[0]);
7313 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7315 /* Force array-to-pointer decay for C++. */
7316 (*params)[0] = default_conversion ((*params)[0]);
7317 type = TREE_TYPE ((*params)[0]);
7320 if (POINTER_TYPE_P (type))
7321 return BUILT_IN_SPECULATION_SAFE_VALUE_PTR;
7323 if (!INTEGRAL_TYPE_P (type))
7324 goto incompatible;
7326 if (!COMPLETE_TYPE_P (type))
7327 goto incompatible;
7329 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7330 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7331 return ((enum built_in_function)
7332 ((int) BUILT_IN_SPECULATION_SAFE_VALUE_1 + exact_log2 (size)));
7334 incompatible:
7335 /* Issue the diagnostic only if the argument is valid, otherwise
7336 it would be redundant at best and could be misleading. */
7337 if (type != error_mark_node)
7338 error ("operand type %qT is incompatible with argument %d of %qE",
7339 type, 1, function);
7341 return BUILT_IN_NONE;
7344 /* Validate and coerce PARAMS, the arguments to ORIG_FUNCTION to fit
7345 the prototype for FUNCTION. The first argument is mandatory, a second
7346 argument, if present, must be type compatible with the first. */
7347 static bool
7348 speculation_safe_value_resolve_params (location_t loc, tree orig_function,
7349 vec<tree, va_gc> *params)
7351 tree val;
7353 if (params->length () == 0)
7355 error_at (loc, "too few arguments to function %qE", orig_function);
7356 return false;
7359 else if (params->length () > 2)
7361 error_at (loc, "too many arguments to function %qE", orig_function);
7362 return false;
7365 val = (*params)[0];
7366 if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE)
7367 val = default_conversion (val);
7368 if (!(TREE_CODE (TREE_TYPE (val)) == POINTER_TYPE
7369 || TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE))
7371 error_at (loc,
7372 "expecting argument of type pointer or of type integer "
7373 "for argument 1");
7374 return false;
7376 (*params)[0] = val;
7378 if (params->length () == 2)
7380 tree val2 = (*params)[1];
7381 if (TREE_CODE (TREE_TYPE (val2)) == ARRAY_TYPE)
7382 val2 = default_conversion (val2);
7383 if (error_operand_p (val2))
7384 return false;
7385 if (!(TREE_TYPE (val) == TREE_TYPE (val2)
7386 || useless_type_conversion_p (TREE_TYPE (val), TREE_TYPE (val2))))
7388 error_at (loc, "both arguments must be compatible");
7389 return false;
7391 (*params)[1] = val2;
7394 return true;
7397 /* Cast the result of the builtin back to the type of the first argument,
7398 preserving any qualifiers that it might have. */
7399 static tree
7400 speculation_safe_value_resolve_return (tree first_param, tree result)
7402 tree ptype = TREE_TYPE (first_param);
7403 tree rtype = TREE_TYPE (result);
7404 ptype = TYPE_MAIN_VARIANT (ptype);
7406 if (tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7407 return convert (ptype, result);
7409 return result;
7412 /* A helper function for resolve_overloaded_builtin in resolving the
7413 overloaded __sync_ builtins. Returns a positive power of 2 if the
7414 first operand of PARAMS is a pointer to a supported data type.
7415 Returns 0 if an error is encountered. Return -1 for _BitInt
7416 __atomic*fetch* with unsupported type which should be handled by
7417 a cas loop.
7418 FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
7419 built-ins. ORIG_FORMAT is for __sync_* rather than __atomic_*
7420 built-ins. */
7422 static int
7423 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch,
7424 bool orig_format)
7426 /* Type of the argument. */
7427 tree argtype;
7428 /* Type the argument points to. */
7429 tree type;
7430 int size;
7432 if (vec_safe_is_empty (params))
7434 error ("too few arguments to function %qE", function);
7435 return 0;
7438 argtype = type = TREE_TYPE ((*params)[0]);
7439 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7441 /* Force array-to-pointer decay for C++. */
7442 (*params)[0] = default_conversion ((*params)[0]);
7443 type = TREE_TYPE ((*params)[0]);
7445 if (TREE_CODE (type) != POINTER_TYPE)
7446 goto incompatible;
7448 type = TREE_TYPE (type);
7449 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
7450 goto incompatible;
7452 if (!COMPLETE_TYPE_P (type))
7453 goto incompatible;
7455 if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
7456 goto incompatible;
7458 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7459 if (size == 16
7460 && fetch
7461 && !orig_format
7462 && TREE_CODE (type) == BITINT_TYPE
7463 && !targetm.scalar_mode_supported_p (TImode))
7464 return -1;
7466 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7467 return size;
7469 if (fetch && !orig_format && TREE_CODE (type) == BITINT_TYPE)
7470 return -1;
7472 incompatible:
7473 /* Issue the diagnostic only if the argument is valid, otherwise
7474 it would be redundant at best and could be misleading. */
7475 if (argtype != error_mark_node)
7476 error ("operand type %qT is incompatible with argument %d of %qE",
7477 argtype, 1, function);
7478 return 0;
7481 /* A helper function for resolve_overloaded_builtin. Adds casts to
7482 PARAMS to make arguments match up with those of FUNCTION. Drops
7483 the variadic arguments at the end. Returns false if some error
7484 was encountered; true on success. */
7486 static bool
7487 sync_resolve_params (location_t loc, tree orig_function, tree function,
7488 vec<tree, va_gc> *params, bool orig_format)
7490 function_args_iterator iter;
7491 tree ptype;
7492 unsigned int parmnum;
7494 function_args_iter_init (&iter, TREE_TYPE (function));
7495 /* We've declared the implementation functions to use "volatile void *"
7496 as the pointer parameter, so we shouldn't get any complaints from the
7497 call to check_function_arguments what ever type the user used. */
7498 function_args_iter_next (&iter);
7499 ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
7500 ptype = TYPE_MAIN_VARIANT (ptype);
7502 /* For the rest of the values, we need to cast these to FTYPE, so that we
7503 don't get warnings for passing pointer types, etc. */
7504 parmnum = 0;
7505 while (1)
7507 tree val, arg_type;
7509 arg_type = function_args_iter_cond (&iter);
7510 /* XXX void_type_node belies the abstraction. */
7511 if (arg_type == void_type_node)
7512 break;
7514 ++parmnum;
7515 if (params->length () <= parmnum)
7517 error_at (loc, "too few arguments to function %qE", orig_function);
7518 return false;
7521 /* Only convert parameters if arg_type is unsigned integer type with
7522 new format sync routines, i.e. don't attempt to convert pointer
7523 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
7524 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
7525 kinds). */
7526 if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
7528 /* Ideally for the first conversion we'd use convert_for_assignment
7529 so that we get warnings for anything that doesn't match the pointer
7530 type. This isn't portable across the C and C++ front ends atm. */
7531 val = (*params)[parmnum];
7532 val = convert (ptype, val);
7533 val = convert (arg_type, val);
7534 (*params)[parmnum] = val;
7537 function_args_iter_next (&iter);
7540 /* __atomic routines are not variadic. */
7541 if (!orig_format && params->length () != parmnum + 1)
7543 error_at (loc, "too many arguments to function %qE", orig_function);
7544 return false;
7547 /* The definition of these primitives is variadic, with the remaining
7548 being "an optional list of variables protected by the memory barrier".
7549 No clue what that's supposed to mean, precisely, but we consider all
7550 call-clobbered variables to be protected so we're safe. */
7551 params->truncate (parmnum + 1);
7553 return true;
7556 /* A helper function for resolve_overloaded_builtin. Adds a cast to
7557 RESULT to make it match the type of the first pointer argument in
7558 PARAMS. */
7560 static tree
7561 sync_resolve_return (tree first_param, tree result, bool orig_format)
7563 tree ptype = TREE_TYPE (TREE_TYPE (first_param));
7564 tree rtype = TREE_TYPE (result);
7565 ptype = TYPE_MAIN_VARIANT (ptype);
7567 /* New format doesn't require casting unless the types are the same size. */
7568 if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7569 return convert (ptype, result);
7570 else
7571 return result;
7574 /* This function verifies the PARAMS to generic atomic FUNCTION.
7575 It returns the size if all the parameters are the same size, otherwise
7576 0 is returned if the parameters are invalid. */
7578 static int
7579 get_atomic_generic_size (location_t loc, tree function,
7580 vec<tree, va_gc> *params)
7582 unsigned int n_param;
7583 unsigned int n_model;
7584 unsigned int outputs = 0; // bitset of output parameters
7585 unsigned int x;
7586 int size_0;
7587 tree type_0;
7589 /* Determine the parameter makeup. */
7590 switch (DECL_FUNCTION_CODE (function))
7592 case BUILT_IN_ATOMIC_EXCHANGE:
7593 n_param = 4;
7594 n_model = 1;
7595 outputs = 5;
7596 break;
7597 case BUILT_IN_ATOMIC_LOAD:
7598 n_param = 3;
7599 n_model = 1;
7600 outputs = 2;
7601 break;
7602 case BUILT_IN_ATOMIC_STORE:
7603 n_param = 3;
7604 n_model = 1;
7605 outputs = 1;
7606 break;
7607 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7608 n_param = 6;
7609 n_model = 2;
7610 outputs = 3;
7611 break;
7612 default:
7613 gcc_unreachable ();
7616 if (vec_safe_length (params) != n_param)
7618 error_at (loc, "incorrect number of arguments to function %qE", function);
7619 return 0;
7622 /* Get type of first parameter, and determine its size. */
7623 type_0 = TREE_TYPE ((*params)[0]);
7624 if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
7626 /* Force array-to-pointer decay for C++. */
7627 (*params)[0] = default_conversion ((*params)[0]);
7628 type_0 = TREE_TYPE ((*params)[0]);
7630 if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
7632 error_at (loc, "argument 1 of %qE must be a non-void pointer type",
7633 function);
7634 return 0;
7637 if (!COMPLETE_TYPE_P (TREE_TYPE (type_0)))
7639 error_at (loc, "argument 1 of %qE must be a pointer to a complete type",
7640 function);
7641 return 0;
7644 /* Types must be compile time constant sizes. */
7645 if (!tree_fits_uhwi_p ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))))
7647 error_at (loc,
7648 "argument 1 of %qE must be a pointer to a constant size type",
7649 function);
7650 return 0;
7653 size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
7655 /* Zero size objects are not allowed. */
7656 if (size_0 == 0)
7658 error_at (loc,
7659 "argument 1 of %qE must be a pointer to a nonzero size object",
7660 function);
7661 return 0;
7664 /* Check each other parameter is a pointer and the same size. */
7665 for (x = 0; x < n_param - n_model; x++)
7667 int size;
7668 tree type = TREE_TYPE ((*params)[x]);
7669 /* __atomic_compare_exchange has a bool in the 4th position, skip it. */
7670 if (n_param == 6 && x == 3)
7671 continue;
7672 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7674 /* Force array-to-pointer decay for C++. */
7675 (*params)[x] = default_conversion ((*params)[x]);
7676 type = TREE_TYPE ((*params)[x]);
7678 if (!POINTER_TYPE_P (type))
7680 error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
7681 function);
7682 return 0;
7684 else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
7685 && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
7686 != INTEGER_CST)
7688 error_at (loc, "argument %d of %qE must be a pointer to a constant "
7689 "size type", x + 1, function);
7690 return 0;
7692 else if (FUNCTION_POINTER_TYPE_P (type))
7694 error_at (loc, "argument %d of %qE must not be a pointer to a "
7695 "function", x + 1, function);
7696 return 0;
7698 tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
7699 size = type_size ? tree_to_uhwi (type_size) : 0;
7700 if (size != size_0)
7702 error_at (loc, "size mismatch in argument %d of %qE", x + 1,
7703 function);
7704 return 0;
7708 auto_diagnostic_group d;
7709 int quals = TYPE_QUALS (TREE_TYPE (type));
7710 /* Must not write to an argument of a const-qualified type. */
7711 if (outputs & (1 << x) && quals & TYPE_QUAL_CONST)
7713 if (c_dialect_cxx ())
7715 error_at (loc, "argument %d of %qE must not be a pointer to "
7716 "a %<const%> type", x + 1, function);
7717 return 0;
7719 else
7720 pedwarn (loc, OPT_Wdiscarded_qualifiers, "argument %d "
7721 "of %qE discards %<const%> qualifier", x + 1,
7722 function);
7724 /* Only the first argument is allowed to be volatile. */
7725 if (x > 0 && quals & TYPE_QUAL_VOLATILE)
7727 if (c_dialect_cxx ())
7729 error_at (loc, "argument %d of %qE must not be a pointer to "
7730 "a %<volatile%> type", x + 1, function);
7731 return 0;
7733 else
7734 pedwarn (loc, OPT_Wdiscarded_qualifiers, "argument %d "
7735 "of %qE discards %<volatile%> qualifier", x + 1,
7736 function);
7741 /* Check memory model parameters for validity. */
7742 for (x = n_param - n_model ; x < n_param; x++)
7744 tree p = (*params)[x];
7745 if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
7747 error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
7748 function);
7749 return 0;
7751 p = fold_for_warn (p);
7752 if (TREE_CODE (p) == INTEGER_CST)
7754 /* memmodel_base masks the low 16 bits, thus ignore any bits above
7755 it by using TREE_INT_CST_LOW instead of tree_to_*hwi. Those high
7756 bits will be checked later during expansion in target specific
7757 way. */
7758 if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
7759 warning_at (loc, OPT_Winvalid_memory_model,
7760 "invalid memory model argument %d of %qE", x + 1,
7761 function);
7765 return size_0;
7769 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
7770 at the beginning of the parameter list PARAMS representing the size of the
7771 objects. This is to match the library ABI requirement. LOC is the location
7772 of the function call.
7773 The new function is returned if it needed rebuilding, otherwise NULL_TREE is
7774 returned to allow the external call to be constructed. */
7776 static tree
7777 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
7778 vec<tree, va_gc> *params)
7780 tree size_node;
7782 /* Insert a SIZE_T parameter as the first param. If there isn't
7783 enough space, allocate a new vector and recursively re-build with that. */
7784 if (!params->space (1))
7786 unsigned int z, len;
7787 vec<tree, va_gc> *v;
7788 tree f;
7790 len = params->length ();
7791 vec_alloc (v, len + 1);
7792 v->quick_push (build_int_cst (size_type_node, n));
7793 for (z = 0; z < len; z++)
7794 v->quick_push ((*params)[z]);
7795 f = build_function_call_vec (loc, vNULL, function, v, NULL);
7796 vec_free (v);
7797 return f;
7800 /* Add the size parameter and leave as a function call for processing. */
7801 size_node = build_int_cst (size_type_node, n);
7802 params->quick_insert (0, size_node);
7803 return NULL_TREE;
7807 /* Return whether atomic operations for naturally aligned N-byte
7808 arguments are supported, whether inline or through libatomic. */
7809 static bool
7810 atomic_size_supported_p (int n)
7812 switch (n)
7814 case 1:
7815 case 2:
7816 case 4:
7817 case 8:
7818 return true;
7820 case 16:
7821 return targetm.scalar_mode_supported_p (TImode);
7823 default:
7824 return false;
7828 /* This will process an __atomic_exchange function call, determine whether it
7829 needs to be mapped to the _N variation, or turned into a library call.
7830 LOC is the location of the builtin call.
7831 FUNCTION is the DECL that has been invoked;
7832 PARAMS is the argument list for the call. The return value is non-null
7833 TRUE is returned if it is translated into the proper format for a call to the
7834 external library, and NEW_RETURN is set the tree for that function.
7835 FALSE is returned if processing for the _N variation is required, and
7836 NEW_RETURN is set to the return value the result is copied into. */
7837 static bool
7838 resolve_overloaded_atomic_exchange (location_t loc, tree function,
7839 vec<tree, va_gc> *params, tree *new_return)
7841 tree p0, p1, p2, p3;
7842 tree I_type, I_type_ptr;
7843 int n = get_atomic_generic_size (loc, function, params);
7845 /* Size of 0 is an error condition. */
7846 if (n == 0)
7848 *new_return = error_mark_node;
7849 return true;
7852 /* If not a lock-free size, change to the library generic format. */
7853 if (!atomic_size_supported_p (n))
7855 *new_return = add_atomic_size_parameter (n, loc, function, params);
7856 return true;
7859 /* Otherwise there is a lockfree match, transform the call from:
7860 void fn(T* mem, T* desired, T* return, model)
7861 into
7862 *return = (T) (fn (In* mem, (In) *desired, model)) */
7864 p0 = (*params)[0];
7865 p1 = (*params)[1];
7866 p2 = (*params)[2];
7867 p3 = (*params)[3];
7869 /* Create pointer to appropriate size. */
7870 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7871 I_type_ptr = build_pointer_type (I_type);
7873 /* Convert object pointer to required type. */
7874 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7875 (*params)[0] = p0;
7876 /* Convert new value to required type, and dereference it.
7877 If *p1 type can have padding or may involve floating point which
7878 could e.g. be promoted to wider precision and demoted afterwards,
7879 state of padding bits might not be preserved. */
7880 build_indirect_ref (loc, p1, RO_UNARY_STAR);
7881 p1 = build2_loc (loc, MEM_REF, I_type,
7882 build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1),
7883 build_zero_cst (TREE_TYPE (p1)));
7884 (*params)[1] = p1;
7886 /* Move memory model to the 3rd position, and end param list. */
7887 (*params)[2] = p3;
7888 params->truncate (3);
7890 /* Convert return pointer and dereference it for later assignment. */
7891 *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7893 return false;
7897 /* This will process an __atomic_compare_exchange function call, determine
7898 whether it needs to be mapped to the _N variation, or turned into a lib call.
7899 LOC is the location of the builtin call.
7900 FUNCTION is the DECL that has been invoked;
7901 PARAMS is the argument list for the call. The return value is non-null
7902 TRUE is returned if it is translated into the proper format for a call to the
7903 external library, and NEW_RETURN is set the tree for that function.
7904 FALSE is returned if processing for the _N variation is required. */
7906 static bool
7907 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
7908 vec<tree, va_gc> *params,
7909 tree *new_return)
7911 tree p0, p1, p2;
7912 tree I_type, I_type_ptr;
7913 int n = get_atomic_generic_size (loc, function, params);
7915 /* Size of 0 is an error condition. */
7916 if (n == 0)
7918 *new_return = error_mark_node;
7919 return true;
7922 /* If not a lock-free size, change to the library generic format. */
7923 if (!atomic_size_supported_p (n))
7925 /* The library generic format does not have the weak parameter, so
7926 remove it from the param list. Since a parameter has been removed,
7927 we can be sure that there is room for the SIZE_T parameter, meaning
7928 there will not be a recursive rebuilding of the parameter list, so
7929 there is no danger this will be done twice. */
7930 if (n > 0)
7932 (*params)[3] = (*params)[4];
7933 (*params)[4] = (*params)[5];
7934 params->truncate (5);
7936 *new_return = add_atomic_size_parameter (n, loc, function, params);
7937 return true;
7940 /* Otherwise, there is a match, so the call needs to be transformed from:
7941 bool fn(T* mem, T* desired, T* return, weak, success, failure)
7942 into
7943 bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail) */
7945 p0 = (*params)[0];
7946 p1 = (*params)[1];
7947 p2 = (*params)[2];
7949 /* Create pointer to appropriate size. */
7950 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7951 I_type_ptr = build_pointer_type (I_type);
7953 /* Convert object pointer to required type. */
7954 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7955 (*params)[0] = p0;
7957 /* Convert expected pointer to required type. */
7958 p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
7959 (*params)[1] = p1;
7961 /* Convert desired value to required type, and dereference it.
7962 If *p2 type can have padding or may involve floating point which
7963 could e.g. be promoted to wider precision and demoted afterwards,
7964 state of padding bits might not be preserved. */
7965 build_indirect_ref (loc, p2, RO_UNARY_STAR);
7966 p2 = build2_loc (loc, MEM_REF, I_type,
7967 build1 (VIEW_CONVERT_EXPR, I_type_ptr, p2),
7968 build_zero_cst (TREE_TYPE (p2)));
7969 (*params)[2] = p2;
7971 /* The rest of the parameters are fine. NULL means no special return value
7972 processing.*/
7973 *new_return = NULL;
7974 return false;
7978 /* This will process an __atomic_load function call, determine whether it
7979 needs to be mapped to the _N variation, or turned into a library call.
7980 LOC is the location of the builtin call.
7981 FUNCTION is the DECL that has been invoked;
7982 PARAMS is the argument list for the call. The return value is non-null
7983 TRUE is returned if it is translated into the proper format for a call to the
7984 external library, and NEW_RETURN is set the tree for that function.
7985 FALSE is returned if processing for the _N variation is required, and
7986 NEW_RETURN is set to the return value the result is copied into. */
7988 static bool
7989 resolve_overloaded_atomic_load (location_t loc, tree function,
7990 vec<tree, va_gc> *params, tree *new_return)
7992 tree p0, p1, p2;
7993 tree I_type, I_type_ptr;
7994 int n = get_atomic_generic_size (loc, function, params);
7996 /* Size of 0 is an error condition. */
7997 if (n == 0)
7999 *new_return = error_mark_node;
8000 return true;
8003 /* If not a lock-free size, change to the library generic format. */
8004 if (!atomic_size_supported_p (n))
8006 *new_return = add_atomic_size_parameter (n, loc, function, params);
8007 return true;
8010 /* Otherwise, there is a match, so the call needs to be transformed from:
8011 void fn(T* mem, T* return, model)
8012 into
8013 *return = (T) (fn ((In *) mem, model)) */
8015 p0 = (*params)[0];
8016 p1 = (*params)[1];
8017 p2 = (*params)[2];
8019 /* Create pointer to appropriate size. */
8020 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
8021 I_type_ptr = build_pointer_type (I_type);
8023 /* Convert object pointer to required type. */
8024 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
8025 (*params)[0] = p0;
8027 /* Move memory model to the 2nd position, and end param list. */
8028 (*params)[1] = p2;
8029 params->truncate (2);
8031 /* Convert return pointer and dereference it for later assignment. */
8032 *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
8034 return false;
8038 /* This will process an __atomic_store function call, determine whether it
8039 needs to be mapped to the _N variation, or turned into a library call.
8040 LOC is the location of the builtin call.
8041 FUNCTION is the DECL that has been invoked;
8042 PARAMS is the argument list for the call. The return value is non-null
8043 TRUE is returned if it is translated into the proper format for a call to the
8044 external library, and NEW_RETURN is set the tree for that function.
8045 FALSE is returned if processing for the _N variation is required, and
8046 NEW_RETURN is set to the return value the result is copied into. */
8048 static bool
8049 resolve_overloaded_atomic_store (location_t loc, tree function,
8050 vec<tree, va_gc> *params, tree *new_return)
8052 tree p0, p1;
8053 tree I_type, I_type_ptr;
8054 int n = get_atomic_generic_size (loc, function, params);
8056 /* Size of 0 is an error condition. */
8057 if (n == 0)
8059 *new_return = error_mark_node;
8060 return true;
8063 /* If not a lock-free size, change to the library generic format. */
8064 if (!atomic_size_supported_p (n))
8066 *new_return = add_atomic_size_parameter (n, loc, function, params);
8067 return true;
8070 /* Otherwise, there is a match, so the call needs to be transformed from:
8071 void fn(T* mem, T* value, model)
8072 into
8073 fn ((In *) mem, (In) *value, model) */
8075 p0 = (*params)[0];
8076 p1 = (*params)[1];
8078 /* Create pointer to appropriate size. */
8079 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
8080 I_type_ptr = build_pointer_type (I_type);
8082 /* Convert object pointer to required type. */
8083 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
8084 (*params)[0] = p0;
8086 /* Convert new value to required type, and dereference it. */
8087 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
8088 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
8089 (*params)[1] = p1;
8091 /* The memory model is in the right spot already. Return is void. */
8092 *new_return = NULL_TREE;
8094 return false;
8098 /* Emit __atomic*fetch* on _BitInt which doesn't have a size of
8099 1, 2, 4, 8 or 16 bytes using __atomic_compare_exchange loop.
8100 ORIG_CODE is the DECL_FUNCTION_CODE of ORIG_FUNCTION and
8101 ORIG_PARAMS arguments of the call. */
8103 static tree
8104 atomic_bitint_fetch_using_cas_loop (location_t loc,
8105 enum built_in_function orig_code,
8106 tree orig_function,
8107 vec<tree, va_gc> *orig_params)
8109 enum tree_code code = ERROR_MARK;
8110 bool return_old_p = false;
8111 switch (orig_code)
8113 case BUILT_IN_ATOMIC_ADD_FETCH_N:
8114 code = PLUS_EXPR;
8115 break;
8116 case BUILT_IN_ATOMIC_SUB_FETCH_N:
8117 code = MINUS_EXPR;
8118 break;
8119 case BUILT_IN_ATOMIC_AND_FETCH_N:
8120 code = BIT_AND_EXPR;
8121 break;
8122 case BUILT_IN_ATOMIC_NAND_FETCH_N:
8123 break;
8124 case BUILT_IN_ATOMIC_XOR_FETCH_N:
8125 code = BIT_XOR_EXPR;
8126 break;
8127 case BUILT_IN_ATOMIC_OR_FETCH_N:
8128 code = BIT_IOR_EXPR;
8129 break;
8130 case BUILT_IN_ATOMIC_FETCH_ADD_N:
8131 code = PLUS_EXPR;
8132 return_old_p = true;
8133 break;
8134 case BUILT_IN_ATOMIC_FETCH_SUB_N:
8135 code = MINUS_EXPR;
8136 return_old_p = true;
8137 break;
8138 case BUILT_IN_ATOMIC_FETCH_AND_N:
8139 code = BIT_AND_EXPR;
8140 return_old_p = true;
8141 break;
8142 case BUILT_IN_ATOMIC_FETCH_NAND_N:
8143 return_old_p = true;
8144 break;
8145 case BUILT_IN_ATOMIC_FETCH_XOR_N:
8146 code = BIT_XOR_EXPR;
8147 return_old_p = true;
8148 break;
8149 case BUILT_IN_ATOMIC_FETCH_OR_N:
8150 code = BIT_IOR_EXPR;
8151 return_old_p = true;
8152 break;
8153 default:
8154 gcc_unreachable ();
8157 if (orig_params->length () != 3)
8159 if (orig_params->length () < 3)
8160 error_at (loc, "too few arguments to function %qE", orig_function);
8161 else
8162 error_at (loc, "too many arguments to function %qE", orig_function);
8163 return error_mark_node;
8166 tree stmts = push_stmt_list ();
8168 tree nonatomic_lhs_type = TREE_TYPE (TREE_TYPE ((*orig_params)[0]));
8169 nonatomic_lhs_type = TYPE_MAIN_VARIANT (nonatomic_lhs_type);
8170 gcc_assert (TREE_CODE (nonatomic_lhs_type) == BITINT_TYPE);
8172 tree lhs_addr = (*orig_params)[0];
8173 tree val = convert (nonatomic_lhs_type, (*orig_params)[1]);
8174 tree model = convert (integer_type_node, (*orig_params)[2]);
8175 if (!c_dialect_cxx ())
8177 lhs_addr = c_fully_fold (lhs_addr, false, NULL);
8178 val = c_fully_fold (val, false, NULL);
8179 model = c_fully_fold (model, false, NULL);
8181 if (TREE_SIDE_EFFECTS (lhs_addr))
8183 tree var = create_tmp_var_raw (TREE_TYPE (lhs_addr));
8184 lhs_addr = build4 (TARGET_EXPR, TREE_TYPE (lhs_addr), var, lhs_addr,
8185 NULL_TREE, NULL_TREE);
8186 add_stmt (lhs_addr);
8188 if (TREE_SIDE_EFFECTS (val))
8190 tree var = create_tmp_var_raw (nonatomic_lhs_type);
8191 val = build4 (TARGET_EXPR, nonatomic_lhs_type, var, val, NULL_TREE,
8192 NULL_TREE);
8193 add_stmt (val);
8195 if (TREE_SIDE_EFFECTS (model))
8197 tree var = create_tmp_var_raw (integer_type_node);
8198 model = build4 (TARGET_EXPR, integer_type_node, var, model, NULL_TREE,
8199 NULL_TREE);
8200 add_stmt (model);
8203 tree old = create_tmp_var_raw (nonatomic_lhs_type);
8204 tree old_addr = build_unary_op (loc, ADDR_EXPR, old, false);
8205 TREE_ADDRESSABLE (old) = 1;
8206 suppress_warning (old);
8208 tree newval = create_tmp_var_raw (nonatomic_lhs_type);
8209 tree newval_addr = build_unary_op (loc, ADDR_EXPR, newval, false);
8210 TREE_ADDRESSABLE (newval) = 1;
8211 suppress_warning (newval);
8213 tree loop_decl = create_artificial_label (loc);
8214 tree loop_label = build1 (LABEL_EXPR, void_type_node, loop_decl);
8216 tree done_decl = create_artificial_label (loc);
8217 tree done_label = build1 (LABEL_EXPR, void_type_node, done_decl);
8219 vec<tree, va_gc> *params;
8220 vec_alloc (params, 6);
8222 /* __atomic_load (addr, &old, SEQ_CST). */
8223 tree fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD);
8224 params->quick_push (lhs_addr);
8225 params->quick_push (old_addr);
8226 params->quick_push (build_int_cst (integer_type_node, MEMMODEL_RELAXED));
8227 tree func_call = resolve_overloaded_builtin (loc, fndecl, params);
8228 if (func_call == NULL_TREE)
8229 func_call = build_function_call_vec (loc, vNULL, fndecl, params, NULL);
8230 old = build4 (TARGET_EXPR, nonatomic_lhs_type, old, func_call, NULL_TREE,
8231 NULL_TREE);
8232 add_stmt (old);
8233 params->truncate (0);
8235 /* loop: */
8236 add_stmt (loop_label);
8238 /* newval = old + val; */
8239 tree rhs;
8240 switch (code)
8242 case PLUS_EXPR:
8243 case MINUS_EXPR:
8244 if (!TYPE_OVERFLOW_WRAPS (nonatomic_lhs_type))
8246 tree utype
8247 = build_bitint_type (TYPE_PRECISION (nonatomic_lhs_type), 1);
8248 rhs = convert (nonatomic_lhs_type,
8249 build2_loc (loc, code, utype,
8250 convert (utype, old),
8251 convert (utype, val)));
8253 else
8254 rhs = build2_loc (loc, code, nonatomic_lhs_type, old, val);
8255 break;
8256 case BIT_AND_EXPR:
8257 case BIT_IOR_EXPR:
8258 case BIT_XOR_EXPR:
8259 rhs = build2_loc (loc, code, nonatomic_lhs_type, old, val);
8260 break;
8261 case ERROR_MARK:
8262 rhs = build2_loc (loc, BIT_AND_EXPR, nonatomic_lhs_type,
8263 build1_loc (loc, BIT_NOT_EXPR,
8264 nonatomic_lhs_type, old), val);
8265 break;
8266 default:
8267 gcc_unreachable ();
8269 rhs = build4 (TARGET_EXPR, nonatomic_lhs_type, newval, rhs, NULL_TREE,
8270 NULL_TREE);
8271 SET_EXPR_LOCATION (rhs, loc);
8272 add_stmt (rhs);
8274 /* if (__atomic_compare_exchange (addr, &old, &new, false, model, model))
8275 goto done; */
8276 fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_COMPARE_EXCHANGE);
8277 params->quick_push (lhs_addr);
8278 params->quick_push (old_addr);
8279 params->quick_push (newval_addr);
8280 params->quick_push (integer_zero_node);
8281 params->quick_push (model);
8282 if (tree_fits_uhwi_p (model)
8283 && (tree_to_uhwi (model) == MEMMODEL_RELEASE
8284 || tree_to_uhwi (model) == MEMMODEL_ACQ_REL))
8285 params->quick_push (build_int_cst (integer_type_node, MEMMODEL_RELAXED));
8286 else
8287 params->quick_push (model);
8288 func_call = resolve_overloaded_builtin (loc, fndecl, params);
8289 if (func_call == NULL_TREE)
8290 func_call = build_function_call_vec (loc, vNULL, fndecl, params, NULL);
8292 tree goto_stmt = build1 (GOTO_EXPR, void_type_node, done_decl);
8293 SET_EXPR_LOCATION (goto_stmt, loc);
8295 tree stmt
8296 = build3 (COND_EXPR, void_type_node, func_call, goto_stmt, NULL_TREE);
8297 SET_EXPR_LOCATION (stmt, loc);
8298 add_stmt (stmt);
8300 /* goto loop; */
8301 goto_stmt = build1 (GOTO_EXPR, void_type_node, loop_decl);
8302 SET_EXPR_LOCATION (goto_stmt, loc);
8303 add_stmt (goto_stmt);
8305 /* done: */
8306 add_stmt (done_label);
8308 tree ret = create_tmp_var_raw (nonatomic_lhs_type);
8309 stmt = build2_loc (loc, MODIFY_EXPR, void_type_node, ret,
8310 return_old_p ? old : newval);
8311 add_stmt (stmt);
8313 /* Finish the compound statement. */
8314 stmts = pop_stmt_list (stmts);
8316 return build4 (TARGET_EXPR, nonatomic_lhs_type, ret, stmts, NULL_TREE,
8317 NULL_TREE);
8321 /* Some builtin functions are placeholders for other expressions. This
8322 function should be called immediately after parsing the call expression
8323 before surrounding code has committed to the type of the expression.
8325 LOC is the location of the builtin call.
8327 FUNCTION is the DECL that has been invoked; it is known to be a builtin.
8328 PARAMS is the argument list for the call. The return value is non-null
8329 when expansion is complete, and null if normal processing should
8330 continue. */
8332 tree
8333 resolve_overloaded_builtin (location_t loc, tree function,
8334 vec<tree, va_gc> *params)
8336 /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
8337 Those are not valid to call with a pointer to _Bool (or C++ bool)
8338 and so must be rejected. */
8339 bool fetch_op = true;
8340 bool orig_format = true;
8341 tree new_return = NULL_TREE;
8343 switch (DECL_BUILT_IN_CLASS (function))
8345 case BUILT_IN_NORMAL:
8346 break;
8347 case BUILT_IN_MD:
8348 if (targetm.resolve_overloaded_builtin)
8349 return targetm.resolve_overloaded_builtin (loc, function, params);
8350 else
8351 return NULL_TREE;
8352 default:
8353 return NULL_TREE;
8356 /* Handle BUILT_IN_NORMAL here. */
8357 enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
8358 switch (orig_code)
8360 case BUILT_IN_SPECULATION_SAFE_VALUE_N:
8362 tree new_function, first_param, result;
8363 enum built_in_function fncode
8364 = speculation_safe_value_resolve_call (function, params);
8366 if (fncode == BUILT_IN_NONE)
8367 return error_mark_node;
8369 first_param = (*params)[0];
8370 if (!speculation_safe_value_resolve_params (loc, function, params))
8371 return error_mark_node;
8373 if (targetm.have_speculation_safe_value (true))
8375 new_function = builtin_decl_explicit (fncode);
8376 result = build_function_call_vec (loc, vNULL, new_function, params,
8377 NULL);
8379 if (result == error_mark_node)
8380 return result;
8382 return speculation_safe_value_resolve_return (first_param, result);
8384 else
8386 /* This target doesn't have, or doesn't need, active mitigation
8387 against incorrect speculative execution. Simply return the
8388 first parameter to the builtin. */
8389 if (!targetm.have_speculation_safe_value (false))
8390 /* The user has invoked __builtin_speculation_safe_value
8391 even though __HAVE_SPECULATION_SAFE_VALUE is not
8392 defined: emit a warning. */
8393 warning_at (input_location, 0,
8394 "this target does not define a speculation barrier; "
8395 "your program will still execute correctly, "
8396 "but incorrect speculation may not be "
8397 "restricted");
8399 /* If the optional second argument is present, handle any side
8400 effects now. */
8401 if (params->length () == 2
8402 && TREE_SIDE_EFFECTS ((*params)[1]))
8403 return build2 (COMPOUND_EXPR, TREE_TYPE (first_param),
8404 (*params)[1], first_param);
8406 return first_param;
8410 case BUILT_IN_ATOMIC_EXCHANGE:
8411 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
8412 case BUILT_IN_ATOMIC_LOAD:
8413 case BUILT_IN_ATOMIC_STORE:
8415 /* Handle these 4 together so that they can fall through to the next
8416 case if the call is transformed to an _N variant. */
8417 switch (orig_code)
8419 case BUILT_IN_ATOMIC_EXCHANGE:
8421 if (resolve_overloaded_atomic_exchange (loc, function, params,
8422 &new_return))
8423 return new_return;
8424 /* Change to the _N variant. */
8425 orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
8426 break;
8429 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
8431 if (resolve_overloaded_atomic_compare_exchange (loc, function,
8432 params,
8433 &new_return))
8434 return new_return;
8435 /* Change to the _N variant. */
8436 orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
8437 break;
8439 case BUILT_IN_ATOMIC_LOAD:
8441 if (resolve_overloaded_atomic_load (loc, function, params,
8442 &new_return))
8443 return new_return;
8444 /* Change to the _N variant. */
8445 orig_code = BUILT_IN_ATOMIC_LOAD_N;
8446 break;
8448 case BUILT_IN_ATOMIC_STORE:
8450 if (resolve_overloaded_atomic_store (loc, function, params,
8451 &new_return))
8452 return new_return;
8453 /* Change to the _N variant. */
8454 orig_code = BUILT_IN_ATOMIC_STORE_N;
8455 break;
8457 default:
8458 gcc_unreachable ();
8461 /* FALLTHRU */
8462 case BUILT_IN_ATOMIC_EXCHANGE_N:
8463 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
8464 case BUILT_IN_ATOMIC_LOAD_N:
8465 case BUILT_IN_ATOMIC_STORE_N:
8466 fetch_op = false;
8467 /* FALLTHRU */
8468 case BUILT_IN_ATOMIC_ADD_FETCH_N:
8469 case BUILT_IN_ATOMIC_SUB_FETCH_N:
8470 case BUILT_IN_ATOMIC_AND_FETCH_N:
8471 case BUILT_IN_ATOMIC_NAND_FETCH_N:
8472 case BUILT_IN_ATOMIC_XOR_FETCH_N:
8473 case BUILT_IN_ATOMIC_OR_FETCH_N:
8474 case BUILT_IN_ATOMIC_FETCH_ADD_N:
8475 case BUILT_IN_ATOMIC_FETCH_SUB_N:
8476 case BUILT_IN_ATOMIC_FETCH_AND_N:
8477 case BUILT_IN_ATOMIC_FETCH_NAND_N:
8478 case BUILT_IN_ATOMIC_FETCH_XOR_N:
8479 case BUILT_IN_ATOMIC_FETCH_OR_N:
8480 orig_format = false;
8481 /* FALLTHRU */
8482 case BUILT_IN_SYNC_FETCH_AND_ADD_N:
8483 case BUILT_IN_SYNC_FETCH_AND_SUB_N:
8484 case BUILT_IN_SYNC_FETCH_AND_OR_N:
8485 case BUILT_IN_SYNC_FETCH_AND_AND_N:
8486 case BUILT_IN_SYNC_FETCH_AND_XOR_N:
8487 case BUILT_IN_SYNC_FETCH_AND_NAND_N:
8488 case BUILT_IN_SYNC_ADD_AND_FETCH_N:
8489 case BUILT_IN_SYNC_SUB_AND_FETCH_N:
8490 case BUILT_IN_SYNC_OR_AND_FETCH_N:
8491 case BUILT_IN_SYNC_AND_AND_FETCH_N:
8492 case BUILT_IN_SYNC_XOR_AND_FETCH_N:
8493 case BUILT_IN_SYNC_NAND_AND_FETCH_N:
8494 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
8495 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
8496 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
8497 case BUILT_IN_SYNC_LOCK_RELEASE_N:
8499 /* The following are not _FETCH_OPs and must be accepted with
8500 pointers to _Bool (or C++ bool). */
8501 if (fetch_op)
8502 fetch_op = (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8503 && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
8504 && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
8505 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
8507 int n = sync_resolve_size (function, params, fetch_op, orig_format);
8508 tree new_function, first_param, result;
8509 enum built_in_function fncode;
8511 if (n == 0)
8512 return error_mark_node;
8514 if (n == -1)
8515 return atomic_bitint_fetch_using_cas_loop (loc, orig_code,
8516 function, params);
8518 fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
8519 new_function = builtin_decl_explicit (fncode);
8520 if (!sync_resolve_params (loc, function, new_function, params,
8521 orig_format))
8522 return error_mark_node;
8524 first_param = (*params)[0];
8525 result = build_function_call_vec (loc, vNULL, new_function, params,
8526 NULL);
8527 if (result == error_mark_node)
8528 return result;
8529 if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8530 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
8531 && orig_code != BUILT_IN_ATOMIC_STORE_N
8532 && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
8533 result = sync_resolve_return (first_param, result, orig_format);
8535 if (fetch_op)
8536 /* Prevent -Wunused-value warning. */
8537 TREE_USED (result) = true;
8539 /* If new_return is set, assign function to that expr and cast the
8540 result to void since the generic interface returned void. */
8541 if (new_return)
8543 /* Cast function result from I{1,2,4,8,16} to the required type. */
8544 if (TREE_CODE (TREE_TYPE (new_return)) == BITINT_TYPE)
8546 struct bitint_info info;
8547 unsigned prec = TYPE_PRECISION (TREE_TYPE (new_return));
8548 targetm.c.bitint_type_info (prec, &info);
8549 if (!info.extended)
8550 /* For _BitInt which has the padding bits undefined
8551 convert to the _BitInt type rather than VCE to force
8552 zero or sign extension. */
8553 result = build1 (NOP_EXPR, TREE_TYPE (new_return), result);
8555 result
8556 = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
8557 result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
8558 result);
8559 TREE_SIDE_EFFECTS (result) = 1;
8560 protected_set_expr_location (result, loc);
8561 result = convert (void_type_node, result);
8563 return result;
8566 default:
8567 return NULL_TREE;
8571 /* vector_types_compatible_elements_p is used in type checks of vectors
8572 values used as operands of binary operators. Where it returns true, and
8573 the other checks of the caller succeed (being vector types in he first
8574 place, and matching number of elements), we can just treat the types
8575 as essentially the same.
8576 Contrast with vector_targets_convertible_p, which is used for vector
8577 pointer types, and vector_types_convertible_p, which will allow
8578 language-specific matches under the control of flag_lax_vector_conversions,
8579 and might still require a conversion. */
8580 /* True if vector types T1 and T2 can be inputs to the same binary
8581 operator without conversion.
8582 We don't check the overall vector size here because some of our callers
8583 want to give different error messages when the vectors are compatible
8584 except for the element count. */
8586 bool
8587 vector_types_compatible_elements_p (tree t1, tree t2)
8589 bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
8590 t1 = TREE_TYPE (t1);
8591 t2 = TREE_TYPE (t2);
8593 enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
8595 gcc_assert ((INTEGRAL_TYPE_P (t1)
8596 || c1 == REAL_TYPE
8597 || c1 == FIXED_POINT_TYPE)
8598 && (INTEGRAL_TYPE_P (t2)
8599 || c2 == REAL_TYPE
8600 || c2 == FIXED_POINT_TYPE));
8602 t1 = c_common_signed_type (t1);
8603 t2 = c_common_signed_type (t2);
8604 /* Equality works here because c_common_signed_type uses
8605 TYPE_MAIN_VARIANT. */
8606 if (t1 == t2)
8607 return true;
8608 if (opaque && c1 == c2
8609 && (INTEGRAL_TYPE_P (t1) || c1 == REAL_TYPE)
8610 && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
8611 return true;
8612 return false;
8615 /* Check for missing format attributes on function pointers. LTYPE is
8616 the new type or left-hand side type. RTYPE is the old type or
8617 right-hand side type. Returns TRUE if LTYPE is missing the desired
8618 attribute. */
8620 bool
8621 check_missing_format_attribute (tree ltype, tree rtype)
8623 tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
8624 tree ra;
8626 for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
8627 if (is_attribute_p ("format", get_attribute_name (ra)))
8628 break;
8629 if (ra)
8631 tree la;
8632 for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
8633 if (is_attribute_p ("format", get_attribute_name (la)))
8634 break;
8635 return !la;
8637 else
8638 return false;
8641 /* Setup a TYPE_DECL node as a typedef representation.
8643 X is a TYPE_DECL for a typedef statement. Create a brand new
8644 ..._TYPE node (which will be just a variant of the existing
8645 ..._TYPE node with identical properties) and then install X
8646 as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
8648 The whole point here is to end up with a situation where each
8649 and every ..._TYPE node the compiler creates will be uniquely
8650 associated with AT MOST one node representing a typedef name.
8651 This way, even though the compiler substitutes corresponding
8652 ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
8653 early on, later parts of the compiler can always do the reverse
8654 translation and get back the corresponding typedef name. For
8655 example, given:
8657 typedef struct S MY_TYPE;
8658 MY_TYPE object;
8660 Later parts of the compiler might only know that `object' was of
8661 type `struct S' if it were not for code just below. With this
8662 code however, later parts of the compiler see something like:
8664 struct S' == struct S
8665 typedef struct S' MY_TYPE;
8666 struct S' object;
8668 And they can then deduce (from the node for type struct S') that
8669 the original object declaration was:
8671 MY_TYPE object;
8673 Being able to do this is important for proper support of protoize,
8674 and also for generating precise symbolic debugging information
8675 which takes full account of the programmer's (typedef) vocabulary.
8677 Obviously, we don't want to generate a duplicate ..._TYPE node if
8678 the TYPE_DECL node that we are now processing really represents a
8679 standard built-in type. */
8681 void
8682 set_underlying_type (tree x)
8684 if (x == error_mark_node || TREE_TYPE (x) == error_mark_node)
8685 return;
8686 if (DECL_IS_UNDECLARED_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
8688 if (TYPE_NAME (TREE_TYPE (x)) == 0)
8689 TYPE_NAME (TREE_TYPE (x)) = x;
8691 else if (DECL_ORIGINAL_TYPE (x))
8692 gcc_checking_assert (TYPE_NAME (TREE_TYPE (x)) == x);
8693 else
8695 tree tt = TREE_TYPE (x);
8696 DECL_ORIGINAL_TYPE (x) = tt;
8697 tt = build_variant_type_copy (tt);
8698 TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
8699 TYPE_NAME (tt) = x;
8701 /* Mark the type as used only when its type decl is decorated
8702 with attribute unused. */
8703 if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
8704 TREE_USED (tt) = 1;
8706 TREE_TYPE (x) = tt;
8710 /* Return true if it is worth exposing the DECL_ORIGINAL_TYPE of TYPE to
8711 the user in diagnostics, false if it would be better to use TYPE itself.
8712 TYPE is known to satisfy typedef_variant_p. */
8714 bool
8715 user_facing_original_type_p (const_tree type)
8717 gcc_assert (typedef_variant_p (type));
8718 tree decl = TYPE_NAME (type);
8720 /* Look through any typedef in "user" code. */
8721 if (!DECL_IN_SYSTEM_HEADER (decl) && !DECL_IS_UNDECLARED_BUILTIN (decl))
8722 return true;
8724 /* If the original type is also named and is in the user namespace,
8725 assume it too is a user-facing type. */
8726 tree orig_type = DECL_ORIGINAL_TYPE (decl);
8727 if (tree orig_id = TYPE_IDENTIFIER (orig_type))
8728 if (!name_reserved_for_implementation_p (IDENTIFIER_POINTER (orig_id)))
8729 return true;
8731 switch (TREE_CODE (orig_type))
8733 /* Don't look through to an anonymous vector type, since the syntax
8734 we use for them in diagnostics isn't real C or C++ syntax.
8735 And if ORIG_TYPE is named but in the implementation namespace,
8736 TYPE is likely to be more meaningful to the user. */
8737 case VECTOR_TYPE:
8738 return false;
8740 /* Don't expose anonymous tag types that are presumably meant to be
8741 known by their typedef name. Also don't expose tags that are in
8742 the implementation namespace, such as:
8744 typedef struct __foo foo; */
8745 case RECORD_TYPE:
8746 case UNION_TYPE:
8747 case ENUMERAL_TYPE:
8748 return false;
8750 /* Look through to anything else. */
8751 default:
8752 return true;
8756 /* Record the types used by the current global variable declaration
8757 being parsed, so that we can decide later to emit their debug info.
8758 Those types are in types_used_by_cur_var_decl, and we are going to
8759 store them in the types_used_by_vars_hash hash table.
8760 DECL is the declaration of the global variable that has been parsed. */
8762 void
8763 record_types_used_by_current_var_decl (tree decl)
8765 gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
8767 while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
8769 tree type = types_used_by_cur_var_decl->pop ();
8770 types_used_by_var_decl_insert (type, decl);
8774 /* The C and C++ parsers both use vectors to hold function arguments.
8775 For efficiency, we keep a cache of unused vectors. This is the
8776 cache. */
8778 typedef vec<tree, va_gc> *tree_gc_vec;
8779 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
8781 /* Return a new vector from the cache. If the cache is empty,
8782 allocate a new vector. These vectors are GC'ed, so it is OK if the
8783 pointer is not released.. */
8785 vec<tree, va_gc> *
8786 make_tree_vector (void)
8788 if (tree_vector_cache && !tree_vector_cache->is_empty ())
8789 return tree_vector_cache->pop ();
8790 else
8792 /* Passing 0 to vec::alloc returns NULL, and our callers require
8793 that we always return a non-NULL value. The vector code uses
8794 4 when growing a NULL vector, so we do too. */
8795 vec<tree, va_gc> *v;
8796 vec_alloc (v, 4);
8797 return v;
8801 /* Release a vector of trees back to the cache. */
8803 void
8804 release_tree_vector (vec<tree, va_gc> *vec)
8806 if (vec != NULL)
8808 if (vec->allocated () >= 16)
8809 /* Don't cache vecs that have expanded more than once. On a p64
8810 target, vecs double in alloc size with each power of 2 elements, e.g
8811 at 16 elements the alloc increases from 128 to 256 bytes. */
8812 vec_free (vec);
8813 else
8815 vec->truncate (0);
8816 vec_safe_push (tree_vector_cache, vec);
8821 /* Get a new tree vector holding a single tree. */
8823 vec<tree, va_gc> *
8824 make_tree_vector_single (tree t)
8826 vec<tree, va_gc> *ret = make_tree_vector ();
8827 ret->quick_push (t);
8828 return ret;
8831 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain. */
8833 vec<tree, va_gc> *
8834 make_tree_vector_from_list (tree list)
8836 vec<tree, va_gc> *ret = make_tree_vector ();
8837 for (; list; list = TREE_CHAIN (list))
8838 vec_safe_push (ret, TREE_VALUE (list));
8839 return ret;
8842 /* Get a new tree vector of the values of a CONSTRUCTOR. */
8844 vec<tree, va_gc> *
8845 make_tree_vector_from_ctor (tree ctor)
8847 vec<tree,va_gc> *ret = make_tree_vector ();
8848 vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
8849 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
8850 ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
8851 return ret;
8854 /* Get a new tree vector which is a copy of an existing one. */
8856 vec<tree, va_gc> *
8857 make_tree_vector_copy (const vec<tree, va_gc> *orig)
8859 vec<tree, va_gc> *ret;
8860 unsigned int ix;
8861 tree t;
8863 ret = make_tree_vector ();
8864 vec_safe_reserve (ret, vec_safe_length (orig));
8865 FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
8866 ret->quick_push (t);
8867 return ret;
8870 /* Return true if KEYWORD starts a type specifier. */
8872 bool
8873 keyword_begins_type_specifier (enum rid keyword)
8875 switch (keyword)
8877 case RID_AUTO_TYPE:
8878 case RID_INT:
8879 case RID_CHAR:
8880 case RID_FLOAT:
8881 case RID_DOUBLE:
8882 case RID_VOID:
8883 case RID_UNSIGNED:
8884 case RID_LONG:
8885 case RID_SHORT:
8886 case RID_SIGNED:
8887 CASE_RID_FLOATN_NX:
8888 case RID_DFLOAT32:
8889 case RID_DFLOAT64:
8890 case RID_DFLOAT128:
8891 case RID_FRACT:
8892 case RID_ACCUM:
8893 case RID_BOOL:
8894 case RID_BITINT:
8895 case RID_WCHAR:
8896 case RID_CHAR8:
8897 case RID_CHAR16:
8898 case RID_CHAR32:
8899 case RID_SAT:
8900 case RID_COMPLEX:
8901 case RID_TYPEOF:
8902 case RID_STRUCT:
8903 case RID_CLASS:
8904 case RID_UNION:
8905 case RID_ENUM:
8906 return true;
8907 default:
8908 if (keyword >= RID_FIRST_INT_N
8909 && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
8910 && int_n_enabled_p[keyword-RID_FIRST_INT_N])
8911 return true;
8912 return false;
8916 /* Return true if KEYWORD names a type qualifier. */
8918 bool
8919 keyword_is_type_qualifier (enum rid keyword)
8921 switch (keyword)
8923 case RID_CONST:
8924 case RID_VOLATILE:
8925 case RID_RESTRICT:
8926 case RID_ATOMIC:
8927 return true;
8928 default:
8929 return false;
8933 /* Return true if KEYWORD names a storage class specifier.
8935 RID_TYPEDEF is not included in this list despite `typedef' being
8936 listed in C99 6.7.1.1. 6.7.1.3 indicates that `typedef' is listed as
8937 such for syntactic convenience only. */
8939 bool
8940 keyword_is_storage_class_specifier (enum rid keyword)
8942 switch (keyword)
8944 case RID_STATIC:
8945 case RID_EXTERN:
8946 case RID_REGISTER:
8947 case RID_AUTO:
8948 case RID_MUTABLE:
8949 case RID_THREAD:
8950 return true;
8951 default:
8952 return false;
8956 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec]. */
8958 static bool
8959 keyword_is_function_specifier (enum rid keyword)
8961 switch (keyword)
8963 case RID_INLINE:
8964 case RID_NORETURN:
8965 case RID_VIRTUAL:
8966 case RID_EXPLICIT:
8967 return true;
8968 default:
8969 return false;
8973 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
8974 declaration-specifier (C99 6.7). */
8976 bool
8977 keyword_is_decl_specifier (enum rid keyword)
8979 if (keyword_is_storage_class_specifier (keyword)
8980 || keyword_is_type_qualifier (keyword)
8981 || keyword_is_function_specifier (keyword))
8982 return true;
8984 switch (keyword)
8986 case RID_TYPEDEF:
8987 case RID_FRIEND:
8988 case RID_CONSTEXPR:
8989 case RID_CONSTINIT:
8990 return true;
8991 default:
8992 return false;
8996 /* Initialize language-specific-bits of tree_contains_struct. */
8998 void
8999 c_common_init_ts (void)
9001 MARK_TS_EXP (SIZEOF_EXPR);
9002 MARK_TS_EXP (PAREN_SIZEOF_EXPR);
9003 MARK_TS_EXP (C_MAYBE_CONST_EXPR);
9004 MARK_TS_EXP (EXCESS_PRECISION_EXPR);
9005 MARK_TS_EXP (BREAK_STMT);
9006 MARK_TS_EXP (CONTINUE_STMT);
9007 MARK_TS_EXP (DO_STMT);
9008 MARK_TS_EXP (FOR_STMT);
9009 MARK_TS_EXP (SWITCH_STMT);
9010 MARK_TS_EXP (WHILE_STMT);
9012 MARK_TS_DECL_COMMON (CONCEPT_DECL);
9015 /* Build a user-defined numeric literal out of an integer constant type VALUE
9016 with identifier SUFFIX. */
9018 tree
9019 build_userdef_literal (tree suffix_id, tree value,
9020 enum overflow_type overflow, tree num_string)
9022 tree literal = make_node (USERDEF_LITERAL);
9023 USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
9024 USERDEF_LITERAL_VALUE (literal) = value;
9025 USERDEF_LITERAL_OVERFLOW (literal) = overflow;
9026 USERDEF_LITERAL_NUM_STRING (literal) = num_string;
9027 return literal;
9030 /* For vector[index], convert the vector to an array of the underlying type.
9031 Return true if the resulting ARRAY_REF should not be an lvalue. */
9033 bool
9034 convert_vector_to_array_for_subscript (location_t loc,
9035 tree *vecp, tree index)
9037 bool ret = false;
9038 if (gnu_vector_type_p (TREE_TYPE (*vecp)))
9040 tree type = TREE_TYPE (*vecp);
9041 tree newitype;
9043 ret = !lvalue_p (*vecp);
9045 index = fold_for_warn (index);
9046 if (TREE_CODE (index) == INTEGER_CST)
9047 if (!tree_fits_uhwi_p (index)
9048 || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
9049 warning_at (loc, OPT_Warray_bounds_, "index value is out of bound");
9051 /* We are building an ARRAY_REF so mark the vector as addressable
9052 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
9053 for function parameters. */
9054 c_common_mark_addressable_vec (*vecp);
9056 /* Make sure qualifiers are copied from the vector type to the new element
9057 of the array type. */
9058 newitype = build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9060 *vecp = build1 (VIEW_CONVERT_EXPR,
9061 build_array_type_nelts (newitype,
9062 TYPE_VECTOR_SUBPARTS (type)),
9063 *vecp);
9065 return ret;
9068 /* Determine which of the operands, if any, is a scalar that needs to be
9069 converted to a vector, for the range of operations. */
9070 enum stv_conv
9071 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
9072 bool complain)
9074 tree type0 = TREE_TYPE (op0);
9075 tree type1 = TREE_TYPE (op1);
9076 bool integer_only_op = false;
9077 enum stv_conv ret = stv_firstarg;
9079 gcc_assert (gnu_vector_type_p (type0) || gnu_vector_type_p (type1));
9080 switch (code)
9082 /* Most GENERIC binary expressions require homogeneous arguments.
9083 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
9084 argument that is a vector and a second one that is a scalar, so
9085 we never return stv_secondarg for them. */
9086 case RSHIFT_EXPR:
9087 case LSHIFT_EXPR:
9088 if (TREE_CODE (type0) == INTEGER_TYPE
9089 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
9091 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
9092 NULL_TREE, false))
9094 if (complain)
9095 error_at (loc, "conversion of scalar %qT to vector %qT "
9096 "involves truncation", type0, type1);
9097 return stv_error;
9099 else
9100 return stv_firstarg;
9102 break;
9104 case BIT_IOR_EXPR:
9105 case BIT_XOR_EXPR:
9106 case BIT_AND_EXPR:
9107 integer_only_op = true;
9108 /* fall through */
9110 case VEC_COND_EXPR:
9112 case PLUS_EXPR:
9113 case MINUS_EXPR:
9114 case MULT_EXPR:
9115 case TRUNC_DIV_EXPR:
9116 case CEIL_DIV_EXPR:
9117 case FLOOR_DIV_EXPR:
9118 case ROUND_DIV_EXPR:
9119 case EXACT_DIV_EXPR:
9120 case TRUNC_MOD_EXPR:
9121 case FLOOR_MOD_EXPR:
9122 case RDIV_EXPR:
9123 case EQ_EXPR:
9124 case NE_EXPR:
9125 case LE_EXPR:
9126 case GE_EXPR:
9127 case LT_EXPR:
9128 case GT_EXPR:
9129 /* What about UNLT_EXPR? */
9130 if (gnu_vector_type_p (type0))
9132 ret = stv_secondarg;
9133 std::swap (type0, type1);
9134 std::swap (op0, op1);
9137 if (TREE_CODE (type0) == INTEGER_TYPE
9138 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
9140 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
9141 NULL_TREE, false))
9143 if (complain)
9144 error_at (loc, "conversion of scalar %qT to vector %qT "
9145 "involves truncation", type0, type1);
9146 return stv_error;
9148 return ret;
9150 else if (!integer_only_op
9151 /* Allow integer --> real conversion if safe. */
9152 && (SCALAR_FLOAT_TYPE_P (type0)
9153 || TREE_CODE (type0) == INTEGER_TYPE)
9154 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
9156 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
9157 NULL_TREE, false))
9159 if (complain)
9160 error_at (loc, "conversion of scalar %qT to vector %qT "
9161 "involves truncation", type0, type1);
9162 return stv_error;
9164 return ret;
9166 default:
9167 break;
9170 return stv_nothing;
9173 /* Return the alignment of std::max_align_t.
9175 [support.types.layout] The type max_align_t is a POD type whose alignment
9176 requirement is at least as great as that of every scalar type, and whose
9177 alignment requirement is supported in every context. */
9179 unsigned
9180 max_align_t_align ()
9182 unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
9183 TYPE_ALIGN (long_double_type_node));
9184 if (float128_type_node != NULL_TREE)
9185 max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
9186 return max_align;
9189 /* Return true iff ALIGN is an integral constant that is a fundamental
9190 alignment, as defined by [basic.align] in the c++-11
9191 specifications.
9193 That is:
9195 [A fundamental alignment is represented by an alignment less than or
9196 equal to the greatest alignment supported by the implementation
9197 in all contexts, which is equal to alignof(max_align_t)]. */
9199 bool
9200 cxx_fundamental_alignment_p (unsigned align)
9202 return (align <= max_align_t_align ());
9205 /* Return true if T is a pointer to a zero-sized aggregate. */
9207 bool
9208 pointer_to_zero_sized_aggr_p (tree t)
9210 if (!POINTER_TYPE_P (t))
9211 return false;
9212 t = TREE_TYPE (t);
9213 return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
9216 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
9217 with no library fallback or for an ADDR_EXPR whose operand is such type
9218 issues an error pointing to the location LOC.
9219 Returns true when the expression has been diagnosed and false
9220 otherwise. */
9222 bool
9223 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
9225 if (TREE_CODE (expr) == ADDR_EXPR)
9226 expr = TREE_OPERAND (expr, 0);
9228 STRIP_ANY_LOCATION_WRAPPER (expr);
9230 if (TREE_TYPE (expr)
9231 && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
9232 && TREE_CODE (expr) == FUNCTION_DECL
9233 /* The intersection of DECL_BUILT_IN and DECL_IS_UNDECLARED_BUILTIN avoids
9234 false positives for user-declared built-ins such as abs or
9235 strlen, and for C++ operators new and delete.
9236 The c_decl_implicit() test avoids false positives for implicitly
9237 declared built-ins with library fallbacks (such as abs). */
9238 && fndecl_built_in_p (expr)
9239 && DECL_IS_UNDECLARED_BUILTIN (expr)
9240 && !c_decl_implicit (expr)
9241 && !DECL_ASSEMBLER_NAME_SET_P (expr))
9243 if (loc == UNKNOWN_LOCATION)
9244 loc = EXPR_LOC_OR_LOC (expr, input_location);
9246 /* Reject arguments that are built-in functions with
9247 no library fallback. */
9248 error_at (loc, "built-in function %qE must be directly called", expr);
9250 return true;
9253 return false;
9256 /* Issue an ERROR for an invalid SIZE of array NAME which is null
9257 for unnamed arrays. */
9259 void
9260 invalid_array_size_error (location_t loc, cst_size_error error,
9261 const_tree size, const_tree name)
9263 tree maxsize = max_object_size ();
9264 switch (error)
9266 case cst_size_not_constant:
9267 if (name)
9268 error_at (loc, "size of array %qE is not a constant expression",
9269 name);
9270 else
9271 error_at (loc, "size of array is not a constant expression");
9272 break;
9273 case cst_size_negative:
9274 if (name)
9275 error_at (loc, "size %qE of array %qE is negative",
9276 size, name);
9277 else
9278 error_at (loc, "size %qE of array is negative",
9279 size);
9280 break;
9281 case cst_size_too_big:
9282 if (name)
9283 error_at (loc, "size %qE of array %qE exceeds maximum "
9284 "object size %qE", size, name, maxsize);
9285 else
9286 error_at (loc, "size %qE of array exceeds maximum "
9287 "object size %qE", size, maxsize);
9288 break;
9289 case cst_size_overflow:
9290 if (name)
9291 error_at (loc, "size of array %qE exceeds maximum "
9292 "object size %qE", name, maxsize);
9293 else
9294 error_at (loc, "size of array exceeds maximum "
9295 "object size %qE", maxsize);
9296 break;
9297 default:
9298 gcc_unreachable ();
9302 /* Check if array size calculations overflow or if the array covers more
9303 than half of the address space. Return true if the size of the array
9304 is valid, false otherwise. T is either the type of the array or its
9305 size, and NAME is the name of the array, or null for unnamed arrays. */
9307 bool
9308 valid_array_size_p (location_t loc, const_tree t, tree name, bool complain)
9310 if (t == error_mark_node)
9311 return true;
9313 const_tree size;
9314 if (TYPE_P (t))
9316 if (!COMPLETE_TYPE_P (t))
9317 return true;
9318 size = TYPE_SIZE_UNIT (t);
9320 else
9321 size = t;
9323 if (TREE_CODE (size) != INTEGER_CST)
9324 return true;
9326 cst_size_error error;
9327 if (valid_constant_size_p (size, &error))
9328 return true;
9330 if (!complain)
9331 return false;
9333 if (TREE_CODE (TREE_TYPE (size)) == ENUMERAL_TYPE)
9334 /* Show the value of the enumerator rather than its name. */
9335 size = convert (ssizetype, const_cast<tree> (size));
9337 invalid_array_size_error (loc, error, size, name);
9338 return false;
9341 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
9342 timestamp to replace embedded current dates to get reproducible
9343 results. Returns -1 if SOURCE_DATE_EPOCH is not defined. */
9345 time_t
9346 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
9348 char *source_date_epoch;
9349 int64_t epoch;
9350 char *endptr;
9352 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
9353 if (!source_date_epoch)
9354 return (time_t) -1;
9356 errno = 0;
9357 #if defined(INT64_T_IS_LONG)
9358 epoch = strtol (source_date_epoch, &endptr, 10);
9359 #else
9360 epoch = strtoll (source_date_epoch, &endptr, 10);
9361 #endif
9362 if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
9363 || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
9365 error_at (input_location, "environment variable %qs must "
9366 "expand to a non-negative integer less than or equal to %wd",
9367 "SOURCE_DATE_EPOCH", MAX_SOURCE_DATE_EPOCH);
9368 return (time_t) -1;
9371 return (time_t) epoch;
9374 /* Callback for libcpp for offering spelling suggestions for misspelled
9375 directives. GOAL is an unrecognized string; CANDIDATES is a
9376 NULL-terminated array of candidate strings. Return the closest
9377 match to GOAL within CANDIDATES, or NULL if none are good
9378 suggestions. */
9380 const char *
9381 cb_get_suggestion (cpp_reader *, const char *goal,
9382 const char *const *candidates)
9384 best_match<const char *, const char *> bm (goal);
9385 while (*candidates)
9386 bm.consider (*candidates++);
9387 return bm.get_best_meaningful_candidate ();
9390 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
9391 modes X, Y. This isn't just >, as the FLT_EVAL_METHOD values added
9392 by C TS 18661-3 for interchange types that are computed in their
9393 native precision are larger than the C11 values for evaluating in the
9394 precision of float/double/long double. If either mode is
9395 FLT_EVAL_METHOD_UNPREDICTABLE, return that. */
9397 enum flt_eval_method
9398 excess_precision_mode_join (enum flt_eval_method x,
9399 enum flt_eval_method y)
9401 if (x == FLT_EVAL_METHOD_UNPREDICTABLE
9402 || y == FLT_EVAL_METHOD_UNPREDICTABLE)
9403 return FLT_EVAL_METHOD_UNPREDICTABLE;
9405 /* GCC only supports one interchange type right now, _Float16. If
9406 we're evaluating _Float16 in 16-bit precision, then flt_eval_method
9407 will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
9408 if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
9409 return y;
9410 if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
9411 return x;
9413 /* Other values for flt_eval_method are directly comparable, and we want
9414 the maximum. */
9415 return MAX (x, y);
9418 /* Return the value that should be set for FLT_EVAL_METHOD in the
9419 context of ISO/IEC TS 18861-3.
9421 This relates to the effective excess precision seen by the user,
9422 which is the join point of the precision the target requests for
9423 -fexcess-precision={standard,fast,16} and the implicit excess precision
9424 the target uses. */
9426 static enum flt_eval_method
9427 c_ts18661_flt_eval_method (void)
9429 enum flt_eval_method implicit
9430 = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
9432 enum excess_precision_type flag_type
9433 = (flag_excess_precision == EXCESS_PRECISION_STANDARD
9434 ? EXCESS_PRECISION_TYPE_STANDARD
9435 : (flag_excess_precision == EXCESS_PRECISION_FLOAT16
9436 ? EXCESS_PRECISION_TYPE_FLOAT16
9437 : EXCESS_PRECISION_TYPE_FAST));
9439 enum flt_eval_method requested
9440 = targetm.c.excess_precision (flag_type);
9442 return excess_precision_mode_join (implicit, requested);
9445 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
9446 those that were permitted by C11. That is to say, eliminates
9447 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
9449 static enum flt_eval_method
9450 c_c11_flt_eval_method (void)
9452 return excess_precision_mode_join (c_ts18661_flt_eval_method (),
9453 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
9456 /* Return the value that should be set for FLT_EVAL_METHOD.
9457 MAYBE_C11_ONLY_P is TRUE if we should check
9458 FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
9459 values we can return to those from C99/C11, and FALSE otherwise.
9460 See the comments on c_ts18661_flt_eval_method for what value we choose
9461 to set here. */
9464 c_flt_eval_method (bool maybe_c11_only_p)
9466 if (maybe_c11_only_p
9467 && flag_permitted_flt_eval_methods
9468 == PERMITTED_FLT_EVAL_METHODS_C11)
9469 return c_c11_flt_eval_method ();
9470 else
9471 return c_ts18661_flt_eval_method ();
9474 /* An enum for get_missing_token_insertion_kind for describing the best
9475 place to insert a missing token, if there is one. */
9477 enum missing_token_insertion_kind
9479 MTIK_IMPOSSIBLE,
9480 MTIK_INSERT_BEFORE_NEXT,
9481 MTIK_INSERT_AFTER_PREV
9484 /* Given a missing token of TYPE, determine if it is reasonable to
9485 emit a fix-it hint suggesting the insertion of the token, and,
9486 if so, where the token should be inserted relative to other tokens.
9488 It only makes sense to do this for values of TYPE that are symbols.
9490 Some symbols should go before the next token, e.g. in:
9491 if flag)
9492 we want to insert the missing '(' immediately before "flag",
9493 giving:
9494 if (flag)
9495 rather than:
9496 if( flag)
9497 These use MTIK_INSERT_BEFORE_NEXT.
9499 Other symbols should go after the previous token, e.g. in:
9500 if (flag
9501 do_something ();
9502 we want to insert the missing ')' immediately after the "flag",
9503 giving:
9504 if (flag)
9505 do_something ();
9506 rather than:
9507 if (flag
9508 )do_something ();
9509 These use MTIK_INSERT_AFTER_PREV. */
9511 static enum missing_token_insertion_kind
9512 get_missing_token_insertion_kind (enum cpp_ttype type)
9514 switch (type)
9516 /* Insert missing "opening" brackets immediately
9517 before the next token. */
9518 case CPP_OPEN_SQUARE:
9519 case CPP_OPEN_PAREN:
9520 return MTIK_INSERT_BEFORE_NEXT;
9522 /* Insert other missing symbols immediately after
9523 the previous token. */
9524 case CPP_CLOSE_PAREN:
9525 case CPP_CLOSE_SQUARE:
9526 case CPP_SEMICOLON:
9527 case CPP_COMMA:
9528 case CPP_COLON:
9529 return MTIK_INSERT_AFTER_PREV;
9531 /* Other kinds of token don't get fix-it hints. */
9532 default:
9533 return MTIK_IMPOSSIBLE;
9537 /* Given RICHLOC, a location for a diagnostic describing a missing token
9538 of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
9539 insertion of the token.
9541 The location of the attempted fix-it hint depends on TOKEN_TYPE:
9542 it will either be:
9543 (a) immediately after PREV_TOKEN_LOC, or
9545 (b) immediately before the primary location within RICHLOC (taken to
9546 be that of the token following where the token was expected).
9548 If we manage to add a fix-it hint, then the location of the
9549 fix-it hint is likely to be more useful as the primary location
9550 of the diagnostic than that of the following token, so we swap
9551 these locations.
9553 For example, given this bogus code:
9554 123456789012345678901234567890
9555 1 | int missing_semicolon (void)
9556 2 | {
9557 3 | return 42
9558 4 | }
9560 we will emit:
9562 "expected ';' before '}'"
9564 RICHLOC's primary location is at the closing brace, so before "swapping"
9565 we would emit the error at line 4 column 1:
9567 123456789012345678901234567890
9568 3 | return 42 |< fix-it hint emitted for this line
9569 | ; |
9570 4 | } |< "expected ';' before '}'" emitted at this line
9571 | ^ |
9573 It's more useful for the location of the diagnostic to be at the
9574 fix-it hint, so we swap the locations, so the primary location
9575 is at the fix-it hint, with the old primary location inserted
9576 as a secondary location, giving this, with the error at line 3
9577 column 12:
9579 123456789012345678901234567890
9580 3 | return 42 |< "expected ';' before '}'" emitted at this line,
9581 | ^ | with fix-it hint
9582 4 | ; |
9583 | } |< secondary range emitted here
9584 | ~ |. */
9586 void
9587 maybe_suggest_missing_token_insertion (rich_location *richloc,
9588 enum cpp_ttype token_type,
9589 location_t prev_token_loc)
9591 gcc_assert (richloc);
9593 enum missing_token_insertion_kind mtik
9594 = get_missing_token_insertion_kind (token_type);
9596 switch (mtik)
9598 default:
9599 gcc_unreachable ();
9600 break;
9602 case MTIK_IMPOSSIBLE:
9603 return;
9605 case MTIK_INSERT_BEFORE_NEXT:
9606 /* Attempt to add the fix-it hint before the primary location
9607 of RICHLOC. */
9608 richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
9609 break;
9611 case MTIK_INSERT_AFTER_PREV:
9612 /* Attempt to add the fix-it hint after PREV_TOKEN_LOC. */
9613 richloc->add_fixit_insert_after (prev_token_loc,
9614 cpp_type2name (token_type, 0));
9615 break;
9618 /* If we were successful, use the fix-it hint's location as the
9619 primary location within RICHLOC, adding the old primary location
9620 back as a secondary location. */
9621 if (!richloc->seen_impossible_fixit_p ())
9623 fixit_hint *hint = richloc->get_last_fixit_hint ();
9624 location_t hint_loc = hint->get_start_loc ();
9625 location_t old_loc = richloc->get_loc ();
9627 richloc->set_range (0, hint_loc, SHOW_RANGE_WITH_CARET);
9628 richloc->add_range (old_loc);
9632 #if CHECKING_P
9634 namespace selftest {
9636 /* Verify that fold_for_warn on error_mark_node is safe. */
9638 static void
9639 test_fold_for_warn ()
9641 ASSERT_EQ (error_mark_node, fold_for_warn (error_mark_node));
9644 /* Run all of the selftests within this file. */
9646 static void
9647 c_common_cc_tests ()
9649 test_fold_for_warn ();
9652 /* Run all of the tests within c-family. */
9654 void
9655 c_family_tests (void)
9657 c_common_cc_tests ();
9658 c_format_cc_tests ();
9659 c_indentation_cc_tests ();
9660 c_pretty_print_cc_tests ();
9661 c_spellcheck_cc_tests ();
9662 c_diagnostic_cc_tests ();
9663 c_opt_problem_cc_tests ();
9666 } // namespace selftest
9668 #endif /* #if CHECKING_P */
9670 /* Attempt to locate a suitable location within FILE for a
9671 #include directive to be inserted before.
9672 LOC is the location of the relevant diagnostic.
9674 Attempt to return the location within FILE immediately
9675 after the last #include within that file, or the start of
9676 that file if it has no #include directives.
9678 Return UNKNOWN_LOCATION if no suitable location is found,
9679 or if an error occurs. */
9681 static location_t
9682 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
9684 /* Locate the last ordinary map within FILE that ended with a #include. */
9685 const line_map_ordinary *last_include_ord_map = NULL;
9687 /* ...and the next ordinary map within FILE after that one. */
9688 const line_map_ordinary *last_ord_map_after_include = NULL;
9690 /* ...and the first ordinary map within FILE. */
9691 const line_map_ordinary *first_ord_map_in_file = NULL;
9693 /* Get ordinary map containing LOC (or its expansion). */
9694 const line_map_ordinary *ord_map_for_loc = NULL;
9695 linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
9696 &ord_map_for_loc);
9697 gcc_assert (ord_map_for_loc);
9699 for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
9701 const line_map_ordinary *ord_map
9702 = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
9704 if (const line_map_ordinary *from
9705 = linemap_included_from_linemap (line_table, ord_map))
9706 /* We cannot use pointer equality, because with preprocessed
9707 input all filename strings are unique. */
9708 if (0 == strcmp (from->to_file, file))
9710 last_include_ord_map = from;
9711 last_ord_map_after_include = NULL;
9714 /* Likewise, use strcmp, and reject any line-zero introductory
9715 map. */
9716 if (ord_map->to_line && 0 == strcmp (ord_map->to_file, file))
9718 if (!first_ord_map_in_file)
9719 first_ord_map_in_file = ord_map;
9720 if (last_include_ord_map && !last_ord_map_after_include)
9721 last_ord_map_after_include = ord_map;
9724 /* Stop searching when reaching the ord_map containing LOC,
9725 as it makes no sense to provide fix-it hints that appear
9726 after the diagnostic in question. */
9727 if (ord_map == ord_map_for_loc)
9728 break;
9731 /* Determine where to insert the #include. */
9732 const line_map_ordinary *ord_map_for_insertion;
9734 /* We want the next ordmap in the file after the last one that's a
9735 #include, but failing that, the start of the file. */
9736 if (last_ord_map_after_include)
9737 ord_map_for_insertion = last_ord_map_after_include;
9738 else
9739 ord_map_for_insertion = first_ord_map_in_file;
9741 if (!ord_map_for_insertion)
9742 return UNKNOWN_LOCATION;
9744 /* The "start_location" is column 0, meaning "the whole line".
9745 rich_location and edit_context can't cope with this, so use
9746 column 1 instead. */
9747 location_t col_0 = ord_map_for_insertion->start_location;
9748 return linemap_position_for_loc_and_offset (line_table, col_0, 1);
9751 /* A map from filenames to sets of headers added to them, for
9752 ensuring idempotency within maybe_add_include_fixit. */
9754 /* The values within the map. We need string comparison as there's
9755 no guarantee that two different diagnostics that are recommending
9756 adding e.g. "<stdio.h>" are using the same buffer. */
9758 typedef hash_set <const char *, false, nofree_string_hash> per_file_includes_t;
9760 /* The map itself. We don't need string comparison for the filename keys,
9761 as they come from libcpp. */
9763 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
9764 static added_includes_t *added_includes;
9766 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
9767 in a suitable location within the file of RICHLOC's primary
9768 location.
9770 This function is idempotent: a header will be added at most once to
9771 any given file.
9773 If OVERRIDE_LOCATION is true, then if a fix-it is added and will be
9774 printed, then RICHLOC's primary location will be replaced by that of
9775 the fix-it hint (for use by "inform" notes where the location of the
9776 issue has already been reported). */
9778 void
9779 maybe_add_include_fixit (rich_location *richloc, const char *header,
9780 bool override_location)
9782 location_t loc = richloc->get_loc ();
9783 const char *file = LOCATION_FILE (loc);
9784 if (!file)
9785 return;
9787 /* Idempotency: don't add the same header more than once to a given file. */
9788 if (!added_includes)
9789 added_includes = new added_includes_t ();
9790 per_file_includes_t *&set = added_includes->get_or_insert (file);
9791 if (set)
9792 if (set->contains (header))
9793 /* ...then we've already added HEADER to that file. */
9794 return;
9795 if (!set)
9796 set = new per_file_includes_t ();
9797 set->add (header);
9799 /* Attempt to locate a suitable place for the new directive. */
9800 location_t include_insert_loc
9801 = try_to_locate_new_include_insertion_point (file, loc);
9802 if (include_insert_loc == UNKNOWN_LOCATION)
9803 return;
9805 char *text = xasprintf ("#include %s\n", header);
9806 richloc->add_fixit_insert_before (include_insert_loc, text);
9807 free (text);
9809 if (override_location && global_dc->m_source_printing.enabled)
9811 /* Replace the primary location with that of the insertion point for the
9812 fix-it hint.
9814 We use SHOW_LINES_WITHOUT_RANGE so that we don't meaningless print a
9815 caret for the insertion point (or colorize it).
9817 Hence we print e.g.:
9819 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9820 73 | # include <debug/vector>
9821 +++ |+#include <vector>
9822 74 | #endif
9824 rather than:
9826 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9827 73 | # include <debug/vector>
9828 +++ |+#include <vector>
9829 74 | #endif
9832 avoiding the caret on the first column of line 74. */
9833 richloc->set_range (0, include_insert_loc, SHOW_LINES_WITHOUT_RANGE);
9837 /* Attempt to convert a braced array initializer list CTOR for array
9838 TYPE into a STRING_CST for convenience and efficiency. Return
9839 the converted string on success or the original ctor on failure.
9840 Also, for non-convertable CTORs which contain RAW_DATA_CST values
9841 among the elts try to extend the range of RAW_DATA_CSTs. */
9843 static tree
9844 braced_list_to_string (tree type, tree ctor, bool member)
9846 /* Ignore non-members with unknown size like arrays with unspecified
9847 bound. */
9848 tree typesize = TYPE_SIZE_UNIT (type);
9849 if (!member && !tree_fits_uhwi_p (typesize))
9850 return ctor;
9852 /* If the target char size differs from the host char size, we'd risk
9853 loosing data and getting object sizes wrong by converting to
9854 host chars. */
9855 if (TYPE_PRECISION (char_type_node) != CHAR_BIT)
9856 return ctor;
9858 /* STRING_CST doesn't support wide characters. */
9859 gcc_checking_assert (TYPE_PRECISION (TREE_TYPE (type)) == CHAR_BIT);
9861 /* If the array has an explicit bound, use it to constrain the size
9862 of the string. If it doesn't, be sure to create a string that's
9863 as long as implied by the index of the last zero specified via
9864 a designator, as in:
9865 const char a[] = { [7] = 0 }; */
9866 unsigned HOST_WIDE_INT maxelts;
9867 if (typesize)
9869 maxelts = tree_to_uhwi (typesize);
9870 maxelts /= tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type)));
9872 else
9873 maxelts = HOST_WIDE_INT_M1U;
9875 /* Avoid converting initializers for zero-length arrays (but do
9876 create them for flexible array members). */
9877 if (!maxelts)
9878 return ctor;
9880 unsigned HOST_WIDE_INT nelts = CONSTRUCTOR_NELTS (ctor);
9882 auto_vec<char> str;
9883 str.reserve (nelts + 1);
9885 unsigned HOST_WIDE_INT i, j = HOST_WIDE_INT_M1U;
9886 tree index, value;
9887 bool check_raw_data = false;
9889 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, index, value)
9891 if (check_raw_data)
9893 /* The preprocessor always surrounds CPP_EMBED tokens in between
9894 CPP_NUMBER and CPP_COMMA tokens. Try to undo that here now that
9895 the whole initializer is parsed. E.g. if we have
9896 [0] = 'T', [1] = "his is a #embed tex", [20] = 't'
9897 where the middle value is RAW_DATA_CST and in its owner this is
9898 surrounded by 'T' and 't' characters, we can create from it just
9899 [0] = "This is a #embed text"
9900 Similarly if a RAW_DATA_CST needs to be split into two parts
9901 because of designated init store but the stored value is actually
9902 the same as in the RAW_DATA_OWNER's memory we can merge multiple
9903 RAW_DATA_CSTs. */
9904 if (TREE_CODE (value) == RAW_DATA_CST
9905 && index
9906 && tree_fits_uhwi_p (index))
9908 tree owner = RAW_DATA_OWNER (value);
9909 unsigned int start, end, k;
9910 if (TREE_CODE (owner) == STRING_CST)
9912 start
9913 = RAW_DATA_POINTER (value) - TREE_STRING_POINTER (owner);
9914 end = TREE_STRING_LENGTH (owner) - RAW_DATA_LENGTH (value);
9916 else
9918 gcc_checking_assert (TREE_CODE (owner) == RAW_DATA_CST);
9919 start
9920 = RAW_DATA_POINTER (value) - RAW_DATA_POINTER (owner);
9921 end = RAW_DATA_LENGTH (owner) - RAW_DATA_LENGTH (value);
9923 end -= start;
9924 unsigned HOST_WIDE_INT l = j == HOST_WIDE_INT_M1U ? i : j;
9925 for (k = 0; k < start && k < l; ++k)
9927 constructor_elt *elt = CONSTRUCTOR_ELT (ctor, l - k - 1);
9928 if (elt->index == NULL_TREE
9929 || !tree_fits_uhwi_p (elt->index)
9930 || !tree_fits_shwi_p (elt->value)
9931 || wi::to_widest (index) != (wi::to_widest (elt->index)
9932 + (k + 1)))
9933 break;
9934 if (TYPE_UNSIGNED (TREE_TYPE (value)))
9936 if (tree_to_shwi (elt->value)
9937 != *((const unsigned char *)
9938 RAW_DATA_POINTER (value) - k - 1))
9939 break;
9941 else if (tree_to_shwi (elt->value)
9942 != *((const signed char *)
9943 RAW_DATA_POINTER (value) - k - 1))
9944 break;
9946 start = k;
9947 l = 0;
9948 for (k = 0; k < end && k + 1 < CONSTRUCTOR_NELTS (ctor) - i; ++k)
9950 constructor_elt *elt = CONSTRUCTOR_ELT (ctor, i + k + 1);
9951 if (elt->index == NULL_TREE
9952 || !tree_fits_uhwi_p (elt->index)
9953 || (wi::to_widest (elt->index)
9954 != (wi::to_widest (index)
9955 + (RAW_DATA_LENGTH (value) + l))))
9956 break;
9957 if (TREE_CODE (elt->value) == RAW_DATA_CST
9958 && RAW_DATA_OWNER (elt->value) == RAW_DATA_OWNER (value)
9959 && (RAW_DATA_POINTER (elt->value)
9960 == RAW_DATA_POINTER (value) + l))
9962 l += RAW_DATA_LENGTH (elt->value);
9963 end -= RAW_DATA_LENGTH (elt->value) - 1;
9964 continue;
9966 if (!tree_fits_shwi_p (elt->value))
9967 break;
9968 if (TYPE_UNSIGNED (TREE_TYPE (value)))
9970 if (tree_to_shwi (elt->value)
9971 != *((const unsigned char *)
9972 RAW_DATA_POINTER (value)
9973 + RAW_DATA_LENGTH (value) + k))
9974 break;
9976 else if (tree_to_shwi (elt->value)
9977 != *((const signed char *)
9978 RAW_DATA_POINTER (value)
9979 + RAW_DATA_LENGTH (value) + k))
9980 break;
9981 ++l;
9983 end = k;
9984 if (start != 0 || end != 0)
9986 if (j == HOST_WIDE_INT_M1U)
9987 j = i - start;
9988 else
9989 j -= start;
9990 RAW_DATA_POINTER (value) -= start;
9991 RAW_DATA_LENGTH (value) += start + end;
9992 i += end;
9993 if (start == 0)
9994 CONSTRUCTOR_ELT (ctor, j)->index = index;
9995 CONSTRUCTOR_ELT (ctor, j)->value = value;
9996 ++j;
9997 continue;
10000 if (j != HOST_WIDE_INT_M1U)
10002 CONSTRUCTOR_ELT (ctor, j)->index = index;
10003 CONSTRUCTOR_ELT (ctor, j)->value = value;
10004 ++j;
10006 continue;
10009 unsigned HOST_WIDE_INT idx = i;
10010 if (index)
10012 if (!tree_fits_uhwi_p (index))
10014 check_raw_data = true;
10015 continue;
10017 idx = tree_to_uhwi (index);
10020 /* auto_vec is limited to UINT_MAX elements. */
10021 if (idx > UINT_MAX)
10023 check_raw_data = true;
10024 continue;
10027 /* Avoid non-constant initializers. */
10028 if (!tree_fits_shwi_p (value))
10030 check_raw_data = true;
10031 --i;
10032 continue;
10035 /* Skip over embedded nuls except the last one (initializer
10036 elements are in ascending order of indices). */
10037 HOST_WIDE_INT val = tree_to_shwi (value);
10038 if (!val && i + 1 < nelts)
10039 continue;
10041 if (idx < str.length ())
10043 check_raw_data = true;
10044 continue;
10047 /* Bail if the CTOR has a block of more than 256 embedded nuls
10048 due to implicitly initialized elements. */
10049 unsigned nchars = (idx - str.length ()) + 1;
10050 if (nchars > 256)
10052 check_raw_data = true;
10053 continue;
10056 if (nchars > 1)
10058 str.reserve (idx);
10059 str.quick_grow_cleared (idx);
10062 if (idx >= maxelts)
10064 check_raw_data = true;
10065 continue;
10068 str.safe_insert (idx, val);
10071 if (check_raw_data)
10073 if (j != HOST_WIDE_INT_M1U)
10074 CONSTRUCTOR_ELTS (ctor)->truncate (j);
10075 return ctor;
10078 /* Append a nul string termination. */
10079 if (maxelts != HOST_WIDE_INT_M1U && str.length () < maxelts)
10080 str.safe_push (0);
10082 /* Build a STRING_CST with the same type as the array. */
10083 tree res = build_string (str.length (), str.begin ());
10084 TREE_TYPE (res) = type;
10085 return res;
10088 /* Implementation of the two-argument braced_lists_to_string withe
10089 the same arguments plus MEMBER which is set for struct members
10090 to allow initializers for flexible member arrays. */
10092 static tree
10093 braced_lists_to_strings (tree type, tree ctor, bool member)
10095 if (TREE_CODE (ctor) != CONSTRUCTOR)
10096 return ctor;
10098 tree_code code = TREE_CODE (type);
10100 tree ttp;
10101 if (code == ARRAY_TYPE)
10102 ttp = TREE_TYPE (type);
10103 else if (code == RECORD_TYPE)
10105 ttp = TREE_TYPE (ctor);
10106 if (TREE_CODE (ttp) == ARRAY_TYPE)
10108 type = ttp;
10109 ttp = TREE_TYPE (ttp);
10112 else
10113 return ctor;
10115 if ((TREE_CODE (ttp) == ARRAY_TYPE || TREE_CODE (ttp) == INTEGER_TYPE)
10116 && TYPE_STRING_FLAG (ttp))
10117 return braced_list_to_string (type, ctor, member);
10119 code = TREE_CODE (ttp);
10120 if (code == ARRAY_TYPE || RECORD_OR_UNION_TYPE_P (ttp))
10122 bool rec = RECORD_OR_UNION_TYPE_P (ttp);
10124 /* Handle array of arrays or struct member initializers. */
10125 tree val;
10126 unsigned HOST_WIDE_INT idx;
10127 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, val)
10129 val = braced_lists_to_strings (ttp, val, rec);
10130 CONSTRUCTOR_ELT (ctor, idx)->value = val;
10134 return ctor;
10137 /* Attempt to convert a CTOR containing braced array initializer lists
10138 for array TYPE into one containing STRING_CSTs, for convenience and
10139 efficiency. Recurse for arrays of arrays and member initializers.
10140 Return the converted CTOR or STRING_CST on success or the original
10141 CTOR otherwise. */
10143 tree
10144 braced_lists_to_strings (tree type, tree ctor)
10146 return braced_lists_to_strings (type, ctor, false);
10150 /* Emit debug for functions before finalizing early debug. */
10152 void
10153 c_common_finalize_early_debug (void)
10155 /* Emit early debug for reachable functions, and by consequence,
10156 locally scoped symbols. Also emit debug for extern declared
10157 functions that are still reachable at this point. */
10158 struct cgraph_node *cnode;
10159 FOR_EACH_FUNCTION (cnode)
10160 if (!cnode->alias && !cnode->thunk
10161 && (cnode->has_gimple_body_p ()
10162 || !DECL_IS_UNDECLARED_BUILTIN (cnode->decl)))
10163 (*debug_hooks->early_global_decl) (cnode->decl);
10166 /* Determine whether TYPE is an ISO C99 flexible array member type "[]". */
10167 bool
10168 c_flexible_array_member_type_p (const_tree type)
10170 if (TREE_CODE (type) == ARRAY_TYPE
10171 && TYPE_SIZE (type) == NULL_TREE
10172 && TYPE_DOMAIN (type) != NULL_TREE
10173 && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL_TREE)
10174 return true;
10176 return false;
10179 /* Get the LEVEL of the strict_flex_array for the ARRAY_FIELD based on the
10180 values of attribute strict_flex_array and the flag_strict_flex_arrays. */
10181 unsigned int
10182 c_strict_flex_array_level_of (tree array_field)
10184 gcc_assert (TREE_CODE (array_field) == FIELD_DECL);
10185 unsigned int strict_flex_array_level = flag_strict_flex_arrays;
10187 tree attr_strict_flex_array
10188 = lookup_attribute ("strict_flex_array", DECL_ATTRIBUTES (array_field));
10189 /* If there is a strict_flex_array attribute attached to the field,
10190 override the flag_strict_flex_arrays. */
10191 if (attr_strict_flex_array)
10193 /* Get the value of the level first from the attribute. */
10194 unsigned HOST_WIDE_INT attr_strict_flex_array_level = 0;
10195 gcc_assert (TREE_VALUE (attr_strict_flex_array) != NULL_TREE);
10196 attr_strict_flex_array = TREE_VALUE (attr_strict_flex_array);
10197 gcc_assert (TREE_VALUE (attr_strict_flex_array) != NULL_TREE);
10198 attr_strict_flex_array = TREE_VALUE (attr_strict_flex_array);
10199 gcc_assert (tree_fits_uhwi_p (attr_strict_flex_array));
10200 attr_strict_flex_array_level = tree_to_uhwi (attr_strict_flex_array);
10202 /* The attribute has higher priority than flag_struct_flex_array. */
10203 strict_flex_array_level = attr_strict_flex_array_level;
10205 return strict_flex_array_level;
10208 /* Map from identifiers to booleans. Value is true for features, and
10209 false for extensions. Used to implement __has_{feature,extension}. */
10211 using feature_map_t = hash_map <tree, bool>;
10212 static feature_map_t *feature_map;
10214 /* Register a feature for __has_{feature,extension}. FEATURE_P is true
10215 if the feature identified by NAME is a feature (as opposed to an
10216 extension). */
10218 void
10219 c_common_register_feature (const char *name, bool feature_p)
10221 bool dup = feature_map->put (get_identifier (name), feature_p);
10222 gcc_checking_assert (!dup);
10225 /* Lazily initialize hash table for __has_{feature,extension},
10226 dispatching to the appropriate front end to register language-specific
10227 features. */
10229 static void
10230 init_has_feature ()
10232 gcc_checking_assert (!feature_map);
10233 feature_map = new feature_map_t;
10235 for (unsigned i = 0; i < ARRAY_SIZE (has_feature_table); i++)
10237 const hf_feature_info *info = has_feature_table + i;
10239 if ((info->flags & HF_FLAG_SANITIZE) && !(flag_sanitize & info->mask))
10240 continue;
10242 const bool feature_p = !(info->flags & HF_FLAG_EXT);
10243 c_common_register_feature (info->ident, feature_p);
10246 /* Register language-specific features. */
10247 c_family_register_lang_features ();
10250 /* If STRICT_P is true, evaluate __has_feature (IDENT).
10251 Otherwise, evaluate __has_extension (IDENT). */
10253 bool
10254 has_feature_p (const char *ident, bool strict_p)
10256 if (!feature_map)
10257 init_has_feature ();
10259 tree name = canonicalize_attr_name (get_identifier (ident));
10260 bool *feat_p = feature_map->get (name);
10261 if (!feat_p)
10262 return false;
10264 return !strict_p || *feat_p;
10267 /* This is the slow path of c-common.h's c_hardbool_type_attr. */
10269 tree
10270 c_hardbool_type_attr_1 (tree type, tree *false_value, tree *true_value)
10272 tree attr = lookup_attribute ("hardbool", TYPE_ATTRIBUTES (type));
10273 if (!attr)
10274 return attr;
10276 if (false_value)
10277 *false_value = TREE_VALUE (TYPE_VALUES (type));
10279 if (true_value)
10280 *true_value = TREE_VALUE (TREE_CHAIN (TYPE_VALUES (type)));
10282 return attr;
10285 #include "gt-c-family-c-common.h"