Make vectorizable_load/store handle IFN_MASK_LOAD/STORE
[official-gcc.git] / gcc / c-family / c-common.c
blob87bd326b5e41fec20615a2891648c71d00a9c648
1 /* Subroutines shared by all languages that are variants of C.
2 Copyright (C) 1992-2018 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #define GCC_C_COMMON_C
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "target.h"
26 #include "function.h"
27 #include "tree.h"
28 #include "memmodel.h"
29 #include "c-common.h"
30 #include "gimple-expr.h"
31 #include "tm_p.h"
32 #include "stringpool.h"
33 #include "cgraph.h"
34 #include "diagnostic.h"
35 #include "intl.h"
36 #include "stor-layout.h"
37 #include "calls.h"
38 #include "attribs.h"
39 #include "varasm.h"
40 #include "trans-mem.h"
41 #include "c-objc.h"
42 #include "common/common-target.h"
43 #include "langhooks.h"
44 #include "tree-inline.h"
45 #include "toplev.h"
46 #include "tree-iterator.h"
47 #include "opts.h"
48 #include "gimplify.h"
49 #include "substring-locations.h"
50 #include "spellcheck.h"
52 cpp_reader *parse_in; /* Declared in c-pragma.h. */
54 /* Mode used to build pointers (VOIDmode means ptr_mode). */
56 machine_mode c_default_pointer_mode = VOIDmode;
58 /* The following symbols are subsumed in the c_global_trees array, and
59 listed here individually for documentation purposes.
61 INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
63 tree short_integer_type_node;
64 tree long_integer_type_node;
65 tree long_long_integer_type_node;
67 tree short_unsigned_type_node;
68 tree long_unsigned_type_node;
69 tree long_long_unsigned_type_node;
71 tree truthvalue_type_node;
72 tree truthvalue_false_node;
73 tree truthvalue_true_node;
75 tree ptrdiff_type_node;
77 tree unsigned_char_type_node;
78 tree signed_char_type_node;
79 tree wchar_type_node;
81 tree char16_type_node;
82 tree char32_type_node;
84 tree float_type_node;
85 tree double_type_node;
86 tree long_double_type_node;
88 tree complex_integer_type_node;
89 tree complex_float_type_node;
90 tree complex_double_type_node;
91 tree complex_long_double_type_node;
93 tree dfloat32_type_node;
94 tree dfloat64_type_node;
95 tree_dfloat128_type_node;
97 tree intQI_type_node;
98 tree intHI_type_node;
99 tree intSI_type_node;
100 tree intDI_type_node;
101 tree intTI_type_node;
103 tree unsigned_intQI_type_node;
104 tree unsigned_intHI_type_node;
105 tree unsigned_intSI_type_node;
106 tree unsigned_intDI_type_node;
107 tree unsigned_intTI_type_node;
109 tree widest_integer_literal_type_node;
110 tree widest_unsigned_literal_type_node;
112 Nodes for types `void *' and `const void *'.
114 tree ptr_type_node, const_ptr_type_node;
116 Nodes for types `char *' and `const char *'.
118 tree string_type_node, const_string_type_node;
120 Type `char[SOMENUMBER]'.
121 Used when an array of char is needed and the size is irrelevant.
123 tree char_array_type_node;
125 Type `wchar_t[SOMENUMBER]' or something like it.
126 Used when a wide string literal is created.
128 tree wchar_array_type_node;
130 Type `char16_t[SOMENUMBER]' or something like it.
131 Used when a UTF-16 string literal is created.
133 tree char16_array_type_node;
135 Type `char32_t[SOMENUMBER]' or something like it.
136 Used when a UTF-32 string literal is created.
138 tree char32_array_type_node;
140 Type `int ()' -- used for implicit declaration of functions.
142 tree default_function_type;
144 A VOID_TYPE node, packaged in a TREE_LIST.
146 tree void_list_node;
148 The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
149 and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
150 VAR_DECLS, but C++ does.)
152 tree function_name_decl_node;
153 tree pretty_function_name_decl_node;
154 tree c99_function_name_decl_node;
156 Stack of nested function name VAR_DECLs.
158 tree saved_function_name_decls;
162 tree c_global_trees[CTI_MAX];
164 /* Switches common to the C front ends. */
166 /* Nonzero means don't output line number information. */
168 char flag_no_line_commands;
170 /* Nonzero causes -E output not to be done, but directives such as
171 #define that have side effects are still obeyed. */
173 char flag_no_output;
175 /* Nonzero means dump macros in some fashion. */
177 char flag_dump_macros;
179 /* Nonzero means pass #include lines through to the output. */
181 char flag_dump_includes;
183 /* Nonzero means process PCH files while preprocessing. */
185 bool flag_pch_preprocess;
187 /* The file name to which we should write a precompiled header, or
188 NULL if no header will be written in this compile. */
190 const char *pch_file;
192 /* Nonzero if an ISO standard was selected. It rejects macros in the
193 user's namespace. */
194 int flag_iso;
196 /* C/ObjC language option variables. */
199 /* Nonzero means allow type mismatches in conditional expressions;
200 just make their values `void'. */
202 int flag_cond_mismatch;
204 /* Nonzero means enable C89 Amendment 1 features. */
206 int flag_isoc94;
208 /* Nonzero means use the ISO C99 (or C11) dialect of C. */
210 int flag_isoc99;
212 /* Nonzero means use the ISO C11 dialect of C. */
214 int flag_isoc11;
216 /* Nonzero means that we have builtin functions, and main is an int. */
218 int flag_hosted = 1;
221 /* ObjC language option variables. */
224 /* Tells the compiler that this is a special run. Do not perform any
225 compiling, instead we are to test some platform dependent features
226 and output a C header file with appropriate definitions. */
228 int print_struct_values;
230 /* Tells the compiler what is the constant string class for ObjC. */
232 const char *constant_string_class_name;
235 /* C++ language option variables. */
237 /* The reference version of the ABI for -Wabi. */
239 int warn_abi_version = -1;
241 /* Nonzero means generate separate instantiation control files and
242 juggle them at link time. */
244 int flag_use_repository;
246 /* The C++ dialect being used. Default set in c_common_post_options. */
248 enum cxx_dialect cxx_dialect = cxx_unset;
250 /* Maximum template instantiation depth. This limit exists to limit the
251 time it takes to notice excessively recursive template instantiations.
253 The default is lower than the 1024 recommended by the C++0x standard
254 because G++ runs out of stack before 1024 with highly recursive template
255 argument deduction substitution (g++.dg/cpp0x/enum11.C). */
257 int max_tinst_depth = 900;
259 /* The elements of `ridpointers' are identifier nodes for the reserved
260 type names and storage classes. It is indexed by a RID_... value. */
261 tree *ridpointers;
263 tree (*make_fname_decl) (location_t, tree, int);
265 /* Nonzero means don't warn about problems that occur when the code is
266 executed. */
267 int c_inhibit_evaluation_warnings;
269 /* Whether we are building a boolean conversion inside
270 convert_for_assignment, or some other late binary operation. If
271 build_binary_op is called for C (from code shared by C and C++) in
272 this case, then the operands have already been folded and the
273 result will not be folded again, so C_MAYBE_CONST_EXPR should not
274 be generated. */
275 bool in_late_binary_op;
277 /* Whether lexing has been completed, so subsequent preprocessor
278 errors should use the compiler's input_location. */
279 bool done_lexing = false;
281 /* Information about how a function name is generated. */
282 struct fname_var_t
284 tree *const decl; /* pointer to the VAR_DECL. */
285 const unsigned rid; /* RID number for the identifier. */
286 const int pretty; /* How pretty is it? */
289 /* The three ways of getting then name of the current function. */
291 const struct fname_var_t fname_vars[] =
293 /* C99 compliant __func__, must be first. */
294 {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
295 /* GCC __FUNCTION__ compliant. */
296 {&function_name_decl_node, RID_FUNCTION_NAME, 0},
297 /* GCC __PRETTY_FUNCTION__ compliant. */
298 {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
299 {NULL, 0, 0},
302 /* Global visibility options. */
303 struct visibility_flags visibility_options;
305 static tree check_case_value (location_t, tree);
306 static bool check_case_bounds (location_t, tree, tree, tree *, tree *,
307 bool *);
310 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
311 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
313 /* Reserved words. The third field is a mask: keywords are disabled
314 if they match the mask.
316 Masks for languages:
317 C --std=c89: D_C99 | D_CXXONLY | D_OBJC | D_CXX_OBJC
318 C --std=c99: D_CXXONLY | D_OBJC
319 ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
320 C++ --std=c++98: D_CONLY | D_CXX11 | D_OBJC
321 C++ --std=c++11: D_CONLY | D_OBJC
322 ObjC++ is like C++ except that D_OBJC is not set
324 If -fno-asm is used, D_ASM is added to the mask. If
325 -fno-gnu-keywords is used, D_EXT is added. If -fno-asm and C in
326 C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
327 In C with -Wc++-compat, we warn if D_CXXWARN is set.
329 Note the complication of the D_CXX_OBJC keywords. These are
330 reserved words such as 'class'. In C++, 'class' is a reserved
331 word. In Objective-C++ it is too. In Objective-C, it is a
332 reserved word too, but only if it follows an '@' sign.
334 const struct c_common_resword c_common_reswords[] =
336 { "_Alignas", RID_ALIGNAS, D_CONLY },
337 { "_Alignof", RID_ALIGNOF, D_CONLY },
338 { "_Atomic", RID_ATOMIC, D_CONLY },
339 { "_Bool", RID_BOOL, D_CONLY },
340 { "_Complex", RID_COMPLEX, 0 },
341 { "_Imaginary", RID_IMAGINARY, D_CONLY },
342 { "_Float16", RID_FLOAT16, D_CONLY },
343 { "_Float32", RID_FLOAT32, D_CONLY },
344 { "_Float64", RID_FLOAT64, D_CONLY },
345 { "_Float128", RID_FLOAT128, D_CONLY },
346 { "_Float32x", RID_FLOAT32X, D_CONLY },
347 { "_Float64x", RID_FLOAT64X, D_CONLY },
348 { "_Float128x", RID_FLOAT128X, D_CONLY },
349 { "_Decimal32", RID_DFLOAT32, D_CONLY | D_EXT },
350 { "_Decimal64", RID_DFLOAT64, D_CONLY | D_EXT },
351 { "_Decimal128", RID_DFLOAT128, D_CONLY | D_EXT },
352 { "_Fract", RID_FRACT, D_CONLY | D_EXT },
353 { "_Accum", RID_ACCUM, D_CONLY | D_EXT },
354 { "_Sat", RID_SAT, D_CONLY | D_EXT },
355 { "_Static_assert", RID_STATIC_ASSERT, D_CONLY },
356 { "_Noreturn", RID_NORETURN, D_CONLY },
357 { "_Generic", RID_GENERIC, D_CONLY },
358 { "_Thread_local", RID_THREAD, D_CONLY },
359 { "__FUNCTION__", RID_FUNCTION_NAME, 0 },
360 { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
361 { "__alignof", RID_ALIGNOF, 0 },
362 { "__alignof__", RID_ALIGNOF, 0 },
363 { "__asm", RID_ASM, 0 },
364 { "__asm__", RID_ASM, 0 },
365 { "__attribute", RID_ATTRIBUTE, 0 },
366 { "__attribute__", RID_ATTRIBUTE, 0 },
367 { "__auto_type", RID_AUTO_TYPE, D_CONLY },
368 { "__bases", RID_BASES, D_CXXONLY },
369 { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
370 { "__builtin_call_with_static_chain",
371 RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
372 { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
373 { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
374 { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
375 { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
376 { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
377 { "__builtin_offsetof", RID_OFFSETOF, 0 },
378 { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
379 { "__builtin_va_arg", RID_VA_ARG, 0 },
380 { "__complex", RID_COMPLEX, 0 },
381 { "__complex__", RID_COMPLEX, 0 },
382 { "__const", RID_CONST, 0 },
383 { "__const__", RID_CONST, 0 },
384 { "__decltype", RID_DECLTYPE, D_CXXONLY },
385 { "__direct_bases", RID_DIRECT_BASES, D_CXXONLY },
386 { "__extension__", RID_EXTENSION, 0 },
387 { "__func__", RID_C99_FUNCTION_NAME, 0 },
388 { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
389 { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
390 { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
391 { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
392 { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
393 { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
394 { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
395 { "__has_unique_object_representations", RID_HAS_UNIQUE_OBJ_REPRESENTATIONS,
396 D_CXXONLY },
397 { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
398 { "__imag", RID_IMAGPART, 0 },
399 { "__imag__", RID_IMAGPART, 0 },
400 { "__inline", RID_INLINE, 0 },
401 { "__inline__", RID_INLINE, 0 },
402 { "__is_abstract", RID_IS_ABSTRACT, D_CXXONLY },
403 { "__is_aggregate", RID_IS_AGGREGATE, D_CXXONLY },
404 { "__is_base_of", RID_IS_BASE_OF, D_CXXONLY },
405 { "__is_class", RID_IS_CLASS, D_CXXONLY },
406 { "__is_empty", RID_IS_EMPTY, D_CXXONLY },
407 { "__is_enum", RID_IS_ENUM, D_CXXONLY },
408 { "__is_final", RID_IS_FINAL, D_CXXONLY },
409 { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
410 { "__is_pod", RID_IS_POD, D_CXXONLY },
411 { "__is_polymorphic", RID_IS_POLYMORPHIC, D_CXXONLY },
412 { "__is_same_as", RID_IS_SAME_AS, D_CXXONLY },
413 { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
414 { "__is_trivial", RID_IS_TRIVIAL, D_CXXONLY },
415 { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
416 { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
417 { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
418 { "__is_union", RID_IS_UNION, D_CXXONLY },
419 { "__label__", RID_LABEL, 0 },
420 { "__null", RID_NULL, 0 },
421 { "__real", RID_REALPART, 0 },
422 { "__real__", RID_REALPART, 0 },
423 { "__restrict", RID_RESTRICT, 0 },
424 { "__restrict__", RID_RESTRICT, 0 },
425 { "__signed", RID_SIGNED, 0 },
426 { "__signed__", RID_SIGNED, 0 },
427 { "__thread", RID_THREAD, 0 },
428 { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
429 { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
430 { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
431 { "__typeof", RID_TYPEOF, 0 },
432 { "__typeof__", RID_TYPEOF, 0 },
433 { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
434 { "__volatile", RID_VOLATILE, 0 },
435 { "__volatile__", RID_VOLATILE, 0 },
436 { "__GIMPLE", RID_GIMPLE, D_CONLY },
437 { "__PHI", RID_PHI, D_CONLY },
438 { "__RTL", RID_RTL, D_CONLY },
439 { "alignas", RID_ALIGNAS, D_CXXONLY | D_CXX11 | D_CXXWARN },
440 { "alignof", RID_ALIGNOF, D_CXXONLY | D_CXX11 | D_CXXWARN },
441 { "asm", RID_ASM, D_ASM },
442 { "auto", RID_AUTO, 0 },
443 { "bool", RID_BOOL, D_CXXONLY | D_CXXWARN },
444 { "break", RID_BREAK, 0 },
445 { "case", RID_CASE, 0 },
446 { "catch", RID_CATCH, D_CXX_OBJC | D_CXXWARN },
447 { "char", RID_CHAR, 0 },
448 { "char16_t", RID_CHAR16, D_CXXONLY | D_CXX11 | D_CXXWARN },
449 { "char32_t", RID_CHAR32, D_CXXONLY | D_CXX11 | D_CXXWARN },
450 { "class", RID_CLASS, D_CXX_OBJC | D_CXXWARN },
451 { "const", RID_CONST, 0 },
452 { "constexpr", RID_CONSTEXPR, D_CXXONLY | D_CXX11 | D_CXXWARN },
453 { "const_cast", RID_CONSTCAST, D_CXXONLY | D_CXXWARN },
454 { "continue", RID_CONTINUE, 0 },
455 { "decltype", RID_DECLTYPE, D_CXXONLY | D_CXX11 | D_CXXWARN },
456 { "default", RID_DEFAULT, 0 },
457 { "delete", RID_DELETE, D_CXXONLY | D_CXXWARN },
458 { "do", RID_DO, 0 },
459 { "double", RID_DOUBLE, 0 },
460 { "dynamic_cast", RID_DYNCAST, D_CXXONLY | D_CXXWARN },
461 { "else", RID_ELSE, 0 },
462 { "enum", RID_ENUM, 0 },
463 { "explicit", RID_EXPLICIT, D_CXXONLY | D_CXXWARN },
464 { "export", RID_EXPORT, D_CXXONLY | D_CXXWARN },
465 { "extern", RID_EXTERN, 0 },
466 { "false", RID_FALSE, D_CXXONLY | D_CXXWARN },
467 { "float", RID_FLOAT, 0 },
468 { "for", RID_FOR, 0 },
469 { "friend", RID_FRIEND, D_CXXONLY | D_CXXWARN },
470 { "goto", RID_GOTO, 0 },
471 { "if", RID_IF, 0 },
472 { "inline", RID_INLINE, D_EXT89 },
473 { "int", RID_INT, 0 },
474 { "long", RID_LONG, 0 },
475 { "mutable", RID_MUTABLE, D_CXXONLY | D_CXXWARN },
476 { "namespace", RID_NAMESPACE, D_CXXONLY | D_CXXWARN },
477 { "new", RID_NEW, D_CXXONLY | D_CXXWARN },
478 { "noexcept", RID_NOEXCEPT, D_CXXONLY | D_CXX11 | D_CXXWARN },
479 { "nullptr", RID_NULLPTR, D_CXXONLY | D_CXX11 | D_CXXWARN },
480 { "operator", RID_OPERATOR, D_CXXONLY | D_CXXWARN },
481 { "private", RID_PRIVATE, D_CXX_OBJC | D_CXXWARN },
482 { "protected", RID_PROTECTED, D_CXX_OBJC | D_CXXWARN },
483 { "public", RID_PUBLIC, D_CXX_OBJC | D_CXXWARN },
484 { "register", RID_REGISTER, 0 },
485 { "reinterpret_cast", RID_REINTCAST, D_CXXONLY | D_CXXWARN },
486 { "restrict", RID_RESTRICT, D_CONLY | D_C99 },
487 { "return", RID_RETURN, 0 },
488 { "short", RID_SHORT, 0 },
489 { "signed", RID_SIGNED, 0 },
490 { "sizeof", RID_SIZEOF, 0 },
491 { "static", RID_STATIC, 0 },
492 { "static_assert", RID_STATIC_ASSERT, D_CXXONLY | D_CXX11 | D_CXXWARN },
493 { "static_cast", RID_STATCAST, D_CXXONLY | D_CXXWARN },
494 { "struct", RID_STRUCT, 0 },
495 { "switch", RID_SWITCH, 0 },
496 { "template", RID_TEMPLATE, D_CXXONLY | D_CXXWARN },
497 { "this", RID_THIS, D_CXXONLY | D_CXXWARN },
498 { "thread_local", RID_THREAD, D_CXXONLY | D_CXX11 | D_CXXWARN },
499 { "throw", RID_THROW, D_CXX_OBJC | D_CXXWARN },
500 { "true", RID_TRUE, D_CXXONLY | D_CXXWARN },
501 { "try", RID_TRY, D_CXX_OBJC | D_CXXWARN },
502 { "typedef", RID_TYPEDEF, 0 },
503 { "typename", RID_TYPENAME, D_CXXONLY | D_CXXWARN },
504 { "typeid", RID_TYPEID, D_CXXONLY | D_CXXWARN },
505 { "typeof", RID_TYPEOF, D_ASM | D_EXT },
506 { "union", RID_UNION, 0 },
507 { "unsigned", RID_UNSIGNED, 0 },
508 { "using", RID_USING, D_CXXONLY | D_CXXWARN },
509 { "virtual", RID_VIRTUAL, D_CXXONLY | D_CXXWARN },
510 { "void", RID_VOID, 0 },
511 { "volatile", RID_VOLATILE, 0 },
512 { "wchar_t", RID_WCHAR, D_CXXONLY },
513 { "while", RID_WHILE, 0 },
514 { "__is_assignable", RID_IS_ASSIGNABLE, D_CXXONLY },
515 { "__is_constructible", RID_IS_CONSTRUCTIBLE, D_CXXONLY },
517 /* C++ transactional memory. */
518 { "synchronized", RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
519 { "atomic_noexcept", RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
520 { "atomic_cancel", RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
521 { "atomic_commit", RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
523 /* Concepts-related keywords */
524 { "concept", RID_CONCEPT, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
525 { "requires", RID_REQUIRES, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
527 /* These Objective-C keywords are recognized only immediately after
528 an '@'. */
529 { "compatibility_alias", RID_AT_ALIAS, D_OBJC },
530 { "defs", RID_AT_DEFS, D_OBJC },
531 { "encode", RID_AT_ENCODE, D_OBJC },
532 { "end", RID_AT_END, D_OBJC },
533 { "implementation", RID_AT_IMPLEMENTATION, D_OBJC },
534 { "interface", RID_AT_INTERFACE, D_OBJC },
535 { "protocol", RID_AT_PROTOCOL, D_OBJC },
536 { "selector", RID_AT_SELECTOR, D_OBJC },
537 { "finally", RID_AT_FINALLY, D_OBJC },
538 { "optional", RID_AT_OPTIONAL, D_OBJC },
539 { "required", RID_AT_REQUIRED, D_OBJC },
540 { "property", RID_AT_PROPERTY, D_OBJC },
541 { "package", RID_AT_PACKAGE, D_OBJC },
542 { "synthesize", RID_AT_SYNTHESIZE, D_OBJC },
543 { "dynamic", RID_AT_DYNAMIC, D_OBJC },
544 /* These are recognized only in protocol-qualifier context
545 (see above) */
546 { "bycopy", RID_BYCOPY, D_OBJC },
547 { "byref", RID_BYREF, D_OBJC },
548 { "in", RID_IN, D_OBJC },
549 { "inout", RID_INOUT, D_OBJC },
550 { "oneway", RID_ONEWAY, D_OBJC },
551 { "out", RID_OUT, D_OBJC },
552 /* These are recognized inside a property attribute list */
553 { "assign", RID_ASSIGN, D_OBJC },
554 { "copy", RID_COPY, D_OBJC },
555 { "getter", RID_GETTER, D_OBJC },
556 { "nonatomic", RID_NONATOMIC, D_OBJC },
557 { "readonly", RID_READONLY, D_OBJC },
558 { "readwrite", RID_READWRITE, D_OBJC },
559 { "retain", RID_RETAIN, D_OBJC },
560 { "setter", RID_SETTER, D_OBJC },
563 const unsigned int num_c_common_reswords =
564 sizeof c_common_reswords / sizeof (struct c_common_resword);
566 /* Return identifier for address space AS. */
568 const char *
569 c_addr_space_name (addr_space_t as)
571 int rid = RID_FIRST_ADDR_SPACE + as;
572 gcc_assert (ridpointers [rid]);
573 return IDENTIFIER_POINTER (ridpointers [rid]);
576 /* Push current bindings for the function name VAR_DECLS. */
578 void
579 start_fname_decls (void)
581 unsigned ix;
582 tree saved = NULL_TREE;
584 for (ix = 0; fname_vars[ix].decl; ix++)
586 tree decl = *fname_vars[ix].decl;
588 if (decl)
590 saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
591 saved);
592 *fname_vars[ix].decl = NULL_TREE;
595 if (saved || saved_function_name_decls)
596 /* Normally they'll have been NULL, so only push if we've got a
597 stack, or they are non-NULL. */
598 saved_function_name_decls = tree_cons (saved, NULL_TREE,
599 saved_function_name_decls);
602 /* Finish up the current bindings, adding them into the current function's
603 statement tree. This must be done _before_ finish_stmt_tree is called.
604 If there is no current function, we must be at file scope and no statements
605 are involved. Pop the previous bindings. */
607 void
608 finish_fname_decls (void)
610 unsigned ix;
611 tree stmts = NULL_TREE;
612 tree stack = saved_function_name_decls;
614 for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
615 append_to_statement_list (TREE_VALUE (stack), &stmts);
617 if (stmts)
619 tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
621 if (TREE_CODE (*bodyp) == BIND_EXPR)
622 bodyp = &BIND_EXPR_BODY (*bodyp);
624 append_to_statement_list_force (*bodyp, &stmts);
625 *bodyp = stmts;
628 for (ix = 0; fname_vars[ix].decl; ix++)
629 *fname_vars[ix].decl = NULL_TREE;
631 if (stack)
633 /* We had saved values, restore them. */
634 tree saved;
636 for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
638 tree decl = TREE_PURPOSE (saved);
639 unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
641 *fname_vars[ix].decl = decl;
643 stack = TREE_CHAIN (stack);
645 saved_function_name_decls = stack;
648 /* Return the text name of the current function, suitably prettified
649 by PRETTY_P. Return string must be freed by caller. */
651 const char *
652 fname_as_string (int pretty_p)
654 const char *name = "top level";
655 char *namep;
656 int vrb = 2, len;
657 cpp_string cstr = { 0, 0 }, strname;
659 if (!pretty_p)
661 name = "";
662 vrb = 0;
665 if (current_function_decl)
666 name = lang_hooks.decl_printable_name (current_function_decl, vrb);
668 len = strlen (name) + 3; /* Two for '"'s. One for NULL. */
670 namep = XNEWVEC (char, len);
671 snprintf (namep, len, "\"%s\"", name);
672 strname.text = (unsigned char *) namep;
673 strname.len = len - 1;
675 if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
677 XDELETEVEC (namep);
678 return (const char *) cstr.text;
681 return namep;
684 /* Return the VAR_DECL for a const char array naming the current
685 function. If the VAR_DECL has not yet been created, create it
686 now. RID indicates how it should be formatted and IDENTIFIER_NODE
687 ID is its name (unfortunately C and C++ hold the RID values of
688 keywords in different places, so we can't derive RID from ID in
689 this language independent code. LOC is the location of the
690 function. */
692 tree
693 fname_decl (location_t loc, unsigned int rid, tree id)
695 unsigned ix;
696 tree decl = NULL_TREE;
698 for (ix = 0; fname_vars[ix].decl; ix++)
699 if (fname_vars[ix].rid == rid)
700 break;
702 decl = *fname_vars[ix].decl;
703 if (!decl)
705 /* If a tree is built here, it would normally have the lineno of
706 the current statement. Later this tree will be moved to the
707 beginning of the function and this line number will be wrong.
708 To avoid this problem set the lineno to 0 here; that prevents
709 it from appearing in the RTL. */
710 tree stmts;
711 location_t saved_location = input_location;
712 input_location = UNKNOWN_LOCATION;
714 stmts = push_stmt_list ();
715 decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
716 stmts = pop_stmt_list (stmts);
717 if (!IS_EMPTY_STMT (stmts))
718 saved_function_name_decls
719 = tree_cons (decl, stmts, saved_function_name_decls);
720 *fname_vars[ix].decl = decl;
721 input_location = saved_location;
723 if (!ix && !current_function_decl)
724 pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
726 return decl;
729 /* Given a STRING_CST, give it a suitable array-of-chars data type. */
731 tree
732 fix_string_type (tree value)
734 int length = TREE_STRING_LENGTH (value);
735 int nchars;
736 tree e_type, i_type, a_type;
738 /* Compute the number of elements, for the array type. */
739 if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
741 nchars = length;
742 e_type = char_type_node;
744 else if (TREE_TYPE (value) == char16_array_type_node)
746 nchars = length / (TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT);
747 e_type = char16_type_node;
749 else if (TREE_TYPE (value) == char32_array_type_node)
751 nchars = length / (TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT);
752 e_type = char32_type_node;
754 else
756 nchars = length / (TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT);
757 e_type = wchar_type_node;
760 /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits). The analogous
761 limit in C++98 Annex B is very large (65536) and is not normative,
762 so we do not diagnose it (warn_overlength_strings is forced off
763 in c_common_post_options). */
764 if (warn_overlength_strings)
766 const int nchars_max = flag_isoc99 ? 4095 : 509;
767 const int relevant_std = flag_isoc99 ? 99 : 90;
768 if (nchars - 1 > nchars_max)
769 /* Translators: The %d after 'ISO C' will be 90 or 99. Do not
770 separate the %d from the 'C'. 'ISO' should not be
771 translated, but it may be moved after 'C%d' in languages
772 where modifiers follow nouns. */
773 pedwarn (input_location, OPT_Woverlength_strings,
774 "string length %qd is greater than the length %qd "
775 "ISO C%d compilers are required to support",
776 nchars - 1, nchars_max, relevant_std);
779 /* Create the array type for the string constant. The ISO C++
780 standard says that a string literal has type `const char[N]' or
781 `const wchar_t[N]'. We use the same logic when invoked as a C
782 front-end with -Wwrite-strings.
783 ??? We should change the type of an expression depending on the
784 state of a warning flag. We should just be warning -- see how
785 this is handled in the C++ front-end for the deprecated implicit
786 conversion from string literals to `char*' or `wchar_t*'.
788 The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
789 array type being the unqualified version of that type.
790 Therefore, if we are constructing an array of const char, we must
791 construct the matching unqualified array type first. The C front
792 end does not require this, but it does no harm, so we do it
793 unconditionally. */
794 i_type = build_index_type (size_int (nchars - 1));
795 a_type = build_array_type (e_type, i_type);
796 if (c_dialect_cxx() || warn_write_strings)
797 a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
799 TREE_TYPE (value) = a_type;
800 TREE_CONSTANT (value) = 1;
801 TREE_READONLY (value) = 1;
802 TREE_STATIC (value) = 1;
803 return value;
806 /* Given a string of type STRING_TYPE, determine what kind of string
807 token would give an equivalent execution encoding: CPP_STRING,
808 CPP_STRING16, or CPP_STRING32. Return CPP_OTHER in case of error.
809 This may not be exactly the string token type that initially created
810 the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
811 string type at this point.
813 This effectively reverses part of the logic in lex_string and
814 fix_string_type. */
816 static enum cpp_ttype
817 get_cpp_ttype_from_string_type (tree string_type)
819 gcc_assert (string_type);
820 if (TREE_CODE (string_type) == POINTER_TYPE)
821 string_type = TREE_TYPE (string_type);
823 if (TREE_CODE (string_type) != ARRAY_TYPE)
824 return CPP_OTHER;
826 tree element_type = TREE_TYPE (string_type);
827 if (TREE_CODE (element_type) != INTEGER_TYPE)
828 return CPP_OTHER;
830 int bits_per_character = TYPE_PRECISION (element_type);
831 switch (bits_per_character)
833 case 8:
834 return CPP_STRING; /* It could have also been CPP_UTF8STRING. */
835 case 16:
836 return CPP_STRING16;
837 case 32:
838 return CPP_STRING32;
841 return CPP_OTHER;
844 /* The global record of string concatentations, for use in
845 extracting locations within string literals. */
847 GTY(()) string_concat_db *g_string_concat_db;
849 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION. */
851 const char *
852 c_get_substring_location (const substring_loc &substr_loc,
853 location_t *out_loc)
855 enum cpp_ttype tok_type
856 = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
857 if (tok_type == CPP_OTHER)
858 return "unrecognized string type";
860 return get_source_location_for_substring (parse_in, g_string_concat_db,
861 substr_loc.get_fmt_string_loc (),
862 tok_type,
863 substr_loc.get_caret_idx (),
864 substr_loc.get_start_idx (),
865 substr_loc.get_end_idx (),
866 out_loc);
870 /* Fold X for consideration by one of the warning functions when checking
871 whether an expression has a constant value. */
873 tree
874 fold_for_warn (tree x)
876 if (c_dialect_cxx ())
877 return c_fully_fold (x, /*for_init*/false, /*maybe_constp*/NULL);
878 else
879 /* The C front-end has already folded X appropriately. */
880 return x;
883 /* Return true iff T is a boolean promoted to int. */
885 bool
886 bool_promoted_to_int_p (tree t)
888 return (CONVERT_EXPR_P (t)
889 && TREE_TYPE (t) == integer_type_node
890 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
893 /* vector_targets_convertible_p is used for vector pointer types. The
894 callers perform various checks that the qualifiers are satisfactory,
895 while OTOH vector_targets_convertible_p ignores the number of elements
896 in the vectors. That's fine with vector pointers as we can consider,
897 say, a vector of 8 elements as two consecutive vectors of 4 elements,
898 and that does not require and conversion of the pointer values.
899 In contrast, vector_types_convertible_p and
900 vector_types_compatible_elements_p are used for vector value types. */
901 /* True if pointers to distinct types T1 and T2 can be converted to
902 each other without an explicit cast. Only returns true for opaque
903 vector types. */
904 bool
905 vector_targets_convertible_p (const_tree t1, const_tree t2)
907 if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
908 && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
909 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
910 return true;
912 return false;
915 /* vector_types_convertible_p is used for vector value types.
916 It could in principle call vector_targets_convertible_p as a subroutine,
917 but then the check for vector type would be duplicated with its callers,
918 and also the purpose of vector_targets_convertible_p would become
919 muddled.
920 Where vector_types_convertible_p returns true, a conversion might still be
921 needed to make the types match.
922 In contrast, vector_targets_convertible_p is used for vector pointer
923 values, and vector_types_compatible_elements_p is used specifically
924 in the context for binary operators, as a check if use is possible without
925 conversion. */
926 /* True if vector types T1 and T2 can be converted to each other
927 without an explicit cast. If EMIT_LAX_NOTE is true, and T1 and T2
928 can only be converted with -flax-vector-conversions yet that is not
929 in effect, emit a note telling the user about that option if such
930 a note has not previously been emitted. */
931 bool
932 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
934 static bool emitted_lax_note = false;
935 bool convertible_lax;
937 if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
938 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
939 return true;
941 convertible_lax =
942 (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
943 && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
944 || known_eq (TYPE_VECTOR_SUBPARTS (t1),
945 TYPE_VECTOR_SUBPARTS (t2)))
946 && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
947 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
949 if (!convertible_lax || flag_lax_vector_conversions)
950 return convertible_lax;
952 if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
953 && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
954 return true;
956 if (emit_lax_note && !emitted_lax_note)
958 emitted_lax_note = true;
959 inform (input_location, "use -flax-vector-conversions to permit "
960 "conversions between vectors with differing "
961 "element types or numbers of subparts");
964 return false;
967 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
968 and have vector types, V0 has the same type as V1, and the number of
969 elements of V0, V1, MASK is the same.
971 In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
972 called with two arguments. In this case implementation passes the
973 first argument twice in order to share the same tree code. This fact
974 could enable the mask-values being twice the vector length. This is
975 an implementation accident and this semantics is not guaranteed to
976 the user. */
977 tree
978 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
979 bool complain)
981 tree ret;
982 bool wrap = true;
983 bool maybe_const = false;
984 bool two_arguments = false;
986 if (v1 == NULL_TREE)
988 two_arguments = true;
989 v1 = v0;
992 if (v0 == error_mark_node || v1 == error_mark_node
993 || mask == error_mark_node)
994 return error_mark_node;
996 if (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
998 if (complain)
999 error_at (loc, "__builtin_shuffle last argument must "
1000 "be an integer vector");
1001 return error_mark_node;
1004 if (!VECTOR_TYPE_P (TREE_TYPE (v0))
1005 || !VECTOR_TYPE_P (TREE_TYPE (v1)))
1007 if (complain)
1008 error_at (loc, "__builtin_shuffle arguments must be vectors");
1009 return error_mark_node;
1012 if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1014 if (complain)
1015 error_at (loc, "__builtin_shuffle argument vectors must be of "
1016 "the same type");
1017 return error_mark_node;
1020 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1021 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1022 && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1023 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1025 if (complain)
1026 error_at (loc, "__builtin_shuffle number of elements of the "
1027 "argument vector(s) and the mask vector should "
1028 "be the same");
1029 return error_mark_node;
1032 if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1033 != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1035 if (complain)
1036 error_at (loc, "__builtin_shuffle argument vector(s) inner type "
1037 "must have the same size as inner type of the mask");
1038 return error_mark_node;
1041 if (!c_dialect_cxx ())
1043 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1044 v0 = c_fully_fold (v0, false, &maybe_const);
1045 wrap &= maybe_const;
1047 if (two_arguments)
1048 v1 = v0 = save_expr (v0);
1049 else
1051 v1 = c_fully_fold (v1, false, &maybe_const);
1052 wrap &= maybe_const;
1055 mask = c_fully_fold (mask, false, &maybe_const);
1056 wrap &= maybe_const;
1058 else if (two_arguments)
1059 v1 = v0 = save_expr (v0);
1061 ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1063 if (!c_dialect_cxx () && !wrap)
1064 ret = c_wrap_maybe_const (ret, true);
1066 return ret;
1069 /* Like tree.c:get_narrower, but retain conversion from C++0x scoped enum
1070 to integral type. */
1072 tree
1073 c_common_get_narrower (tree op, int *unsignedp_ptr)
1075 op = get_narrower (op, unsignedp_ptr);
1077 if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1078 && ENUM_IS_SCOPED (TREE_TYPE (op)))
1080 /* C++0x scoped enumerations don't implicitly convert to integral
1081 type; if we stripped an explicit conversion to a larger type we
1082 need to replace it so common_type will still work. */
1083 tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1084 TYPE_UNSIGNED (TREE_TYPE (op)));
1085 op = fold_convert (type, op);
1087 return op;
1090 /* This is a helper function of build_binary_op.
1092 For certain operations if both args were extended from the same
1093 smaller type, do the arithmetic in that type and then extend.
1095 BITWISE indicates a bitwise operation.
1096 For them, this optimization is safe only if
1097 both args are zero-extended or both are sign-extended.
1098 Otherwise, we might change the result.
1099 Eg, (short)-1 | (unsigned short)-1 is (int)-1
1100 but calculated in (unsigned short) it would be (unsigned short)-1.
1102 tree
1103 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1105 int unsigned0, unsigned1;
1106 tree arg0, arg1;
1107 int uns;
1108 tree type;
1110 /* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
1111 excessive narrowing when we call get_narrower below. For
1112 example, suppose that OP0 is of unsigned int extended
1113 from signed char and that RESULT_TYPE is long long int.
1114 If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1115 like
1117 (long long int) (unsigned int) signed_char
1119 which get_narrower would narrow down to
1121 (unsigned int) signed char
1123 If we do not cast OP0 first, get_narrower would return
1124 signed_char, which is inconsistent with the case of the
1125 explicit cast. */
1126 op0 = convert (result_type, op0);
1127 op1 = convert (result_type, op1);
1129 arg0 = c_common_get_narrower (op0, &unsigned0);
1130 arg1 = c_common_get_narrower (op1, &unsigned1);
1132 /* UNS is 1 if the operation to be done is an unsigned one. */
1133 uns = TYPE_UNSIGNED (result_type);
1135 /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1136 but it *requires* conversion to FINAL_TYPE. */
1138 if ((TYPE_PRECISION (TREE_TYPE (op0))
1139 == TYPE_PRECISION (TREE_TYPE (arg0)))
1140 && TREE_TYPE (op0) != result_type)
1141 unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1142 if ((TYPE_PRECISION (TREE_TYPE (op1))
1143 == TYPE_PRECISION (TREE_TYPE (arg1)))
1144 && TREE_TYPE (op1) != result_type)
1145 unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1147 /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
1149 /* For bitwise operations, signedness of nominal type
1150 does not matter. Consider only how operands were extended. */
1151 if (bitwise)
1152 uns = unsigned0;
1154 /* Note that in all three cases below we refrain from optimizing
1155 an unsigned operation on sign-extended args.
1156 That would not be valid. */
1158 /* Both args variable: if both extended in same way
1159 from same width, do it in that width.
1160 Do it unsigned if args were zero-extended. */
1161 if ((TYPE_PRECISION (TREE_TYPE (arg0))
1162 < TYPE_PRECISION (result_type))
1163 && (TYPE_PRECISION (TREE_TYPE (arg1))
1164 == TYPE_PRECISION (TREE_TYPE (arg0)))
1165 && unsigned0 == unsigned1
1166 && (unsigned0 || !uns))
1167 return c_common_signed_or_unsigned_type
1168 (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
1170 else if (TREE_CODE (arg0) == INTEGER_CST
1171 && (unsigned1 || !uns)
1172 && (TYPE_PRECISION (TREE_TYPE (arg1))
1173 < TYPE_PRECISION (result_type))
1174 && (type
1175 = c_common_signed_or_unsigned_type (unsigned1,
1176 TREE_TYPE (arg1)))
1177 && !POINTER_TYPE_P (type)
1178 && int_fits_type_p (arg0, type))
1179 return type;
1181 else if (TREE_CODE (arg1) == INTEGER_CST
1182 && (unsigned0 || !uns)
1183 && (TYPE_PRECISION (TREE_TYPE (arg0))
1184 < TYPE_PRECISION (result_type))
1185 && (type
1186 = c_common_signed_or_unsigned_type (unsigned0,
1187 TREE_TYPE (arg0)))
1188 && !POINTER_TYPE_P (type)
1189 && int_fits_type_p (arg1, type))
1190 return type;
1192 return result_type;
1195 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1196 real of type TO_TYPE. This is a helper function for unsafe_conversion_p. */
1198 static bool
1199 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1201 tree type_low_bound = TYPE_MIN_VALUE (from_type);
1202 tree type_high_bound = TYPE_MAX_VALUE (from_type);
1203 REAL_VALUE_TYPE real_low_bound =
1204 real_value_from_int_cst (0, type_low_bound);
1205 REAL_VALUE_TYPE real_high_bound =
1206 real_value_from_int_cst (0, type_high_bound);
1208 return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1209 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1212 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1213 to the complex/real/integer type TYPE. Function returns non-zero when:
1214 * EXPR is a constant which cannot be exactly converted to TYPE.
1215 * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1216 for EXPR type and TYPE being both integers or both real, or both
1217 complex.
1218 * EXPR is not a constant of complex type and TYPE is a real or
1219 an integer.
1220 * EXPR is not a constant of real type and TYPE is an integer.
1221 * EXPR is not a constant of integer type which cannot be
1222 exactly converted to real type.
1224 Function allows conversions between types of different signedness and
1225 can return SAFE_CONVERSION (zero) in that case. Function can produce
1226 signedness warnings if PRODUCE_WARNS is true.
1228 RESULT, when non-null is the result of the conversion. When constant
1229 it is included in the text of diagnostics.
1231 Function allows conversions from complex constants to non-complex types,
1232 provided that imaginary part is zero and real part can be safely converted
1233 to TYPE. */
1235 enum conversion_safety
1236 unsafe_conversion_p (location_t loc, tree type, tree expr, tree result,
1237 bool produce_warns)
1239 enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1240 tree expr_type = TREE_TYPE (expr);
1242 bool cstresult = (result
1243 && TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant);
1245 loc = expansion_point_location_if_in_system_header (loc);
1247 if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1249 /* If type is complex, we are interested in compatibility with
1250 underlying type. */
1251 if (TREE_CODE (type) == COMPLEX_TYPE)
1252 type = TREE_TYPE (type);
1254 /* Warn for real constant that is not an exact integer converted
1255 to integer type. */
1256 if (TREE_CODE (expr_type) == REAL_TYPE
1257 && TREE_CODE (type) == INTEGER_TYPE)
1259 if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1260 give_warning = UNSAFE_REAL;
1262 /* Warn for an integer constant that does not fit into integer type. */
1263 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1264 && TREE_CODE (type) == INTEGER_TYPE
1265 && !int_fits_type_p (expr, type))
1267 if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1268 && tree_int_cst_sgn (expr) < 0)
1270 if (produce_warns)
1272 if (cstresult)
1273 warning_at (loc, OPT_Wsign_conversion,
1274 "unsigned conversion from %qT to %qT "
1275 "changes value from %qE to %qE",
1276 expr_type, type, expr, result);
1277 else
1278 warning_at (loc, OPT_Wsign_conversion,
1279 "unsigned conversion from %qT to %qT "
1280 "changes the value of %qE",
1281 expr_type, type, expr);
1284 else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1286 if (cstresult)
1287 warning_at (loc, OPT_Wsign_conversion,
1288 "signed conversion from %qT to %qT changes "
1289 "value from %qE to %qE",
1290 expr_type, type, expr, result);
1291 else
1292 warning_at (loc, OPT_Wsign_conversion,
1293 "signed conversion from %qT to %qT changes "
1294 "the value of %qE",
1295 expr_type, type, expr);
1297 else
1298 give_warning = UNSAFE_OTHER;
1300 else if (TREE_CODE (type) == REAL_TYPE)
1302 /* Warn for an integer constant that does not fit into real type. */
1303 if (TREE_CODE (expr_type) == INTEGER_TYPE)
1305 REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1306 if (!exact_real_truncate (TYPE_MODE (type), &a))
1307 give_warning = UNSAFE_REAL;
1309 /* Warn for a real constant that does not fit into a smaller
1310 real type. */
1311 else if (TREE_CODE (expr_type) == REAL_TYPE
1312 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1314 REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1315 if (!exact_real_truncate (TYPE_MODE (type), &a))
1316 give_warning = UNSAFE_REAL;
1321 else if (TREE_CODE (expr) == COMPLEX_CST)
1323 tree imag_part = TREE_IMAGPART (expr);
1324 /* Conversion from complex constant with zero imaginary part,
1325 perform check for conversion of real part. */
1326 if ((TREE_CODE (imag_part) == REAL_CST
1327 && real_zerop (imag_part))
1328 || (TREE_CODE (imag_part) == INTEGER_CST
1329 && integer_zerop (imag_part)))
1330 /* Note: in this branch we use recursive call to unsafe_conversion_p
1331 with different type of EXPR, but it is still safe, because when EXPR
1332 is a constant, it's type is not used in text of generated warnings
1333 (otherwise they could sound misleading). */
1334 return unsafe_conversion_p (loc, type, TREE_REALPART (expr), result,
1335 produce_warns);
1336 /* Conversion from complex constant with non-zero imaginary part. */
1337 else
1339 /* Conversion to complex type.
1340 Perform checks for both real and imaginary parts. */
1341 if (TREE_CODE (type) == COMPLEX_TYPE)
1343 /* Unfortunately, produce_warns must be false in two subsequent
1344 calls of unsafe_conversion_p, because otherwise we could
1345 produce strange "double" warnings, if both real and imaginary
1346 parts have conversion problems related to signedness.
1348 For example:
1349 int32_t _Complex a = 0x80000000 + 0x80000000i;
1351 Possible solution: add a separate function for checking
1352 constants and combine result of two calls appropriately. */
1353 enum conversion_safety re_safety =
1354 unsafe_conversion_p (loc, type, TREE_REALPART (expr),
1355 result, false);
1356 enum conversion_safety im_safety =
1357 unsafe_conversion_p (loc, type, imag_part, result, false);
1359 /* Merge the results into appropriate single warning. */
1361 /* Note: this case includes SAFE_CONVERSION, i.e. success. */
1362 if (re_safety == im_safety)
1363 give_warning = re_safety;
1364 else if (!re_safety && im_safety)
1365 give_warning = im_safety;
1366 else if (re_safety && !im_safety)
1367 give_warning = re_safety;
1368 else
1369 give_warning = UNSAFE_OTHER;
1371 /* Warn about conversion from complex to real or integer type. */
1372 else
1373 give_warning = UNSAFE_IMAGINARY;
1377 /* Checks for remaining case: EXPR is not constant. */
1378 else
1380 /* Warn for real types converted to integer types. */
1381 if (TREE_CODE (expr_type) == REAL_TYPE
1382 && TREE_CODE (type) == INTEGER_TYPE)
1383 give_warning = UNSAFE_REAL;
1385 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1386 && TREE_CODE (type) == INTEGER_TYPE)
1388 /* Don't warn about unsigned char y = 0xff, x = (int) y; */
1389 expr = get_unwidened (expr, 0);
1390 expr_type = TREE_TYPE (expr);
1392 /* Don't warn for short y; short x = ((int)y & 0xff); */
1393 if (TREE_CODE (expr) == BIT_AND_EXPR
1394 || TREE_CODE (expr) == BIT_IOR_EXPR
1395 || TREE_CODE (expr) == BIT_XOR_EXPR)
1397 /* If both args were extended from a shortest type,
1398 use that type if that is safe. */
1399 expr_type = shorten_binary_op (expr_type,
1400 TREE_OPERAND (expr, 0),
1401 TREE_OPERAND (expr, 1),
1402 /* bitwise */1);
1404 if (TREE_CODE (expr) == BIT_AND_EXPR)
1406 tree op0 = TREE_OPERAND (expr, 0);
1407 tree op1 = TREE_OPERAND (expr, 1);
1408 bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1409 bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1411 /* If one of the operands is a non-negative constant
1412 that fits in the target type, then the type of the
1413 other operand does not matter. */
1414 if ((TREE_CODE (op0) == INTEGER_CST
1415 && int_fits_type_p (op0, c_common_signed_type (type))
1416 && int_fits_type_p (op0, c_common_unsigned_type (type)))
1417 || (TREE_CODE (op1) == INTEGER_CST
1418 && int_fits_type_p (op1, c_common_signed_type (type))
1419 && int_fits_type_p (op1,
1420 c_common_unsigned_type (type))))
1421 return SAFE_CONVERSION;
1422 /* If constant is unsigned and fits in the target
1423 type, then the result will also fit. */
1424 else if ((TREE_CODE (op0) == INTEGER_CST
1425 && unsigned0
1426 && int_fits_type_p (op0, type))
1427 || (TREE_CODE (op1) == INTEGER_CST
1428 && unsigned1
1429 && int_fits_type_p (op1, type)))
1430 return SAFE_CONVERSION;
1433 /* Warn for integer types converted to smaller integer types. */
1434 if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1435 give_warning = UNSAFE_OTHER;
1437 /* When they are the same width but different signedness,
1438 then the value may change. */
1439 else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1440 && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1441 /* Even when converted to a bigger type, if the type is
1442 unsigned but expr is signed, then negative values
1443 will be changed. */
1444 || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1445 && produce_warns)
1446 warning_at (loc, OPT_Wsign_conversion, "conversion to %qT from %qT "
1447 "may change the sign of the result",
1448 type, expr_type);
1451 /* Warn for integer types converted to real types if and only if
1452 all the range of values of the integer type cannot be
1453 represented by the real type. */
1454 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1455 && TREE_CODE (type) == REAL_TYPE)
1457 /* Don't warn about char y = 0xff; float x = (int) y; */
1458 expr = get_unwidened (expr, 0);
1459 expr_type = TREE_TYPE (expr);
1461 if (!int_safely_convertible_to_real_p (expr_type, type))
1462 give_warning = UNSAFE_OTHER;
1465 /* Warn for real types converted to smaller real types. */
1466 else if (TREE_CODE (expr_type) == REAL_TYPE
1467 && TREE_CODE (type) == REAL_TYPE
1468 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1469 give_warning = UNSAFE_REAL;
1471 /* Check conversion between two complex types. */
1472 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1473 && TREE_CODE (type) == COMPLEX_TYPE)
1475 /* Extract underlying types (i.e., type of real and imaginary
1476 parts) of expr_type and type. */
1477 tree from_type = TREE_TYPE (expr_type);
1478 tree to_type = TREE_TYPE (type);
1480 /* Warn for real types converted to integer types. */
1481 if (TREE_CODE (from_type) == REAL_TYPE
1482 && TREE_CODE (to_type) == INTEGER_TYPE)
1483 give_warning = UNSAFE_REAL;
1485 /* Warn for real types converted to smaller real types. */
1486 else if (TREE_CODE (from_type) == REAL_TYPE
1487 && TREE_CODE (to_type) == REAL_TYPE
1488 && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1489 give_warning = UNSAFE_REAL;
1491 /* Check conversion for complex integer types. Here implementation
1492 is simpler than for real-domain integers because it does not
1493 involve sophisticated cases, such as bitmasks, casts, etc. */
1494 else if (TREE_CODE (from_type) == INTEGER_TYPE
1495 && TREE_CODE (to_type) == INTEGER_TYPE)
1497 /* Warn for integer types converted to smaller integer types. */
1498 if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1499 give_warning = UNSAFE_OTHER;
1501 /* Check for different signedness, see case for real-domain
1502 integers (above) for a more detailed comment. */
1503 else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1504 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1505 || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1506 && produce_warns)
1507 warning_at (loc, OPT_Wsign_conversion,
1508 "conversion to %qT from %qT "
1509 "may change the sign of the result",
1510 type, expr_type);
1512 else if (TREE_CODE (from_type) == INTEGER_TYPE
1513 && TREE_CODE (to_type) == REAL_TYPE
1514 && !int_safely_convertible_to_real_p (from_type, to_type))
1515 give_warning = UNSAFE_OTHER;
1518 /* Warn for complex types converted to real or integer types. */
1519 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1520 && TREE_CODE (type) != COMPLEX_TYPE)
1521 give_warning = UNSAFE_IMAGINARY;
1524 return give_warning;
1528 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1529 Invoke this function on every expression that is converted implicitly,
1530 i.e. because of language rules and not because of an explicit cast. */
1532 tree
1533 convert_and_check (location_t loc, tree type, tree expr)
1535 tree result;
1536 tree expr_for_warning;
1538 /* Convert from a value with possible excess precision rather than
1539 via the semantic type, but do not warn about values not fitting
1540 exactly in the semantic type. */
1541 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1543 tree orig_type = TREE_TYPE (expr);
1544 expr = TREE_OPERAND (expr, 0);
1545 expr_for_warning = convert (orig_type, expr);
1546 if (orig_type == type)
1547 return expr_for_warning;
1549 else
1550 expr_for_warning = expr;
1552 if (TREE_TYPE (expr) == type)
1553 return expr;
1555 result = convert (type, expr);
1557 if (c_inhibit_evaluation_warnings == 0
1558 && !TREE_OVERFLOW_P (expr)
1559 && result != error_mark_node)
1560 warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1562 return result;
1565 /* A node in a list that describes references to variables (EXPR), which are
1566 either read accesses if WRITER is zero, or write accesses, in which case
1567 WRITER is the parent of EXPR. */
1568 struct tlist
1570 struct tlist *next;
1571 tree expr, writer;
1574 /* Used to implement a cache the results of a call to verify_tree. We only
1575 use this for SAVE_EXPRs. */
1576 struct tlist_cache
1578 struct tlist_cache *next;
1579 struct tlist *cache_before_sp;
1580 struct tlist *cache_after_sp;
1581 tree expr;
1584 /* Obstack to use when allocating tlist structures, and corresponding
1585 firstobj. */
1586 static struct obstack tlist_obstack;
1587 static char *tlist_firstobj = 0;
1589 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1590 warnings. */
1591 static struct tlist *warned_ids;
1592 /* SAVE_EXPRs need special treatment. We process them only once and then
1593 cache the results. */
1594 static struct tlist_cache *save_expr_cache;
1596 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1597 static void merge_tlist (struct tlist **, struct tlist *, int);
1598 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1599 static bool warning_candidate_p (tree);
1600 static bool candidate_equal_p (const_tree, const_tree);
1601 static void warn_for_collisions (struct tlist *);
1602 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1603 static struct tlist *new_tlist (struct tlist *, tree, tree);
1605 /* Create a new struct tlist and fill in its fields. */
1606 static struct tlist *
1607 new_tlist (struct tlist *next, tree t, tree writer)
1609 struct tlist *l;
1610 l = XOBNEW (&tlist_obstack, struct tlist);
1611 l->next = next;
1612 l->expr = t;
1613 l->writer = writer;
1614 return l;
1617 /* Add duplicates of the nodes found in ADD to the list *TO. If EXCLUDE_WRITER
1618 is nonnull, we ignore any node we find which has a writer equal to it. */
1620 static void
1621 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1623 while (add)
1625 struct tlist *next = add->next;
1626 if (!copy)
1627 add->next = *to;
1628 if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1629 *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1630 add = next;
1634 /* Merge the nodes of ADD into TO. This merging process is done so that for
1635 each variable that already exists in TO, no new node is added; however if
1636 there is a write access recorded in ADD, and an occurrence on TO is only
1637 a read access, then the occurrence in TO will be modified to record the
1638 write. */
1640 static void
1641 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1643 struct tlist **end = to;
1645 while (*end)
1646 end = &(*end)->next;
1648 while (add)
1650 int found = 0;
1651 struct tlist *tmp2;
1652 struct tlist *next = add->next;
1654 for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1655 if (candidate_equal_p (tmp2->expr, add->expr))
1657 found = 1;
1658 if (!tmp2->writer)
1659 tmp2->writer = add->writer;
1661 if (!found)
1663 *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1664 end = &(*end)->next;
1665 *end = 0;
1667 add = next;
1671 /* WRITTEN is a variable, WRITER is its parent. Warn if any of the variable
1672 references in list LIST conflict with it, excluding reads if ONLY writers
1673 is nonzero. */
1675 static void
1676 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1677 int only_writes)
1679 struct tlist *tmp;
1681 /* Avoid duplicate warnings. */
1682 for (tmp = warned_ids; tmp; tmp = tmp->next)
1683 if (candidate_equal_p (tmp->expr, written))
1684 return;
1686 while (list)
1688 if (candidate_equal_p (list->expr, written)
1689 && !candidate_equal_p (list->writer, writer)
1690 && (!only_writes || list->writer))
1692 warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1693 warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1694 OPT_Wsequence_point, "operation on %qE may be undefined",
1695 list->expr);
1697 list = list->next;
1701 /* Given a list LIST of references to variables, find whether any of these
1702 can cause conflicts due to missing sequence points. */
1704 static void
1705 warn_for_collisions (struct tlist *list)
1707 struct tlist *tmp;
1709 for (tmp = list; tmp; tmp = tmp->next)
1711 if (tmp->writer)
1712 warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1716 /* Return nonzero if X is a tree that can be verified by the sequence point
1717 warnings. */
1719 static bool
1720 warning_candidate_p (tree x)
1722 if (DECL_P (x) && DECL_ARTIFICIAL (x))
1723 return false;
1725 if (TREE_CODE (x) == BLOCK)
1726 return false;
1728 /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.c
1729 (lvalue_p) crash on TRY/CATCH. */
1730 if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1731 return false;
1733 if (!lvalue_p (x))
1734 return false;
1736 /* No point to track non-const calls, they will never satisfy
1737 operand_equal_p. */
1738 if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1739 return false;
1741 if (TREE_CODE (x) == STRING_CST)
1742 return false;
1744 return true;
1747 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1748 static bool
1749 candidate_equal_p (const_tree x, const_tree y)
1751 return (x == y) || (x && y && operand_equal_p (x, y, 0));
1754 /* Walk the tree X, and record accesses to variables. If X is written by the
1755 parent tree, WRITER is the parent.
1756 We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP. If this
1757 expression or its only operand forces a sequence point, then everything up
1758 to the sequence point is stored in PBEFORE_SP. Everything else gets stored
1759 in PNO_SP.
1760 Once we return, we will have emitted warnings if any subexpression before
1761 such a sequence point could be undefined. On a higher level, however, the
1762 sequence point may not be relevant, and we'll merge the two lists.
1764 Example: (b++, a) + b;
1765 The call that processes the COMPOUND_EXPR will store the increment of B
1766 in PBEFORE_SP, and the use of A in PNO_SP. The higher-level call that
1767 processes the PLUS_EXPR will need to merge the two lists so that
1768 eventually, all accesses end up on the same list (and we'll warn about the
1769 unordered subexpressions b++ and b.
1771 A note on merging. If we modify the former example so that our expression
1772 becomes
1773 (b++, b) + a
1774 care must be taken not simply to add all three expressions into the final
1775 PNO_SP list. The function merge_tlist takes care of that by merging the
1776 before-SP list of the COMPOUND_EXPR into its after-SP list in a special
1777 way, so that no more than one access to B is recorded. */
1779 static void
1780 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
1781 tree writer)
1783 struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
1784 enum tree_code code;
1785 enum tree_code_class cl;
1787 /* X may be NULL if it is the operand of an empty statement expression
1788 ({ }). */
1789 if (x == NULL)
1790 return;
1792 restart:
1793 code = TREE_CODE (x);
1794 cl = TREE_CODE_CLASS (code);
1796 if (warning_candidate_p (x))
1797 *pno_sp = new_tlist (*pno_sp, x, writer);
1799 switch (code)
1801 case CONSTRUCTOR:
1802 case SIZEOF_EXPR:
1803 return;
1805 case COMPOUND_EXPR:
1806 case TRUTH_ANDIF_EXPR:
1807 case TRUTH_ORIF_EXPR:
1808 tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
1809 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1810 warn_for_collisions (tmp_nosp);
1811 merge_tlist (pbefore_sp, tmp_before, 0);
1812 merge_tlist (pbefore_sp, tmp_nosp, 0);
1813 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
1814 warn_for_collisions (tmp_list2);
1815 merge_tlist (pbefore_sp, tmp_list3, 0);
1816 merge_tlist (pno_sp, tmp_list2, 0);
1817 return;
1819 case COND_EXPR:
1820 tmp_before = tmp_list2 = 0;
1821 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
1822 warn_for_collisions (tmp_list2);
1823 merge_tlist (pbefore_sp, tmp_before, 0);
1824 merge_tlist (pbefore_sp, tmp_list2, 0);
1826 tmp_list3 = tmp_nosp = 0;
1827 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
1828 warn_for_collisions (tmp_nosp);
1829 merge_tlist (pbefore_sp, tmp_list3, 0);
1831 tmp_list3 = tmp_list2 = 0;
1832 verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
1833 warn_for_collisions (tmp_list2);
1834 merge_tlist (pbefore_sp, tmp_list3, 0);
1835 /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
1836 two first, to avoid warning for (a ? b++ : b++). */
1837 merge_tlist (&tmp_nosp, tmp_list2, 0);
1838 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1839 return;
1841 case PREDECREMENT_EXPR:
1842 case PREINCREMENT_EXPR:
1843 case POSTDECREMENT_EXPR:
1844 case POSTINCREMENT_EXPR:
1845 verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
1846 return;
1848 case MODIFY_EXPR:
1849 tmp_before = tmp_nosp = tmp_list3 = 0;
1850 verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
1851 verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
1852 /* Expressions inside the LHS are not ordered wrt. the sequence points
1853 in the RHS. Example:
1854 *a = (a++, 2)
1855 Despite the fact that the modification of "a" is in the before_sp
1856 list (tmp_before), it conflicts with the use of "a" in the LHS.
1857 We can handle this by adding the contents of tmp_list3
1858 to those of tmp_before, and redoing the collision warnings for that
1859 list. */
1860 add_tlist (&tmp_before, tmp_list3, x, 1);
1861 warn_for_collisions (tmp_before);
1862 /* Exclude the LHS itself here; we first have to merge it into the
1863 tmp_nosp list. This is done to avoid warning for "a = a"; if we
1864 didn't exclude the LHS, we'd get it twice, once as a read and once
1865 as a write. */
1866 add_tlist (pno_sp, tmp_list3, x, 0);
1867 warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
1869 merge_tlist (pbefore_sp, tmp_before, 0);
1870 if (warning_candidate_p (TREE_OPERAND (x, 0)))
1871 merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
1872 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
1873 return;
1875 case CALL_EXPR:
1876 /* We need to warn about conflicts among arguments and conflicts between
1877 args and the function address. Side effects of the function address,
1878 however, are not ordered by the sequence point of the call. */
1880 call_expr_arg_iterator iter;
1881 tree arg;
1882 tmp_before = tmp_nosp = 0;
1883 verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
1884 FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
1886 tmp_list2 = tmp_list3 = 0;
1887 verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
1888 merge_tlist (&tmp_list3, tmp_list2, 0);
1889 add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
1891 add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
1892 warn_for_collisions (tmp_before);
1893 add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
1894 return;
1897 case TREE_LIST:
1898 /* Scan all the list, e.g. indices of multi dimensional array. */
1899 while (x)
1901 tmp_before = tmp_nosp = 0;
1902 verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
1903 merge_tlist (&tmp_nosp, tmp_before, 0);
1904 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1905 x = TREE_CHAIN (x);
1907 return;
1909 case SAVE_EXPR:
1911 struct tlist_cache *t;
1912 for (t = save_expr_cache; t; t = t->next)
1913 if (candidate_equal_p (t->expr, x))
1914 break;
1916 if (!t)
1918 t = XOBNEW (&tlist_obstack, struct tlist_cache);
1919 t->next = save_expr_cache;
1920 t->expr = x;
1921 save_expr_cache = t;
1923 tmp_before = tmp_nosp = 0;
1924 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1925 warn_for_collisions (tmp_nosp);
1927 tmp_list3 = 0;
1928 merge_tlist (&tmp_list3, tmp_nosp, 0);
1929 t->cache_before_sp = tmp_before;
1930 t->cache_after_sp = tmp_list3;
1932 merge_tlist (pbefore_sp, t->cache_before_sp, 1);
1933 add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
1934 return;
1937 case ADDR_EXPR:
1938 x = TREE_OPERAND (x, 0);
1939 if (DECL_P (x))
1940 return;
1941 writer = 0;
1942 goto restart;
1944 default:
1945 /* For other expressions, simply recurse on their operands.
1946 Manual tail recursion for unary expressions.
1947 Other non-expressions need not be processed. */
1948 if (cl == tcc_unary)
1950 x = TREE_OPERAND (x, 0);
1951 writer = 0;
1952 goto restart;
1954 else if (IS_EXPR_CODE_CLASS (cl))
1956 int lp;
1957 int max = TREE_OPERAND_LENGTH (x);
1958 for (lp = 0; lp < max; lp++)
1960 tmp_before = tmp_nosp = 0;
1961 verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
1962 merge_tlist (&tmp_nosp, tmp_before, 0);
1963 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1966 return;
1970 /* Try to warn for undefined behavior in EXPR due to missing sequence
1971 points. */
1973 DEBUG_FUNCTION void
1974 verify_sequence_points (tree expr)
1976 struct tlist *before_sp = 0, *after_sp = 0;
1978 warned_ids = 0;
1979 save_expr_cache = 0;
1980 if (tlist_firstobj == 0)
1982 gcc_obstack_init (&tlist_obstack);
1983 tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
1986 verify_tree (expr, &before_sp, &after_sp, 0);
1987 warn_for_collisions (after_sp);
1988 obstack_free (&tlist_obstack, tlist_firstobj);
1991 /* Validate the expression after `case' and apply default promotions. */
1993 static tree
1994 check_case_value (location_t loc, tree value)
1996 if (value == NULL_TREE)
1997 return value;
1999 if (TREE_CODE (value) == INTEGER_CST)
2000 /* Promote char or short to int. */
2001 value = perform_integral_promotions (value);
2002 else if (value != error_mark_node)
2004 error_at (loc, "case label does not reduce to an integer constant");
2005 value = error_mark_node;
2008 constant_expression_warning (value);
2010 return value;
2013 /* See if the case values LOW and HIGH are in the range of the original
2014 type (i.e. before the default conversion to int) of the switch testing
2015 expression.
2016 TYPE is the promoted type of the testing expression, and ORIG_TYPE is
2017 the type before promoting it. CASE_LOW_P is a pointer to the lower
2018 bound of the case label, and CASE_HIGH_P is the upper bound or NULL
2019 if the case is not a case range.
2020 The caller has to make sure that we are not called with NULL for
2021 CASE_LOW_P (i.e. the default case). OUTSIDE_RANGE_P says whether there
2022 was a case value that doesn't fit into the range of the ORIG_TYPE.
2023 Returns true if the case label is in range of ORIG_TYPE (saturated or
2024 untouched) or false if the label is out of range. */
2026 static bool
2027 check_case_bounds (location_t loc, tree type, tree orig_type,
2028 tree *case_low_p, tree *case_high_p,
2029 bool *outside_range_p)
2031 tree min_value, max_value;
2032 tree case_low = *case_low_p;
2033 tree case_high = case_high_p ? *case_high_p : case_low;
2035 /* If there was a problem with the original type, do nothing. */
2036 if (orig_type == error_mark_node)
2037 return true;
2039 min_value = TYPE_MIN_VALUE (orig_type);
2040 max_value = TYPE_MAX_VALUE (orig_type);
2042 /* We'll really need integer constants here. */
2043 case_low = fold (case_low);
2044 case_high = fold (case_high);
2046 /* Case label is less than minimum for type. */
2047 if (tree_int_cst_compare (case_low, min_value) < 0
2048 && tree_int_cst_compare (case_high, min_value) < 0)
2050 warning_at (loc, 0, "case label value is less than minimum value "
2051 "for type");
2052 *outside_range_p = true;
2053 return false;
2056 /* Case value is greater than maximum for type. */
2057 if (tree_int_cst_compare (case_low, max_value) > 0
2058 && tree_int_cst_compare (case_high, max_value) > 0)
2060 warning_at (loc, 0, "case label value exceeds maximum value for type");
2061 *outside_range_p = true;
2062 return false;
2065 /* Saturate lower case label value to minimum. */
2066 if (tree_int_cst_compare (case_high, min_value) >= 0
2067 && tree_int_cst_compare (case_low, min_value) < 0)
2069 warning_at (loc, 0, "lower value in case label range"
2070 " less than minimum value for type");
2071 *outside_range_p = true;
2072 case_low = min_value;
2075 /* Saturate upper case label value to maximum. */
2076 if (tree_int_cst_compare (case_low, max_value) <= 0
2077 && tree_int_cst_compare (case_high, max_value) > 0)
2079 warning_at (loc, 0, "upper value in case label range"
2080 " exceeds maximum value for type");
2081 *outside_range_p = true;
2082 case_high = max_value;
2085 if (*case_low_p != case_low)
2086 *case_low_p = convert (type, case_low);
2087 if (case_high_p && *case_high_p != case_high)
2088 *case_high_p = convert (type, case_high);
2090 return true;
2093 /* Return an integer type with BITS bits of precision,
2094 that is unsigned if UNSIGNEDP is nonzero, otherwise signed. */
2096 tree
2097 c_common_type_for_size (unsigned int bits, int unsignedp)
2099 int i;
2101 if (bits == TYPE_PRECISION (integer_type_node))
2102 return unsignedp ? unsigned_type_node : integer_type_node;
2104 if (bits == TYPE_PRECISION (signed_char_type_node))
2105 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2107 if (bits == TYPE_PRECISION (short_integer_type_node))
2108 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2110 if (bits == TYPE_PRECISION (long_integer_type_node))
2111 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2113 if (bits == TYPE_PRECISION (long_long_integer_type_node))
2114 return (unsignedp ? long_long_unsigned_type_node
2115 : long_long_integer_type_node);
2117 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2118 if (int_n_enabled_p[i]
2119 && bits == int_n_data[i].bitsize)
2120 return (unsignedp ? int_n_trees[i].unsigned_type
2121 : int_n_trees[i].signed_type);
2123 if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2124 return (unsignedp ? widest_unsigned_literal_type_node
2125 : widest_integer_literal_type_node);
2127 if (bits <= TYPE_PRECISION (intQI_type_node))
2128 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2130 if (bits <= TYPE_PRECISION (intHI_type_node))
2131 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2133 if (bits <= TYPE_PRECISION (intSI_type_node))
2134 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2136 if (bits <= TYPE_PRECISION (intDI_type_node))
2137 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2139 return NULL_TREE;
2142 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2143 that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2144 and saturating if SATP is nonzero, otherwise not saturating. */
2146 tree
2147 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2148 int unsignedp, int satp)
2150 enum mode_class mclass;
2151 if (ibit == 0)
2152 mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2153 else
2154 mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2156 opt_scalar_mode opt_mode;
2157 scalar_mode mode;
2158 FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2160 mode = opt_mode.require ();
2161 if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2162 break;
2165 if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2167 sorry ("GCC cannot support operators with integer types and "
2168 "fixed-point types that have too many integral and "
2169 "fractional bits together");
2170 return NULL_TREE;
2173 return c_common_type_for_mode (mode, satp);
2176 /* Used for communication between c_common_type_for_mode and
2177 c_register_builtin_type. */
2178 tree registered_builtin_types;
2180 /* Return a data type that has machine mode MODE.
2181 If the mode is an integer,
2182 then UNSIGNEDP selects between signed and unsigned types.
2183 If the mode is a fixed-point mode,
2184 then UNSIGNEDP selects between saturating and nonsaturating types. */
2186 tree
2187 c_common_type_for_mode (machine_mode mode, int unsignedp)
2189 tree t;
2190 int i;
2192 if (mode == TYPE_MODE (integer_type_node))
2193 return unsignedp ? unsigned_type_node : integer_type_node;
2195 if (mode == TYPE_MODE (signed_char_type_node))
2196 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2198 if (mode == TYPE_MODE (short_integer_type_node))
2199 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2201 if (mode == TYPE_MODE (long_integer_type_node))
2202 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2204 if (mode == TYPE_MODE (long_long_integer_type_node))
2205 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2207 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2208 if (int_n_enabled_p[i]
2209 && mode == int_n_data[i].m)
2210 return (unsignedp ? int_n_trees[i].unsigned_type
2211 : int_n_trees[i].signed_type);
2213 if (mode == QImode)
2214 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2216 if (mode == HImode)
2217 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2219 if (mode == SImode)
2220 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2222 if (mode == DImode)
2223 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2225 #if HOST_BITS_PER_WIDE_INT >= 64
2226 if (mode == TYPE_MODE (intTI_type_node))
2227 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2228 #endif
2230 if (mode == TYPE_MODE (float_type_node))
2231 return float_type_node;
2233 if (mode == TYPE_MODE (double_type_node))
2234 return double_type_node;
2236 if (mode == TYPE_MODE (long_double_type_node))
2237 return long_double_type_node;
2239 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2240 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2241 && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2242 return FLOATN_NX_TYPE_NODE (i);
2244 if (mode == TYPE_MODE (void_type_node))
2245 return void_type_node;
2247 if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2248 || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2250 unsigned int precision
2251 = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2252 return (unsignedp
2253 ? make_unsigned_type (precision)
2254 : make_signed_type (precision));
2257 if (COMPLEX_MODE_P (mode))
2259 machine_mode inner_mode;
2260 tree inner_type;
2262 if (mode == TYPE_MODE (complex_float_type_node))
2263 return complex_float_type_node;
2264 if (mode == TYPE_MODE (complex_double_type_node))
2265 return complex_double_type_node;
2266 if (mode == TYPE_MODE (complex_long_double_type_node))
2267 return complex_long_double_type_node;
2269 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2270 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2271 && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2272 return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2274 if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2275 return complex_integer_type_node;
2277 inner_mode = GET_MODE_INNER (mode);
2278 inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2279 if (inner_type != NULL_TREE)
2280 return build_complex_type (inner_type);
2282 else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
2283 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2285 unsigned int elem_bits = vector_element_size (GET_MODE_BITSIZE (mode),
2286 GET_MODE_NUNITS (mode));
2287 tree bool_type = build_nonstandard_boolean_type (elem_bits);
2288 return build_vector_type_for_mode (bool_type, mode);
2290 else if (VECTOR_MODE_P (mode)
2291 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2293 machine_mode inner_mode = GET_MODE_INNER (mode);
2294 tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2295 if (inner_type != NULL_TREE)
2296 return build_vector_type_for_mode (inner_type, mode);
2299 if (mode == TYPE_MODE (dfloat32_type_node))
2300 return dfloat32_type_node;
2301 if (mode == TYPE_MODE (dfloat64_type_node))
2302 return dfloat64_type_node;
2303 if (mode == TYPE_MODE (dfloat128_type_node))
2304 return dfloat128_type_node;
2306 if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2308 if (mode == TYPE_MODE (short_fract_type_node))
2309 return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2310 if (mode == TYPE_MODE (fract_type_node))
2311 return unsignedp ? sat_fract_type_node : fract_type_node;
2312 if (mode == TYPE_MODE (long_fract_type_node))
2313 return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2314 if (mode == TYPE_MODE (long_long_fract_type_node))
2315 return unsignedp ? sat_long_long_fract_type_node
2316 : long_long_fract_type_node;
2318 if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2319 return unsignedp ? sat_unsigned_short_fract_type_node
2320 : unsigned_short_fract_type_node;
2321 if (mode == TYPE_MODE (unsigned_fract_type_node))
2322 return unsignedp ? sat_unsigned_fract_type_node
2323 : unsigned_fract_type_node;
2324 if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2325 return unsignedp ? sat_unsigned_long_fract_type_node
2326 : unsigned_long_fract_type_node;
2327 if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2328 return unsignedp ? sat_unsigned_long_long_fract_type_node
2329 : unsigned_long_long_fract_type_node;
2331 if (mode == TYPE_MODE (short_accum_type_node))
2332 return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2333 if (mode == TYPE_MODE (accum_type_node))
2334 return unsignedp ? sat_accum_type_node : accum_type_node;
2335 if (mode == TYPE_MODE (long_accum_type_node))
2336 return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2337 if (mode == TYPE_MODE (long_long_accum_type_node))
2338 return unsignedp ? sat_long_long_accum_type_node
2339 : long_long_accum_type_node;
2341 if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2342 return unsignedp ? sat_unsigned_short_accum_type_node
2343 : unsigned_short_accum_type_node;
2344 if (mode == TYPE_MODE (unsigned_accum_type_node))
2345 return unsignedp ? sat_unsigned_accum_type_node
2346 : unsigned_accum_type_node;
2347 if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2348 return unsignedp ? sat_unsigned_long_accum_type_node
2349 : unsigned_long_accum_type_node;
2350 if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2351 return unsignedp ? sat_unsigned_long_long_accum_type_node
2352 : unsigned_long_long_accum_type_node;
2354 if (mode == QQmode)
2355 return unsignedp ? sat_qq_type_node : qq_type_node;
2356 if (mode == HQmode)
2357 return unsignedp ? sat_hq_type_node : hq_type_node;
2358 if (mode == SQmode)
2359 return unsignedp ? sat_sq_type_node : sq_type_node;
2360 if (mode == DQmode)
2361 return unsignedp ? sat_dq_type_node : dq_type_node;
2362 if (mode == TQmode)
2363 return unsignedp ? sat_tq_type_node : tq_type_node;
2365 if (mode == UQQmode)
2366 return unsignedp ? sat_uqq_type_node : uqq_type_node;
2367 if (mode == UHQmode)
2368 return unsignedp ? sat_uhq_type_node : uhq_type_node;
2369 if (mode == USQmode)
2370 return unsignedp ? sat_usq_type_node : usq_type_node;
2371 if (mode == UDQmode)
2372 return unsignedp ? sat_udq_type_node : udq_type_node;
2373 if (mode == UTQmode)
2374 return unsignedp ? sat_utq_type_node : utq_type_node;
2376 if (mode == HAmode)
2377 return unsignedp ? sat_ha_type_node : ha_type_node;
2378 if (mode == SAmode)
2379 return unsignedp ? sat_sa_type_node : sa_type_node;
2380 if (mode == DAmode)
2381 return unsignedp ? sat_da_type_node : da_type_node;
2382 if (mode == TAmode)
2383 return unsignedp ? sat_ta_type_node : ta_type_node;
2385 if (mode == UHAmode)
2386 return unsignedp ? sat_uha_type_node : uha_type_node;
2387 if (mode == USAmode)
2388 return unsignedp ? sat_usa_type_node : usa_type_node;
2389 if (mode == UDAmode)
2390 return unsignedp ? sat_uda_type_node : uda_type_node;
2391 if (mode == UTAmode)
2392 return unsignedp ? sat_uta_type_node : uta_type_node;
2395 for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2396 if (TYPE_MODE (TREE_VALUE (t)) == mode
2397 && !!unsignedp == !!TYPE_UNSIGNED (TREE_VALUE (t)))
2398 return TREE_VALUE (t);
2400 return NULL_TREE;
2403 tree
2404 c_common_unsigned_type (tree type)
2406 return c_common_signed_or_unsigned_type (1, type);
2409 /* Return a signed type the same as TYPE in other respects. */
2411 tree
2412 c_common_signed_type (tree type)
2414 return c_common_signed_or_unsigned_type (0, type);
2417 /* Return a type the same as TYPE except unsigned or
2418 signed according to UNSIGNEDP. */
2420 tree
2421 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2423 tree type1;
2424 int i;
2426 /* This block of code emulates the behavior of the old
2427 c_common_unsigned_type. In particular, it returns
2428 long_unsigned_type_node if passed a long, even when a int would
2429 have the same size. This is necessary for warnings to work
2430 correctly in archs where sizeof(int) == sizeof(long) */
2432 type1 = TYPE_MAIN_VARIANT (type);
2433 if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2434 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2435 if (type1 == integer_type_node || type1 == unsigned_type_node)
2436 return unsignedp ? unsigned_type_node : integer_type_node;
2437 if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2438 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2439 if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2440 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2441 if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2442 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2444 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2445 if (int_n_enabled_p[i]
2446 && (type1 == int_n_trees[i].unsigned_type
2447 || type1 == int_n_trees[i].signed_type))
2448 return (unsignedp ? int_n_trees[i].unsigned_type
2449 : int_n_trees[i].signed_type);
2451 #if HOST_BITS_PER_WIDE_INT >= 64
2452 if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2453 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2454 #endif
2455 if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2456 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2457 if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2458 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2459 if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2460 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2461 if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2462 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2464 #define C_COMMON_FIXED_TYPES(NAME) \
2465 if (type1 == short_ ## NAME ## _type_node \
2466 || type1 == unsigned_short_ ## NAME ## _type_node) \
2467 return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2468 : short_ ## NAME ## _type_node; \
2469 if (type1 == NAME ## _type_node \
2470 || type1 == unsigned_ ## NAME ## _type_node) \
2471 return unsignedp ? unsigned_ ## NAME ## _type_node \
2472 : NAME ## _type_node; \
2473 if (type1 == long_ ## NAME ## _type_node \
2474 || type1 == unsigned_long_ ## NAME ## _type_node) \
2475 return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2476 : long_ ## NAME ## _type_node; \
2477 if (type1 == long_long_ ## NAME ## _type_node \
2478 || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2479 return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2480 : long_long_ ## NAME ## _type_node;
2482 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2483 if (type1 == NAME ## _type_node \
2484 || type1 == u ## NAME ## _type_node) \
2485 return unsignedp ? u ## NAME ## _type_node \
2486 : NAME ## _type_node;
2488 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2489 if (type1 == sat_ ## short_ ## NAME ## _type_node \
2490 || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2491 return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2492 : sat_ ## short_ ## NAME ## _type_node; \
2493 if (type1 == sat_ ## NAME ## _type_node \
2494 || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2495 return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2496 : sat_ ## NAME ## _type_node; \
2497 if (type1 == sat_ ## long_ ## NAME ## _type_node \
2498 || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2499 return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2500 : sat_ ## long_ ## NAME ## _type_node; \
2501 if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2502 || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2503 return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2504 : sat_ ## long_long_ ## NAME ## _type_node;
2506 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME) \
2507 if (type1 == sat_ ## NAME ## _type_node \
2508 || type1 == sat_ ## u ## NAME ## _type_node) \
2509 return unsignedp ? sat_ ## u ## NAME ## _type_node \
2510 : sat_ ## NAME ## _type_node;
2512 C_COMMON_FIXED_TYPES (fract);
2513 C_COMMON_FIXED_TYPES_SAT (fract);
2514 C_COMMON_FIXED_TYPES (accum);
2515 C_COMMON_FIXED_TYPES_SAT (accum);
2517 C_COMMON_FIXED_MODE_TYPES (qq);
2518 C_COMMON_FIXED_MODE_TYPES (hq);
2519 C_COMMON_FIXED_MODE_TYPES (sq);
2520 C_COMMON_FIXED_MODE_TYPES (dq);
2521 C_COMMON_FIXED_MODE_TYPES (tq);
2522 C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2523 C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2524 C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2525 C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2526 C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2527 C_COMMON_FIXED_MODE_TYPES (ha);
2528 C_COMMON_FIXED_MODE_TYPES (sa);
2529 C_COMMON_FIXED_MODE_TYPES (da);
2530 C_COMMON_FIXED_MODE_TYPES (ta);
2531 C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2532 C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2533 C_COMMON_FIXED_MODE_TYPES_SAT (da);
2534 C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2536 /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2537 the precision; they have precision set to match their range, but
2538 may use a wider mode to match an ABI. If we change modes, we may
2539 wind up with bad conversions. For INTEGER_TYPEs in C, must check
2540 the precision as well, so as to yield correct results for
2541 bit-field types. C++ does not have these separate bit-field
2542 types, and producing a signed or unsigned variant of an
2543 ENUMERAL_TYPE may cause other problems as well. */
2545 if (!INTEGRAL_TYPE_P (type)
2546 || TYPE_UNSIGNED (type) == unsignedp)
2547 return type;
2549 #define TYPE_OK(node) \
2550 (TYPE_MODE (type) == TYPE_MODE (node) \
2551 && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2552 if (TYPE_OK (signed_char_type_node))
2553 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2554 if (TYPE_OK (integer_type_node))
2555 return unsignedp ? unsigned_type_node : integer_type_node;
2556 if (TYPE_OK (short_integer_type_node))
2557 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2558 if (TYPE_OK (long_integer_type_node))
2559 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2560 if (TYPE_OK (long_long_integer_type_node))
2561 return (unsignedp ? long_long_unsigned_type_node
2562 : long_long_integer_type_node);
2564 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2565 if (int_n_enabled_p[i]
2566 && TYPE_MODE (type) == int_n_data[i].m
2567 && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2568 return (unsignedp ? int_n_trees[i].unsigned_type
2569 : int_n_trees[i].signed_type);
2571 #if HOST_BITS_PER_WIDE_INT >= 64
2572 if (TYPE_OK (intTI_type_node))
2573 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2574 #endif
2575 if (TYPE_OK (intDI_type_node))
2576 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2577 if (TYPE_OK (intSI_type_node))
2578 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2579 if (TYPE_OK (intHI_type_node))
2580 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2581 if (TYPE_OK (intQI_type_node))
2582 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2583 #undef TYPE_OK
2585 return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2588 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP. */
2590 tree
2591 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2593 int i;
2595 /* Extended integer types of the same width as a standard type have
2596 lesser rank, so those of the same width as int promote to int or
2597 unsigned int and are valid for printf formats expecting int or
2598 unsigned int. To avoid such special cases, avoid creating
2599 extended integer types for bit-fields if a standard integer type
2600 is available. */
2601 if (width == TYPE_PRECISION (integer_type_node))
2602 return unsignedp ? unsigned_type_node : integer_type_node;
2603 if (width == TYPE_PRECISION (signed_char_type_node))
2604 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2605 if (width == TYPE_PRECISION (short_integer_type_node))
2606 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2607 if (width == TYPE_PRECISION (long_integer_type_node))
2608 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2609 if (width == TYPE_PRECISION (long_long_integer_type_node))
2610 return (unsignedp ? long_long_unsigned_type_node
2611 : long_long_integer_type_node);
2612 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2613 if (int_n_enabled_p[i]
2614 && width == int_n_data[i].bitsize)
2615 return (unsignedp ? int_n_trees[i].unsigned_type
2616 : int_n_trees[i].signed_type);
2617 return build_nonstandard_integer_type (width, unsignedp);
2620 /* The C version of the register_builtin_type langhook. */
2622 void
2623 c_register_builtin_type (tree type, const char* name)
2625 tree decl;
2627 decl = build_decl (UNKNOWN_LOCATION,
2628 TYPE_DECL, get_identifier (name), type);
2629 DECL_ARTIFICIAL (decl) = 1;
2630 if (!TYPE_NAME (type))
2631 TYPE_NAME (type) = decl;
2632 lang_hooks.decls.pushdecl (decl);
2634 registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2637 /* Print an error message for invalid operands to arith operation
2638 CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2639 RICHLOC is a rich location for the message, containing either
2640 three separate locations for each of the operator and operands
2642 lhs op rhs
2643 ~~~ ^~ ~~~
2645 (C FE), or one location ranging over all over them
2647 lhs op rhs
2648 ~~~~^~~~~~
2650 (C++ FE). */
2652 void
2653 binary_op_error (rich_location *richloc, enum tree_code code,
2654 tree type0, tree type1)
2656 const char *opname;
2658 switch (code)
2660 case PLUS_EXPR:
2661 opname = "+"; break;
2662 case MINUS_EXPR:
2663 opname = "-"; break;
2664 case MULT_EXPR:
2665 opname = "*"; break;
2666 case MAX_EXPR:
2667 opname = "max"; break;
2668 case MIN_EXPR:
2669 opname = "min"; break;
2670 case EQ_EXPR:
2671 opname = "=="; break;
2672 case NE_EXPR:
2673 opname = "!="; break;
2674 case LE_EXPR:
2675 opname = "<="; break;
2676 case GE_EXPR:
2677 opname = ">="; break;
2678 case LT_EXPR:
2679 opname = "<"; break;
2680 case GT_EXPR:
2681 opname = ">"; break;
2682 case LSHIFT_EXPR:
2683 opname = "<<"; break;
2684 case RSHIFT_EXPR:
2685 opname = ">>"; break;
2686 case TRUNC_MOD_EXPR:
2687 case FLOOR_MOD_EXPR:
2688 opname = "%"; break;
2689 case TRUNC_DIV_EXPR:
2690 case FLOOR_DIV_EXPR:
2691 opname = "/"; break;
2692 case BIT_AND_EXPR:
2693 opname = "&"; break;
2694 case BIT_IOR_EXPR:
2695 opname = "|"; break;
2696 case TRUTH_ANDIF_EXPR:
2697 opname = "&&"; break;
2698 case TRUTH_ORIF_EXPR:
2699 opname = "||"; break;
2700 case BIT_XOR_EXPR:
2701 opname = "^"; break;
2702 default:
2703 gcc_unreachable ();
2705 error_at (richloc,
2706 "invalid operands to binary %s (have %qT and %qT)",
2707 opname, type0, type1);
2710 /* Given an expression as a tree, return its original type. Do this
2711 by stripping any conversion that preserves the sign and precision. */
2712 static tree
2713 expr_original_type (tree expr)
2715 STRIP_SIGN_NOPS (expr);
2716 return TREE_TYPE (expr);
2719 /* Subroutine of build_binary_op, used for comparison operations.
2720 See if the operands have both been converted from subword integer types
2721 and, if so, perhaps change them both back to their original type.
2722 This function is also responsible for converting the two operands
2723 to the proper common type for comparison.
2725 The arguments of this function are all pointers to local variables
2726 of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2727 RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2729 LOC is the location of the comparison.
2731 If this function returns non-NULL_TREE, it means that the comparison has
2732 a constant value. What this function returns is an expression for
2733 that value. */
2735 tree
2736 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2737 tree *restype_ptr, enum tree_code *rescode_ptr)
2739 tree type;
2740 tree op0 = *op0_ptr;
2741 tree op1 = *op1_ptr;
2742 int unsignedp0, unsignedp1;
2743 int real1, real2;
2744 tree primop0, primop1;
2745 enum tree_code code = *rescode_ptr;
2747 /* Throw away any conversions to wider types
2748 already present in the operands. */
2750 primop0 = c_common_get_narrower (op0, &unsignedp0);
2751 primop1 = c_common_get_narrower (op1, &unsignedp1);
2753 /* If primopN is first sign-extended from primopN's precision to opN's
2754 precision, then zero-extended from opN's precision to
2755 *restype_ptr precision, shortenings might be invalid. */
2756 if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2757 && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2758 && !unsignedp0
2759 && TYPE_UNSIGNED (TREE_TYPE (op0)))
2760 primop0 = op0;
2761 if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2762 && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2763 && !unsignedp1
2764 && TYPE_UNSIGNED (TREE_TYPE (op1)))
2765 primop1 = op1;
2767 /* Handle the case that OP0 does not *contain* a conversion
2768 but it *requires* conversion to FINAL_TYPE. */
2770 if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2771 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2772 if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2773 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2775 /* If one of the operands must be floated, we cannot optimize. */
2776 real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
2777 real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
2779 /* If first arg is constant, swap the args (changing operation
2780 so value is preserved), for canonicalization. Don't do this if
2781 the second arg is 0. */
2783 if (TREE_CONSTANT (primop0)
2784 && !integer_zerop (primop1) && !real_zerop (primop1)
2785 && !fixed_zerop (primop1))
2787 std::swap (primop0, primop1);
2788 std::swap (op0, op1);
2789 *op0_ptr = op0;
2790 *op1_ptr = op1;
2791 std::swap (unsignedp0, unsignedp1);
2792 std::swap (real1, real2);
2794 switch (code)
2796 case LT_EXPR:
2797 code = GT_EXPR;
2798 break;
2799 case GT_EXPR:
2800 code = LT_EXPR;
2801 break;
2802 case LE_EXPR:
2803 code = GE_EXPR;
2804 break;
2805 case GE_EXPR:
2806 code = LE_EXPR;
2807 break;
2808 default:
2809 break;
2811 *rescode_ptr = code;
2814 /* If comparing an integer against a constant more bits wide,
2815 maybe we can deduce a value of 1 or 0 independent of the data.
2816 Or else truncate the constant now
2817 rather than extend the variable at run time.
2819 This is only interesting if the constant is the wider arg.
2820 Also, it is not safe if the constant is unsigned and the
2821 variable arg is signed, since in this case the variable
2822 would be sign-extended and then regarded as unsigned.
2823 Our technique fails in this case because the lowest/highest
2824 possible unsigned results don't follow naturally from the
2825 lowest/highest possible values of the variable operand.
2826 For just EQ_EXPR and NE_EXPR there is another technique that
2827 could be used: see if the constant can be faithfully represented
2828 in the other operand's type, by truncating it and reextending it
2829 and see if that preserves the constant's value. */
2831 if (!real1 && !real2
2832 && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
2833 && TREE_CODE (primop1) == INTEGER_CST
2834 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
2836 int min_gt, max_gt, min_lt, max_lt;
2837 tree maxval, minval;
2838 /* 1 if comparison is nominally unsigned. */
2839 int unsignedp = TYPE_UNSIGNED (*restype_ptr);
2840 tree val;
2842 type = c_common_signed_or_unsigned_type (unsignedp0,
2843 TREE_TYPE (primop0));
2845 maxval = TYPE_MAX_VALUE (type);
2846 minval = TYPE_MIN_VALUE (type);
2848 if (unsignedp && !unsignedp0)
2849 *restype_ptr = c_common_signed_type (*restype_ptr);
2851 if (TREE_TYPE (primop1) != *restype_ptr)
2853 /* Convert primop1 to target type, but do not introduce
2854 additional overflow. We know primop1 is an int_cst. */
2855 primop1 = force_fit_type (*restype_ptr,
2856 wi::to_wide
2857 (primop1,
2858 TYPE_PRECISION (*restype_ptr)),
2859 0, TREE_OVERFLOW (primop1));
2861 if (type != *restype_ptr)
2863 minval = convert (*restype_ptr, minval);
2864 maxval = convert (*restype_ptr, maxval);
2867 min_gt = tree_int_cst_lt (primop1, minval);
2868 max_gt = tree_int_cst_lt (primop1, maxval);
2869 min_lt = tree_int_cst_lt (minval, primop1);
2870 max_lt = tree_int_cst_lt (maxval, primop1);
2872 val = 0;
2873 /* This used to be a switch, but Genix compiler can't handle that. */
2874 if (code == NE_EXPR)
2876 if (max_lt || min_gt)
2877 val = truthvalue_true_node;
2879 else if (code == EQ_EXPR)
2881 if (max_lt || min_gt)
2882 val = truthvalue_false_node;
2884 else if (code == LT_EXPR)
2886 if (max_lt)
2887 val = truthvalue_true_node;
2888 if (!min_lt)
2889 val = truthvalue_false_node;
2891 else if (code == GT_EXPR)
2893 if (min_gt)
2894 val = truthvalue_true_node;
2895 if (!max_gt)
2896 val = truthvalue_false_node;
2898 else if (code == LE_EXPR)
2900 if (!max_gt)
2901 val = truthvalue_true_node;
2902 if (min_gt)
2903 val = truthvalue_false_node;
2905 else if (code == GE_EXPR)
2907 if (!min_lt)
2908 val = truthvalue_true_node;
2909 if (max_lt)
2910 val = truthvalue_false_node;
2913 /* If primop0 was sign-extended and unsigned comparison specd,
2914 we did a signed comparison above using the signed type bounds.
2915 But the comparison we output must be unsigned.
2917 Also, for inequalities, VAL is no good; but if the signed
2918 comparison had *any* fixed result, it follows that the
2919 unsigned comparison just tests the sign in reverse
2920 (positive values are LE, negative ones GE).
2921 So we can generate an unsigned comparison
2922 against an extreme value of the signed type. */
2924 if (unsignedp && !unsignedp0)
2926 if (val != 0)
2927 switch (code)
2929 case LT_EXPR:
2930 case GE_EXPR:
2931 primop1 = TYPE_MIN_VALUE (type);
2932 val = 0;
2933 break;
2935 case LE_EXPR:
2936 case GT_EXPR:
2937 primop1 = TYPE_MAX_VALUE (type);
2938 val = 0;
2939 break;
2941 default:
2942 break;
2944 type = c_common_unsigned_type (type);
2947 if (TREE_CODE (primop0) != INTEGER_CST
2948 /* Don't warn if it's from a (non-system) macro. */
2949 && !(from_macro_expansion_at
2950 (expansion_point_location_if_in_system_header
2951 (EXPR_LOCATION (primop0)))))
2953 if (val == truthvalue_false_node)
2954 warning_at (loc, OPT_Wtype_limits,
2955 "comparison is always false due to limited range of data type");
2956 if (val == truthvalue_true_node)
2957 warning_at (loc, OPT_Wtype_limits,
2958 "comparison is always true due to limited range of data type");
2961 if (val != 0)
2963 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
2964 if (TREE_SIDE_EFFECTS (primop0))
2965 return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
2966 return val;
2969 /* Value is not predetermined, but do the comparison
2970 in the type of the operand that is not constant.
2971 TYPE is already properly set. */
2974 /* If either arg is decimal float and the other is float, find the
2975 proper common type to use for comparison. */
2976 else if (real1 && real2
2977 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2978 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
2979 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
2981 /* If either arg is decimal float and the other is float, fail. */
2982 else if (real1 && real2
2983 && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2984 || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
2985 return NULL_TREE;
2987 else if (real1 && real2
2988 && (TYPE_PRECISION (TREE_TYPE (primop0))
2989 == TYPE_PRECISION (TREE_TYPE (primop1))))
2990 type = TREE_TYPE (primop0);
2992 /* If args' natural types are both narrower than nominal type
2993 and both extend in the same manner, compare them
2994 in the type of the wider arg.
2995 Otherwise must actually extend both to the nominal
2996 common type lest different ways of extending
2997 alter the result.
2998 (eg, (short)-1 == (unsigned short)-1 should be 0.) */
3000 else if (unsignedp0 == unsignedp1 && real1 == real2
3001 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
3002 && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
3004 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3005 type = c_common_signed_or_unsigned_type (unsignedp0
3006 || TYPE_UNSIGNED (*restype_ptr),
3007 type);
3008 /* Make sure shorter operand is extended the right way
3009 to match the longer operand. */
3010 primop0
3011 = convert (c_common_signed_or_unsigned_type (unsignedp0,
3012 TREE_TYPE (primop0)),
3013 primop0);
3014 primop1
3015 = convert (c_common_signed_or_unsigned_type (unsignedp1,
3016 TREE_TYPE (primop1)),
3017 primop1);
3019 else
3021 /* Here we must do the comparison on the nominal type
3022 using the args exactly as we received them. */
3023 type = *restype_ptr;
3024 primop0 = op0;
3025 primop1 = op1;
3027 if (!real1 && !real2 && integer_zerop (primop1)
3028 && TYPE_UNSIGNED (*restype_ptr))
3030 tree value = NULL_TREE;
3031 /* All unsigned values are >= 0, so we warn. However,
3032 if OP0 is a constant that is >= 0, the signedness of
3033 the comparison isn't an issue, so suppress the
3034 warning. */
3035 bool warn =
3036 warn_type_limits && !in_system_header_at (loc)
3037 && !(TREE_CODE (primop0) == INTEGER_CST
3038 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3039 primop0)))
3040 /* Do not warn for enumeration types. */
3041 && (TREE_CODE (expr_original_type (primop0)) != ENUMERAL_TYPE);
3043 switch (code)
3045 case GE_EXPR:
3046 if (warn)
3047 warning_at (loc, OPT_Wtype_limits,
3048 "comparison of unsigned expression >= 0 is always true");
3049 value = truthvalue_true_node;
3050 break;
3052 case LT_EXPR:
3053 if (warn)
3054 warning_at (loc, OPT_Wtype_limits,
3055 "comparison of unsigned expression < 0 is always false");
3056 value = truthvalue_false_node;
3057 break;
3059 default:
3060 break;
3063 if (value != NULL_TREE)
3065 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3066 if (TREE_SIDE_EFFECTS (primop0))
3067 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3068 primop0, value);
3069 return value;
3074 *op0_ptr = convert (type, primop0);
3075 *op1_ptr = convert (type, primop1);
3077 *restype_ptr = truthvalue_type_node;
3079 return NULL_TREE;
3082 /* Return a tree for the sum or difference (RESULTCODE says which)
3083 of pointer PTROP and integer INTOP. */
3085 tree
3086 pointer_int_sum (location_t loc, enum tree_code resultcode,
3087 tree ptrop, tree intop, bool complain)
3089 tree size_exp, ret;
3091 /* The result is a pointer of the same type that is being added. */
3092 tree result_type = TREE_TYPE (ptrop);
3094 if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
3096 if (complain && warn_pointer_arith)
3097 pedwarn (loc, OPT_Wpointer_arith,
3098 "pointer of type %<void *%> used in arithmetic");
3099 else if (!complain)
3100 return error_mark_node;
3101 size_exp = integer_one_node;
3103 else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3105 if (complain && warn_pointer_arith)
3106 pedwarn (loc, OPT_Wpointer_arith,
3107 "pointer to a function used in arithmetic");
3108 else if (!complain)
3109 return error_mark_node;
3110 size_exp = integer_one_node;
3112 else
3113 size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3115 /* We are manipulating pointer values, so we don't need to warn
3116 about relying on undefined signed overflow. We disable the
3117 warning here because we use integer types so fold won't know that
3118 they are really pointers. */
3119 fold_defer_overflow_warnings ();
3121 /* If what we are about to multiply by the size of the elements
3122 contains a constant term, apply distributive law
3123 and multiply that constant term separately.
3124 This helps produce common subexpressions. */
3125 if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3126 && !TREE_CONSTANT (intop)
3127 && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3128 && TREE_CONSTANT (size_exp)
3129 /* If the constant comes from pointer subtraction,
3130 skip this optimization--it would cause an error. */
3131 && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3132 /* If the constant is unsigned, and smaller than the pointer size,
3133 then we must skip this optimization. This is because it could cause
3134 an overflow error if the constant is negative but INTOP is not. */
3135 && (!TYPE_UNSIGNED (TREE_TYPE (intop))
3136 || (TYPE_PRECISION (TREE_TYPE (intop))
3137 == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3139 enum tree_code subcode = resultcode;
3140 tree int_type = TREE_TYPE (intop);
3141 if (TREE_CODE (intop) == MINUS_EXPR)
3142 subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3143 /* Convert both subexpression types to the type of intop,
3144 because weird cases involving pointer arithmetic
3145 can result in a sum or difference with different type args. */
3146 ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3147 subcode, ptrop,
3148 convert (int_type, TREE_OPERAND (intop, 1)),
3149 true);
3150 intop = convert (int_type, TREE_OPERAND (intop, 0));
3153 /* Convert the integer argument to a type the same size as sizetype
3154 so the multiply won't overflow spuriously. */
3155 if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3156 || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3157 intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3158 TYPE_UNSIGNED (sizetype)), intop);
3160 /* Replace the integer argument with a suitable product by the object size.
3161 Do this multiplication as signed, then convert to the appropriate type
3162 for the pointer operation and disregard an overflow that occurred only
3163 because of the sign-extension change in the latter conversion. */
3165 tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3166 convert (TREE_TYPE (intop), size_exp));
3167 intop = convert (sizetype, t);
3168 if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3169 intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3172 /* Create the sum or difference. */
3173 if (resultcode == MINUS_EXPR)
3174 intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3176 ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3178 fold_undefer_and_ignore_overflow_warnings ();
3180 return ret;
3183 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3184 and if NON_CONST is known not to be permitted in an evaluated part
3185 of a constant expression. */
3187 tree
3188 c_wrap_maybe_const (tree expr, bool non_const)
3190 bool nowarning = TREE_NO_WARNING (expr);
3191 location_t loc = EXPR_LOCATION (expr);
3193 /* This should never be called for C++. */
3194 if (c_dialect_cxx ())
3195 gcc_unreachable ();
3197 /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING. */
3198 STRIP_TYPE_NOPS (expr);
3199 expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3200 C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3201 if (nowarning)
3202 TREE_NO_WARNING (expr) = 1;
3203 protected_set_expr_location (expr, loc);
3205 return expr;
3208 /* Return whether EXPR is a declaration whose address can never be
3209 NULL. */
3211 bool
3212 decl_with_nonnull_addr_p (const_tree expr)
3214 return (DECL_P (expr)
3215 && (TREE_CODE (expr) == PARM_DECL
3216 || TREE_CODE (expr) == LABEL_DECL
3217 || !DECL_WEAK (expr)));
3220 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3221 or for an `if' or `while' statement or ?..: exp. It should already
3222 have been validated to be of suitable type; otherwise, a bad
3223 diagnostic may result.
3225 The EXPR is located at LOCATION.
3227 This preparation consists of taking the ordinary
3228 representation of an expression expr and producing a valid tree
3229 boolean expression describing whether expr is nonzero. We could
3230 simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3231 but we optimize comparisons, &&, ||, and !.
3233 The resulting type should always be `truthvalue_type_node'. */
3235 tree
3236 c_common_truthvalue_conversion (location_t location, tree expr)
3238 switch (TREE_CODE (expr))
3240 case EQ_EXPR: case NE_EXPR: case UNEQ_EXPR: case LTGT_EXPR:
3241 case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
3242 case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3243 case ORDERED_EXPR: case UNORDERED_EXPR:
3244 if (TREE_TYPE (expr) == truthvalue_type_node)
3245 return expr;
3246 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3247 TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3248 goto ret;
3250 case TRUTH_ANDIF_EXPR:
3251 case TRUTH_ORIF_EXPR:
3252 case TRUTH_AND_EXPR:
3253 case TRUTH_OR_EXPR:
3254 case TRUTH_XOR_EXPR:
3255 if (TREE_TYPE (expr) == truthvalue_type_node)
3256 return expr;
3257 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3258 c_common_truthvalue_conversion (location,
3259 TREE_OPERAND (expr, 0)),
3260 c_common_truthvalue_conversion (location,
3261 TREE_OPERAND (expr, 1)));
3262 goto ret;
3264 case TRUTH_NOT_EXPR:
3265 if (TREE_TYPE (expr) == truthvalue_type_node)
3266 return expr;
3267 expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3268 c_common_truthvalue_conversion (location,
3269 TREE_OPERAND (expr, 0)));
3270 goto ret;
3272 case ERROR_MARK:
3273 return expr;
3275 case INTEGER_CST:
3276 if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3277 && !integer_zerop (expr)
3278 && !integer_onep (expr))
3279 warning_at (location, OPT_Wint_in_bool_context,
3280 "enum constant in boolean context");
3281 return integer_zerop (expr) ? truthvalue_false_node
3282 : truthvalue_true_node;
3284 case REAL_CST:
3285 return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3286 ? truthvalue_true_node
3287 : truthvalue_false_node;
3289 case FIXED_CST:
3290 return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3291 &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3292 ? truthvalue_true_node
3293 : truthvalue_false_node;
3295 case FUNCTION_DECL:
3296 expr = build_unary_op (location, ADDR_EXPR, expr, false);
3297 /* Fall through. */
3299 case ADDR_EXPR:
3301 tree inner = TREE_OPERAND (expr, 0);
3302 if (decl_with_nonnull_addr_p (inner))
3304 /* Common Ada/Pascal programmer's mistake. */
3305 warning_at (location,
3306 OPT_Waddress,
3307 "the address of %qD will always evaluate as %<true%>",
3308 inner);
3309 return truthvalue_true_node;
3311 break;
3314 case COMPLEX_EXPR:
3315 expr = build_binary_op (EXPR_LOCATION (expr),
3316 (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3317 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3318 c_common_truthvalue_conversion (location,
3319 TREE_OPERAND (expr, 0)),
3320 c_common_truthvalue_conversion (location,
3321 TREE_OPERAND (expr, 1)),
3322 false);
3323 goto ret;
3325 case NEGATE_EXPR:
3326 case ABS_EXPR:
3327 case FLOAT_EXPR:
3328 case EXCESS_PRECISION_EXPR:
3329 /* These don't change whether an object is nonzero or zero. */
3330 return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3332 case LROTATE_EXPR:
3333 case RROTATE_EXPR:
3334 /* These don't change whether an object is zero or nonzero, but
3335 we can't ignore them if their second arg has side-effects. */
3336 if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3338 expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3339 TREE_OPERAND (expr, 1),
3340 c_common_truthvalue_conversion
3341 (location, TREE_OPERAND (expr, 0)));
3342 goto ret;
3344 else
3345 return c_common_truthvalue_conversion (location,
3346 TREE_OPERAND (expr, 0));
3348 case MULT_EXPR:
3349 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3350 "%<*%> in boolean context, suggest %<&&%> instead");
3351 break;
3353 case LSHIFT_EXPR:
3354 /* We will only warn on signed shifts here, because the majority of
3355 false positive warnings happen in code where unsigned arithmetic
3356 was used in anticipation of a possible overflow.
3357 Furthermore, if we see an unsigned type here we know that the
3358 result of the shift is not subject to integer promotion rules. */
3359 if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3360 && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3361 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3362 "%<<<%> in boolean context, did you mean %<<%> ?");
3363 break;
3365 case COND_EXPR:
3366 if (warn_int_in_bool_context
3367 && !from_macro_definition_at (EXPR_LOCATION (expr)))
3369 tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3370 tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3371 if (TREE_CODE (val1) == INTEGER_CST
3372 && TREE_CODE (val2) == INTEGER_CST
3373 && !integer_zerop (val1)
3374 && !integer_zerop (val2)
3375 && (!integer_onep (val1)
3376 || !integer_onep (val2)))
3377 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3378 "?: using integer constants in boolean context, "
3379 "the expression will always evaluate to %<true%>");
3380 else if ((TREE_CODE (val1) == INTEGER_CST
3381 && !integer_zerop (val1)
3382 && !integer_onep (val1))
3383 || (TREE_CODE (val2) == INTEGER_CST
3384 && !integer_zerop (val2)
3385 && !integer_onep (val2)))
3386 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3387 "?: using integer constants in boolean context");
3389 /* Distribute the conversion into the arms of a COND_EXPR. */
3390 if (c_dialect_cxx ())
3391 /* Avoid premature folding. */
3392 break;
3393 else
3395 int w = warn_int_in_bool_context;
3396 warn_int_in_bool_context = 0;
3397 /* Folding will happen later for C. */
3398 expr = build3 (COND_EXPR, truthvalue_type_node,
3399 TREE_OPERAND (expr, 0),
3400 c_common_truthvalue_conversion (location,
3401 TREE_OPERAND (expr, 1)),
3402 c_common_truthvalue_conversion (location,
3403 TREE_OPERAND (expr, 2)));
3404 warn_int_in_bool_context = w;
3405 goto ret;
3408 CASE_CONVERT:
3410 tree totype = TREE_TYPE (expr);
3411 tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3413 if (POINTER_TYPE_P (totype)
3414 && !c_inhibit_evaluation_warnings
3415 && TREE_CODE (fromtype) == REFERENCE_TYPE)
3417 tree inner = expr;
3418 STRIP_NOPS (inner);
3420 if (DECL_P (inner))
3421 warning_at (location,
3422 OPT_Waddress,
3423 "the compiler can assume that the address of "
3424 "%qD will always evaluate to %<true%>",
3425 inner);
3428 /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3429 since that affects how `default_conversion' will behave. */
3430 if (TREE_CODE (totype) == REFERENCE_TYPE
3431 || TREE_CODE (fromtype) == REFERENCE_TYPE)
3432 break;
3433 /* Don't strip a conversion from C++0x scoped enum, since they
3434 don't implicitly convert to other types. */
3435 if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3436 && ENUM_IS_SCOPED (fromtype))
3437 break;
3438 /* If this isn't narrowing the argument, we can ignore it. */
3439 if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3440 return c_common_truthvalue_conversion (location,
3441 TREE_OPERAND (expr, 0));
3443 break;
3445 case MODIFY_EXPR:
3446 if (!TREE_NO_WARNING (expr)
3447 && warn_parentheses)
3449 warning_at (location, OPT_Wparentheses,
3450 "suggest parentheses around assignment used as "
3451 "truth value");
3452 TREE_NO_WARNING (expr) = 1;
3454 break;
3456 default:
3457 break;
3460 if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3462 tree t = save_expr (expr);
3463 expr = (build_binary_op
3464 (EXPR_LOCATION (expr),
3465 (TREE_SIDE_EFFECTS (expr)
3466 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3467 c_common_truthvalue_conversion
3468 (location,
3469 build_unary_op (location, REALPART_EXPR, t, false)),
3470 c_common_truthvalue_conversion
3471 (location,
3472 build_unary_op (location, IMAGPART_EXPR, t, false)),
3473 false));
3474 goto ret;
3477 if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
3479 tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3480 FCONST0 (TYPE_MODE
3481 (TREE_TYPE (expr))));
3482 return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3484 else
3485 return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3487 ret:
3488 protected_set_expr_location (expr, location);
3489 return expr;
3492 static void def_builtin_1 (enum built_in_function fncode,
3493 const char *name,
3494 enum built_in_class fnclass,
3495 tree fntype, tree libtype,
3496 bool both_p, bool fallback_p, bool nonansi_p,
3497 tree fnattrs, bool implicit_p);
3500 /* Apply the TYPE_QUALS to the new DECL. */
3502 void
3503 c_apply_type_quals_to_decl (int type_quals, tree decl)
3505 tree type = TREE_TYPE (decl);
3507 if (type == error_mark_node)
3508 return;
3510 if ((type_quals & TYPE_QUAL_CONST)
3511 || (type && TREE_CODE (type) == REFERENCE_TYPE))
3512 /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3513 constructor can produce constant init, so rely on cp_finish_decl to
3514 clear TREE_READONLY if the variable has non-constant init. */
3515 TREE_READONLY (decl) = 1;
3516 if (type_quals & TYPE_QUAL_VOLATILE)
3518 TREE_SIDE_EFFECTS (decl) = 1;
3519 TREE_THIS_VOLATILE (decl) = 1;
3521 if (type_quals & TYPE_QUAL_RESTRICT)
3523 while (type && TREE_CODE (type) == ARRAY_TYPE)
3524 /* Allow 'restrict' on arrays of pointers.
3525 FIXME currently we just ignore it. */
3526 type = TREE_TYPE (type);
3527 if (!type
3528 || !POINTER_TYPE_P (type)
3529 || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3530 error ("invalid use of %<restrict%>");
3534 /* Return the typed-based alias set for T, which may be an expression
3535 or a type. Return -1 if we don't do anything special. */
3537 alias_set_type
3538 c_common_get_alias_set (tree t)
3540 /* For VLAs, use the alias set of the element type rather than the
3541 default of alias set 0 for types compared structurally. */
3542 if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3544 if (TREE_CODE (t) == ARRAY_TYPE)
3545 return get_alias_set (TREE_TYPE (t));
3546 return -1;
3549 /* That's all the expressions we handle specially. */
3550 if (!TYPE_P (t))
3551 return -1;
3553 /* The C standard guarantees that any object may be accessed via an
3554 lvalue that has character type. */
3555 if (t == char_type_node
3556 || t == signed_char_type_node
3557 || t == unsigned_char_type_node)
3558 return 0;
3560 /* The C standard specifically allows aliasing between signed and
3561 unsigned variants of the same type. We treat the signed
3562 variant as canonical. */
3563 if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
3565 tree t1 = c_common_signed_type (t);
3567 /* t1 == t can happen for boolean nodes which are always unsigned. */
3568 if (t1 != t)
3569 return get_alias_set (t1);
3572 return -1;
3575 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3576 the IS_SIZEOF parameter indicates which operator is being applied.
3577 The COMPLAIN flag controls whether we should diagnose possibly
3578 ill-formed constructs or not. LOC is the location of the SIZEOF or
3579 TYPEOF operator. If MIN_ALIGNOF, the least alignment required for
3580 a type in any context should be returned, rather than the normal
3581 alignment for that type. */
3583 tree
3584 c_sizeof_or_alignof_type (location_t loc,
3585 tree type, bool is_sizeof, bool min_alignof,
3586 int complain)
3588 const char *op_name;
3589 tree value = NULL;
3590 enum tree_code type_code = TREE_CODE (type);
3592 op_name = is_sizeof ? "sizeof" : "__alignof__";
3594 if (type_code == FUNCTION_TYPE)
3596 if (is_sizeof)
3598 if (complain && warn_pointer_arith)
3599 pedwarn (loc, OPT_Wpointer_arith,
3600 "invalid application of %<sizeof%> to a function type");
3601 else if (!complain)
3602 return error_mark_node;
3603 value = size_one_node;
3605 else
3607 if (complain)
3609 if (c_dialect_cxx ())
3610 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3611 "%<alignof%> applied to a function type");
3612 else
3613 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3614 "%<_Alignof%> applied to a function type");
3616 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3619 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3621 if (type_code == VOID_TYPE
3622 && complain && warn_pointer_arith)
3623 pedwarn (loc, OPT_Wpointer_arith,
3624 "invalid application of %qs to a void type", op_name);
3625 else if (!complain)
3626 return error_mark_node;
3627 value = size_one_node;
3629 else if (!COMPLETE_TYPE_P (type)
3630 && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3632 if (complain)
3633 error_at (loc, "invalid application of %qs to incomplete type %qT",
3634 op_name, type);
3635 return error_mark_node;
3637 else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3638 && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3640 if (complain)
3641 error_at (loc, "invalid application of %qs to array type %qT of "
3642 "incomplete element type", op_name, type);
3643 return error_mark_node;
3645 else
3647 if (is_sizeof)
3648 /* Convert in case a char is more than one unit. */
3649 value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3650 size_int (TYPE_PRECISION (char_type_node)
3651 / BITS_PER_UNIT));
3652 else if (min_alignof)
3653 value = size_int (min_align_of_type (type));
3654 else
3655 value = size_int (TYPE_ALIGN_UNIT (type));
3658 /* VALUE will have the middle-end integer type sizetype.
3659 However, we should really return a value of type `size_t',
3660 which is just a typedef for an ordinary integer type. */
3661 value = fold_convert_loc (loc, size_type_node, value);
3663 return value;
3666 /* Implement the __alignof keyword: Return the minimum required
3667 alignment of EXPR, measured in bytes. For VAR_DECLs,
3668 FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3669 from an "aligned" __attribute__ specification). LOC is the
3670 location of the ALIGNOF operator. */
3672 tree
3673 c_alignof_expr (location_t loc, tree expr)
3675 tree t;
3677 if (VAR_OR_FUNCTION_DECL_P (expr))
3678 t = size_int (DECL_ALIGN_UNIT (expr));
3680 else if (TREE_CODE (expr) == COMPONENT_REF
3681 && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3683 error_at (loc, "%<__alignof%> applied to a bit-field");
3684 t = size_one_node;
3686 else if (TREE_CODE (expr) == COMPONENT_REF
3687 && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3688 t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3690 else if (INDIRECT_REF_P (expr))
3692 tree t = TREE_OPERAND (expr, 0);
3693 tree best = t;
3694 int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3696 while (CONVERT_EXPR_P (t)
3697 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3699 int thisalign;
3701 t = TREE_OPERAND (t, 0);
3702 thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3703 if (thisalign > bestalign)
3704 best = t, bestalign = thisalign;
3706 return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
3708 else
3709 return c_alignof (loc, TREE_TYPE (expr));
3711 return fold_convert_loc (loc, size_type_node, t);
3714 /* Handle C and C++ default attributes. */
3716 enum built_in_attribute
3718 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
3719 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
3720 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
3721 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
3722 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
3723 #include "builtin-attrs.def"
3724 #undef DEF_ATTR_NULL_TREE
3725 #undef DEF_ATTR_INT
3726 #undef DEF_ATTR_STRING
3727 #undef DEF_ATTR_IDENT
3728 #undef DEF_ATTR_TREE_LIST
3729 ATTR_LAST
3732 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
3734 static void c_init_attributes (void);
3736 enum c_builtin_type
3738 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
3739 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
3740 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
3741 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
3742 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3743 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3744 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
3745 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3746 ARG6) NAME,
3747 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3748 ARG6, ARG7) NAME,
3749 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3750 ARG6, ARG7, ARG8) NAME,
3751 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3752 ARG6, ARG7, ARG8, ARG9) NAME,
3753 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3754 ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
3755 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3756 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
3757 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
3758 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
3759 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
3760 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3761 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3762 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3763 NAME,
3764 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3765 ARG6) NAME,
3766 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3767 ARG6, ARG7) NAME,
3768 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
3769 #include "builtin-types.def"
3770 #undef DEF_PRIMITIVE_TYPE
3771 #undef DEF_FUNCTION_TYPE_0
3772 #undef DEF_FUNCTION_TYPE_1
3773 #undef DEF_FUNCTION_TYPE_2
3774 #undef DEF_FUNCTION_TYPE_3
3775 #undef DEF_FUNCTION_TYPE_4
3776 #undef DEF_FUNCTION_TYPE_5
3777 #undef DEF_FUNCTION_TYPE_6
3778 #undef DEF_FUNCTION_TYPE_7
3779 #undef DEF_FUNCTION_TYPE_8
3780 #undef DEF_FUNCTION_TYPE_9
3781 #undef DEF_FUNCTION_TYPE_10
3782 #undef DEF_FUNCTION_TYPE_11
3783 #undef DEF_FUNCTION_TYPE_VAR_0
3784 #undef DEF_FUNCTION_TYPE_VAR_1
3785 #undef DEF_FUNCTION_TYPE_VAR_2
3786 #undef DEF_FUNCTION_TYPE_VAR_3
3787 #undef DEF_FUNCTION_TYPE_VAR_4
3788 #undef DEF_FUNCTION_TYPE_VAR_5
3789 #undef DEF_FUNCTION_TYPE_VAR_6
3790 #undef DEF_FUNCTION_TYPE_VAR_7
3791 #undef DEF_POINTER_TYPE
3792 BT_LAST
3795 typedef enum c_builtin_type builtin_type;
3797 /* A temporary array for c_common_nodes_and_builtins. Used in
3798 communication with def_fn_type. */
3799 static tree builtin_types[(int) BT_LAST + 1];
3801 /* A helper function for c_common_nodes_and_builtins. Build function type
3802 for DEF with return type RET and N arguments. If VAR is true, then the
3803 function should be variadic after those N arguments.
3805 Takes special care not to ICE if any of the types involved are
3806 error_mark_node, which indicates that said type is not in fact available
3807 (see builtin_type_for_size). In which case the function type as a whole
3808 should be error_mark_node. */
3810 static void
3811 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
3813 tree t;
3814 tree *args = XALLOCAVEC (tree, n);
3815 va_list list;
3816 int i;
3818 va_start (list, n);
3819 for (i = 0; i < n; ++i)
3821 builtin_type a = (builtin_type) va_arg (list, int);
3822 t = builtin_types[a];
3823 if (t == error_mark_node)
3824 goto egress;
3825 args[i] = t;
3828 t = builtin_types[ret];
3829 if (t == error_mark_node)
3830 goto egress;
3831 if (var)
3832 t = build_varargs_function_type_array (t, n, args);
3833 else
3834 t = build_function_type_array (t, n, args);
3836 egress:
3837 builtin_types[def] = t;
3838 va_end (list);
3841 /* Build builtin functions common to both C and C++ language
3842 frontends. */
3844 static void
3845 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
3847 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
3848 builtin_types[ENUM] = VALUE;
3849 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
3850 def_fn_type (ENUM, RETURN, 0, 0);
3851 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
3852 def_fn_type (ENUM, RETURN, 0, 1, ARG1);
3853 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
3854 def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
3855 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3856 def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
3857 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3858 def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
3859 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3860 def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3861 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3862 ARG6) \
3863 def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3864 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3865 ARG6, ARG7) \
3866 def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3867 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3868 ARG6, ARG7, ARG8) \
3869 def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3870 ARG7, ARG8);
3871 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3872 ARG6, ARG7, ARG8, ARG9) \
3873 def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3874 ARG7, ARG8, ARG9);
3875 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3876 ARG6, ARG7, ARG8, ARG9, ARG10) \
3877 def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3878 ARG7, ARG8, ARG9, ARG10);
3879 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3880 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
3881 def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3882 ARG7, ARG8, ARG9, ARG10, ARG11);
3883 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
3884 def_fn_type (ENUM, RETURN, 1, 0);
3885 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
3886 def_fn_type (ENUM, RETURN, 1, 1, ARG1);
3887 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
3888 def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
3889 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3890 def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
3891 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3892 def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
3893 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3894 def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3895 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3896 ARG6) \
3897 def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3898 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3899 ARG6, ARG7) \
3900 def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3901 #define DEF_POINTER_TYPE(ENUM, TYPE) \
3902 builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
3904 #include "builtin-types.def"
3906 #undef DEF_PRIMITIVE_TYPE
3907 #undef DEF_FUNCTION_TYPE_0
3908 #undef DEF_FUNCTION_TYPE_1
3909 #undef DEF_FUNCTION_TYPE_2
3910 #undef DEF_FUNCTION_TYPE_3
3911 #undef DEF_FUNCTION_TYPE_4
3912 #undef DEF_FUNCTION_TYPE_5
3913 #undef DEF_FUNCTION_TYPE_6
3914 #undef DEF_FUNCTION_TYPE_7
3915 #undef DEF_FUNCTION_TYPE_8
3916 #undef DEF_FUNCTION_TYPE_9
3917 #undef DEF_FUNCTION_TYPE_10
3918 #undef DEF_FUNCTION_TYPE_11
3919 #undef DEF_FUNCTION_TYPE_VAR_0
3920 #undef DEF_FUNCTION_TYPE_VAR_1
3921 #undef DEF_FUNCTION_TYPE_VAR_2
3922 #undef DEF_FUNCTION_TYPE_VAR_3
3923 #undef DEF_FUNCTION_TYPE_VAR_4
3924 #undef DEF_FUNCTION_TYPE_VAR_5
3925 #undef DEF_FUNCTION_TYPE_VAR_6
3926 #undef DEF_FUNCTION_TYPE_VAR_7
3927 #undef DEF_POINTER_TYPE
3928 builtin_types[(int) BT_LAST] = NULL_TREE;
3930 c_init_attributes ();
3932 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
3933 NONANSI_P, ATTRS, IMPLICIT, COND) \
3934 if (NAME && COND) \
3935 def_builtin_1 (ENUM, NAME, CLASS, \
3936 builtin_types[(int) TYPE], \
3937 builtin_types[(int) LIBTYPE], \
3938 BOTH_P, FALLBACK_P, NONANSI_P, \
3939 built_in_attributes[(int) ATTRS], IMPLICIT);
3940 #include "builtins.def"
3942 targetm.init_builtins ();
3944 build_common_builtin_nodes ();
3947 /* Like get_identifier, but avoid warnings about null arguments when
3948 the argument may be NULL for targets where GCC lacks stdint.h type
3949 information. */
3951 static inline tree
3952 c_get_ident (const char *id)
3954 return get_identifier (id);
3957 /* Build tree nodes and builtin functions common to both C and C++ language
3958 frontends. */
3960 void
3961 c_common_nodes_and_builtins (void)
3963 int char16_type_size;
3964 int char32_type_size;
3965 int wchar_type_size;
3966 tree array_domain_type;
3967 tree va_list_ref_type_node;
3968 tree va_list_arg_type_node;
3969 int i;
3971 build_common_tree_nodes (flag_signed_char);
3973 /* Define `int' and `char' first so that dbx will output them first. */
3974 record_builtin_type (RID_INT, NULL, integer_type_node);
3975 record_builtin_type (RID_CHAR, "char", char_type_node);
3977 /* `signed' is the same as `int'. FIXME: the declarations of "signed",
3978 "unsigned long", "long long unsigned" and "unsigned short" were in C++
3979 but not C. Are the conditionals here needed? */
3980 if (c_dialect_cxx ())
3981 record_builtin_type (RID_SIGNED, NULL, integer_type_node);
3982 record_builtin_type (RID_LONG, "long int", long_integer_type_node);
3983 record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
3984 record_builtin_type (RID_MAX, "long unsigned int",
3985 long_unsigned_type_node);
3987 for (i = 0; i < NUM_INT_N_ENTS; i ++)
3989 char name[25];
3991 sprintf (name, "__int%d", int_n_data[i].bitsize);
3992 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
3993 int_n_trees[i].signed_type);
3994 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
3995 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
3998 if (c_dialect_cxx ())
3999 record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
4000 record_builtin_type (RID_MAX, "long long int",
4001 long_long_integer_type_node);
4002 record_builtin_type (RID_MAX, "long long unsigned int",
4003 long_long_unsigned_type_node);
4004 if (c_dialect_cxx ())
4005 record_builtin_type (RID_MAX, "long long unsigned",
4006 long_long_unsigned_type_node);
4007 record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4008 record_builtin_type (RID_MAX, "short unsigned int",
4009 short_unsigned_type_node);
4010 if (c_dialect_cxx ())
4011 record_builtin_type (RID_MAX, "unsigned short",
4012 short_unsigned_type_node);
4014 /* Define both `signed char' and `unsigned char'. */
4015 record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4016 record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4018 /* These are types that c_common_type_for_size and
4019 c_common_type_for_mode use. */
4020 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4021 TYPE_DECL, NULL_TREE,
4022 intQI_type_node));
4023 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4024 TYPE_DECL, NULL_TREE,
4025 intHI_type_node));
4026 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4027 TYPE_DECL, NULL_TREE,
4028 intSI_type_node));
4029 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4030 TYPE_DECL, NULL_TREE,
4031 intDI_type_node));
4032 #if HOST_BITS_PER_WIDE_INT >= 64
4033 /* Note that this is different than the __int128 type that's part of
4034 the generic __intN support. */
4035 if (targetm.scalar_mode_supported_p (TImode))
4036 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4037 TYPE_DECL,
4038 get_identifier ("__int128_t"),
4039 intTI_type_node));
4040 #endif
4041 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4042 TYPE_DECL, NULL_TREE,
4043 unsigned_intQI_type_node));
4044 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4045 TYPE_DECL, NULL_TREE,
4046 unsigned_intHI_type_node));
4047 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4048 TYPE_DECL, NULL_TREE,
4049 unsigned_intSI_type_node));
4050 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4051 TYPE_DECL, NULL_TREE,
4052 unsigned_intDI_type_node));
4053 #if HOST_BITS_PER_WIDE_INT >= 64
4054 if (targetm.scalar_mode_supported_p (TImode))
4055 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4056 TYPE_DECL,
4057 get_identifier ("__uint128_t"),
4058 unsigned_intTI_type_node));
4059 #endif
4061 /* Create the widest literal types. */
4062 if (targetm.scalar_mode_supported_p (TImode))
4064 widest_integer_literal_type_node = intTI_type_node;
4065 widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4067 else
4069 widest_integer_literal_type_node = intDI_type_node;
4070 widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4073 signed_size_type_node = c_common_signed_type (size_type_node);
4075 pid_type_node =
4076 TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4078 record_builtin_type (RID_FLOAT, NULL, float_type_node);
4079 record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4080 record_builtin_type (RID_MAX, "long double", long_double_type_node);
4082 if (!c_dialect_cxx ())
4083 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4084 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4085 record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4086 FLOATN_NX_TYPE_NODE (i));
4088 /* Only supported decimal floating point extension if the target
4089 actually supports underlying modes. */
4090 if (targetm.scalar_mode_supported_p (SDmode)
4091 && targetm.scalar_mode_supported_p (DDmode)
4092 && targetm.scalar_mode_supported_p (TDmode))
4094 record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4095 record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4096 record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4099 if (targetm.fixed_point_supported_p ())
4101 record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4102 record_builtin_type (RID_FRACT, NULL, fract_type_node);
4103 record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4104 record_builtin_type (RID_MAX, "long long _Fract",
4105 long_long_fract_type_node);
4106 record_builtin_type (RID_MAX, "unsigned short _Fract",
4107 unsigned_short_fract_type_node);
4108 record_builtin_type (RID_MAX, "unsigned _Fract",
4109 unsigned_fract_type_node);
4110 record_builtin_type (RID_MAX, "unsigned long _Fract",
4111 unsigned_long_fract_type_node);
4112 record_builtin_type (RID_MAX, "unsigned long long _Fract",
4113 unsigned_long_long_fract_type_node);
4114 record_builtin_type (RID_MAX, "_Sat short _Fract",
4115 sat_short_fract_type_node);
4116 record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4117 record_builtin_type (RID_MAX, "_Sat long _Fract",
4118 sat_long_fract_type_node);
4119 record_builtin_type (RID_MAX, "_Sat long long _Fract",
4120 sat_long_long_fract_type_node);
4121 record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4122 sat_unsigned_short_fract_type_node);
4123 record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4124 sat_unsigned_fract_type_node);
4125 record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4126 sat_unsigned_long_fract_type_node);
4127 record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4128 sat_unsigned_long_long_fract_type_node);
4129 record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4130 record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4131 record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4132 record_builtin_type (RID_MAX, "long long _Accum",
4133 long_long_accum_type_node);
4134 record_builtin_type (RID_MAX, "unsigned short _Accum",
4135 unsigned_short_accum_type_node);
4136 record_builtin_type (RID_MAX, "unsigned _Accum",
4137 unsigned_accum_type_node);
4138 record_builtin_type (RID_MAX, "unsigned long _Accum",
4139 unsigned_long_accum_type_node);
4140 record_builtin_type (RID_MAX, "unsigned long long _Accum",
4141 unsigned_long_long_accum_type_node);
4142 record_builtin_type (RID_MAX, "_Sat short _Accum",
4143 sat_short_accum_type_node);
4144 record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4145 record_builtin_type (RID_MAX, "_Sat long _Accum",
4146 sat_long_accum_type_node);
4147 record_builtin_type (RID_MAX, "_Sat long long _Accum",
4148 sat_long_long_accum_type_node);
4149 record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4150 sat_unsigned_short_accum_type_node);
4151 record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4152 sat_unsigned_accum_type_node);
4153 record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4154 sat_unsigned_long_accum_type_node);
4155 record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4156 sat_unsigned_long_long_accum_type_node);
4160 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4161 TYPE_DECL,
4162 get_identifier ("complex int"),
4163 complex_integer_type_node));
4164 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4165 TYPE_DECL,
4166 get_identifier ("complex float"),
4167 complex_float_type_node));
4168 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4169 TYPE_DECL,
4170 get_identifier ("complex double"),
4171 complex_double_type_node));
4172 lang_hooks.decls.pushdecl
4173 (build_decl (UNKNOWN_LOCATION,
4174 TYPE_DECL, get_identifier ("complex long double"),
4175 complex_long_double_type_node));
4177 if (!c_dialect_cxx ())
4178 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4179 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4181 char buf[30];
4182 sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4183 floatn_nx_types[i].extended ? "x" : "");
4184 lang_hooks.decls.pushdecl
4185 (build_decl (UNKNOWN_LOCATION,
4186 TYPE_DECL,
4187 get_identifier (buf),
4188 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4191 if (c_dialect_cxx ())
4193 /* For C++, make fileptr_type_node a distinct void * type until
4194 FILE type is defined. Likewise for const struct tm*. */
4195 for (unsigned i = 0;
4196 i < sizeof (builtin_structptr_types)
4197 / sizeof (builtin_structptr_type);
4198 ++i)
4199 builtin_structptr_types[i].node =
4200 build_variant_type_copy (builtin_structptr_types[i].base);
4204 record_builtin_type (RID_VOID, NULL, void_type_node);
4206 /* Set the TYPE_NAME for any variants that were built before
4207 record_builtin_type gave names to the built-in types. */
4209 tree void_name = TYPE_NAME (void_type_node);
4210 TYPE_NAME (void_type_node) = NULL_TREE;
4211 TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4212 = void_name;
4213 TYPE_NAME (void_type_node) = void_name;
4216 void_list_node = build_void_list_node ();
4218 /* Make a type to be the domain of a few array types
4219 whose domains don't really matter.
4220 200 is small enough that it always fits in size_t
4221 and large enough that it can hold most function names for the
4222 initializations of __FUNCTION__ and __PRETTY_FUNCTION__. */
4223 array_domain_type = build_index_type (size_int (200));
4225 /* Make a type for arrays of characters.
4226 With luck nothing will ever really depend on the length of this
4227 array type. */
4228 char_array_type_node
4229 = build_array_type (char_type_node, array_domain_type);
4231 string_type_node = build_pointer_type (char_type_node);
4232 const_string_type_node
4233 = build_pointer_type (build_qualified_type
4234 (char_type_node, TYPE_QUAL_CONST));
4236 /* This is special for C++ so functions can be overloaded. */
4237 wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4238 wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4239 wchar_type_size = TYPE_PRECISION (wchar_type_node);
4240 underlying_wchar_type_node = wchar_type_node;
4241 if (c_dialect_cxx ())
4243 if (TYPE_UNSIGNED (wchar_type_node))
4244 wchar_type_node = make_unsigned_type (wchar_type_size);
4245 else
4246 wchar_type_node = make_signed_type (wchar_type_size);
4247 record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4250 /* This is for wide string constants. */
4251 wchar_array_type_node
4252 = build_array_type (wchar_type_node, array_domain_type);
4254 /* Define 'char16_t'. */
4255 char16_type_node = get_identifier (CHAR16_TYPE);
4256 char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4257 char16_type_size = TYPE_PRECISION (char16_type_node);
4258 if (c_dialect_cxx ())
4260 char16_type_node = make_unsigned_type (char16_type_size);
4262 if (cxx_dialect >= cxx11)
4263 record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4266 /* This is for UTF-16 string constants. */
4267 char16_array_type_node
4268 = build_array_type (char16_type_node, array_domain_type);
4270 /* Define 'char32_t'. */
4271 char32_type_node = get_identifier (CHAR32_TYPE);
4272 char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4273 char32_type_size = TYPE_PRECISION (char32_type_node);
4274 if (c_dialect_cxx ())
4276 char32_type_node = make_unsigned_type (char32_type_size);
4278 if (cxx_dialect >= cxx11)
4279 record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4282 /* This is for UTF-32 string constants. */
4283 char32_array_type_node
4284 = build_array_type (char32_type_node, array_domain_type);
4286 wint_type_node =
4287 TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4289 intmax_type_node =
4290 TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4291 uintmax_type_node =
4292 TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4294 if (SIG_ATOMIC_TYPE)
4295 sig_atomic_type_node =
4296 TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4297 if (INT8_TYPE)
4298 int8_type_node =
4299 TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4300 if (INT16_TYPE)
4301 int16_type_node =
4302 TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4303 if (INT32_TYPE)
4304 int32_type_node =
4305 TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4306 if (INT64_TYPE)
4307 int64_type_node =
4308 TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4309 if (UINT8_TYPE)
4310 uint8_type_node =
4311 TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4312 if (UINT16_TYPE)
4313 c_uint16_type_node = uint16_type_node =
4314 TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4315 if (UINT32_TYPE)
4316 c_uint32_type_node = uint32_type_node =
4317 TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4318 if (UINT64_TYPE)
4319 c_uint64_type_node = uint64_type_node =
4320 TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4321 if (INT_LEAST8_TYPE)
4322 int_least8_type_node =
4323 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4324 if (INT_LEAST16_TYPE)
4325 int_least16_type_node =
4326 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4327 if (INT_LEAST32_TYPE)
4328 int_least32_type_node =
4329 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4330 if (INT_LEAST64_TYPE)
4331 int_least64_type_node =
4332 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4333 if (UINT_LEAST8_TYPE)
4334 uint_least8_type_node =
4335 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4336 if (UINT_LEAST16_TYPE)
4337 uint_least16_type_node =
4338 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4339 if (UINT_LEAST32_TYPE)
4340 uint_least32_type_node =
4341 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4342 if (UINT_LEAST64_TYPE)
4343 uint_least64_type_node =
4344 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4345 if (INT_FAST8_TYPE)
4346 int_fast8_type_node =
4347 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4348 if (INT_FAST16_TYPE)
4349 int_fast16_type_node =
4350 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4351 if (INT_FAST32_TYPE)
4352 int_fast32_type_node =
4353 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4354 if (INT_FAST64_TYPE)
4355 int_fast64_type_node =
4356 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4357 if (UINT_FAST8_TYPE)
4358 uint_fast8_type_node =
4359 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4360 if (UINT_FAST16_TYPE)
4361 uint_fast16_type_node =
4362 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4363 if (UINT_FAST32_TYPE)
4364 uint_fast32_type_node =
4365 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4366 if (UINT_FAST64_TYPE)
4367 uint_fast64_type_node =
4368 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4369 if (INTPTR_TYPE)
4370 intptr_type_node =
4371 TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4372 if (UINTPTR_TYPE)
4373 uintptr_type_node =
4374 TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4376 default_function_type
4377 = build_varargs_function_type_list (integer_type_node, NULL_TREE);
4378 unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4380 lang_hooks.decls.pushdecl
4381 (build_decl (UNKNOWN_LOCATION,
4382 TYPE_DECL, get_identifier ("__builtin_va_list"),
4383 va_list_type_node));
4384 if (targetm.enum_va_list_p)
4386 int l;
4387 const char *pname;
4388 tree ptype;
4390 for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4392 lang_hooks.decls.pushdecl
4393 (build_decl (UNKNOWN_LOCATION,
4394 TYPE_DECL, get_identifier (pname),
4395 ptype));
4400 if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4402 va_list_arg_type_node = va_list_ref_type_node =
4403 build_pointer_type (TREE_TYPE (va_list_type_node));
4405 else
4407 va_list_arg_type_node = va_list_type_node;
4408 va_list_ref_type_node = build_reference_type (va_list_type_node);
4411 if (!flag_preprocess_only)
4412 c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4414 main_identifier_node = get_identifier ("main");
4416 /* Create the built-in __null node. It is important that this is
4417 not shared. */
4418 null_node = make_int_cst (1, 1);
4419 TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4421 /* Since builtin_types isn't gc'ed, don't export these nodes. */
4422 memset (builtin_types, 0, sizeof (builtin_types));
4425 /* The number of named compound-literals generated thus far. */
4426 static GTY(()) int compound_literal_number;
4428 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal. */
4430 void
4431 set_compound_literal_name (tree decl)
4433 char *name;
4434 ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4435 compound_literal_number);
4436 compound_literal_number++;
4437 DECL_NAME (decl) = get_identifier (name);
4440 /* build_va_arg helper function. Return a VA_ARG_EXPR with location LOC, type
4441 TYPE and operand OP. */
4443 static tree
4444 build_va_arg_1 (location_t loc, tree type, tree op)
4446 tree expr = build1 (VA_ARG_EXPR, type, op);
4447 SET_EXPR_LOCATION (expr, loc);
4448 return expr;
4451 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4452 va_arg (EXPR, TYPE) at source location LOC. */
4454 tree
4455 build_va_arg (location_t loc, tree expr, tree type)
4457 tree va_type = TREE_TYPE (expr);
4458 tree canon_va_type = (va_type == error_mark_node
4459 ? error_mark_node
4460 : targetm.canonical_va_list_type (va_type));
4462 if (va_type == error_mark_node
4463 || canon_va_type == NULL_TREE)
4465 if (canon_va_type == NULL_TREE)
4466 error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4468 /* Let's handle things neutrallly, if expr:
4469 - has undeclared type, or
4470 - is not an va_list type. */
4471 return build_va_arg_1 (loc, type, error_mark_node);
4474 if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4476 /* Case 1: Not an array type. */
4478 /* Take the address, to get '&ap'. Note that &ap is not a va_list
4479 type. */
4480 mark_addressable (expr);
4481 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4483 return build_va_arg_1 (loc, type, expr);
4486 /* Case 2: Array type.
4488 Background:
4490 For contrast, let's start with the simple case (case 1). If
4491 canon_va_type is not an array type, but say a char *, then when
4492 passing-by-value a va_list, the type of the va_list param decl is
4493 the same as for another va_list decl (all ap's are char *):
4495 f2_1 (char * ap)
4496 D.1815 = VA_ARG (&ap, 0B, 1);
4497 return D.1815;
4499 f2 (int i)
4500 char * ap.0;
4501 char * ap;
4502 __builtin_va_start (&ap, 0);
4503 ap.0 = ap;
4504 res = f2_1 (ap.0);
4505 __builtin_va_end (&ap);
4506 D.1812 = res;
4507 return D.1812;
4509 However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4510 va_list the type of the va_list param decl (case 2b, struct * ap) is not
4511 the same as for another va_list decl (case 2a, struct ap[1]).
4513 f2_1 (struct * ap)
4514 D.1844 = VA_ARG (ap, 0B, 0);
4515 return D.1844;
4517 f2 (int i)
4518 struct ap[1];
4519 __builtin_va_start (&ap, 0);
4520 res = f2_1 (&ap);
4521 __builtin_va_end (&ap);
4522 D.1841 = res;
4523 return D.1841;
4525 Case 2b is different because:
4526 - on the callee side, the parm decl has declared type va_list, but
4527 grokdeclarator changes the type of the parm decl to a pointer to the
4528 array elem type.
4529 - on the caller side, the pass-by-value uses &ap.
4531 We unify these two cases (case 2a: va_list is array type,
4532 case 2b: va_list is pointer to array elem type), by adding '&' for the
4533 array type case, such that we have a pointer to array elem in both
4534 cases. */
4536 if (TREE_CODE (va_type) == ARRAY_TYPE)
4538 /* Case 2a: va_list is array type. */
4540 /* Take the address, to get '&ap'. Make sure it's a pointer to array
4541 elem type. */
4542 mark_addressable (expr);
4543 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4544 expr);
4546 /* Verify that &ap is still recognized as having va_list type. */
4547 tree canon_expr_type
4548 = targetm.canonical_va_list_type (TREE_TYPE (expr));
4549 gcc_assert (canon_expr_type != NULL_TREE);
4551 else
4553 /* Case 2b: va_list is pointer to array elem type. */
4554 gcc_assert (POINTER_TYPE_P (va_type));
4556 /* Comparison as in std_canonical_va_list_type. */
4557 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4558 == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4560 /* Don't take the address. We've already got '&ap'. */
4564 return build_va_arg_1 (loc, type, expr);
4568 /* Linked list of disabled built-in functions. */
4570 struct disabled_builtin
4572 const char *name;
4573 struct disabled_builtin *next;
4575 static disabled_builtin *disabled_builtins = NULL;
4577 static bool builtin_function_disabled_p (const char *);
4579 /* Disable a built-in function specified by -fno-builtin-NAME. If NAME
4580 begins with "__builtin_", give an error. */
4582 void
4583 disable_builtin_function (const char *name)
4585 if (strncmp (name, "__builtin_", strlen ("__builtin_")) == 0)
4586 error ("cannot disable built-in function %qs", name);
4587 else
4589 disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4590 new_disabled_builtin->name = name;
4591 new_disabled_builtin->next = disabled_builtins;
4592 disabled_builtins = new_disabled_builtin;
4597 /* Return true if the built-in function NAME has been disabled, false
4598 otherwise. */
4600 static bool
4601 builtin_function_disabled_p (const char *name)
4603 disabled_builtin *p;
4604 for (p = disabled_builtins; p != NULL; p = p->next)
4606 if (strcmp (name, p->name) == 0)
4607 return true;
4609 return false;
4613 /* Worker for DEF_BUILTIN.
4614 Possibly define a builtin function with one or two names.
4615 Does not declare a non-__builtin_ function if flag_no_builtin, or if
4616 nonansi_p and flag_no_nonansi_builtin. */
4618 static void
4619 def_builtin_1 (enum built_in_function fncode,
4620 const char *name,
4621 enum built_in_class fnclass,
4622 tree fntype, tree libtype,
4623 bool both_p, bool fallback_p, bool nonansi_p,
4624 tree fnattrs, bool implicit_p)
4626 tree decl;
4627 const char *libname;
4629 if (fntype == error_mark_node)
4630 return;
4632 gcc_assert ((!both_p && !fallback_p)
4633 || !strncmp (name, "__builtin_",
4634 strlen ("__builtin_")));
4636 libname = name + strlen ("__builtin_");
4637 decl = add_builtin_function (name, fntype, fncode, fnclass,
4638 (fallback_p ? libname : NULL),
4639 fnattrs);
4641 set_builtin_decl (fncode, decl, implicit_p);
4643 if (both_p
4644 && !flag_no_builtin && !builtin_function_disabled_p (libname)
4645 && !(nonansi_p && flag_no_nonansi_builtin))
4646 add_builtin_function (libname, libtype, fncode, fnclass,
4647 NULL, fnattrs);
4650 /* Nonzero if the type T promotes to int. This is (nearly) the
4651 integral promotions defined in ISO C99 6.3.1.1/2. */
4653 bool
4654 c_promoting_integer_type_p (const_tree t)
4656 switch (TREE_CODE (t))
4658 case INTEGER_TYPE:
4659 return (TYPE_MAIN_VARIANT (t) == char_type_node
4660 || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4661 || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4662 || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4663 || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
4664 || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
4666 case ENUMERAL_TYPE:
4667 /* ??? Technically all enumerations not larger than an int
4668 promote to an int. But this is used along code paths
4669 that only want to notice a size change. */
4670 return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
4672 case BOOLEAN_TYPE:
4673 return true;
4675 default:
4676 return false;
4680 /* Return 1 if PARMS specifies a fixed number of parameters
4681 and none of their types is affected by default promotions. */
4683 bool
4684 self_promoting_args_p (const_tree parms)
4686 const_tree t;
4687 for (t = parms; t; t = TREE_CHAIN (t))
4689 tree type = TREE_VALUE (t);
4691 if (type == error_mark_node)
4692 continue;
4694 if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
4695 return false;
4697 if (type == NULL_TREE)
4698 return false;
4700 if (TYPE_MAIN_VARIANT (type) == float_type_node)
4701 return false;
4703 if (c_promoting_integer_type_p (type))
4704 return false;
4706 return true;
4709 /* Recursively remove any '*' or '&' operator from TYPE. */
4710 tree
4711 strip_pointer_operator (tree t)
4713 while (POINTER_TYPE_P (t))
4714 t = TREE_TYPE (t);
4715 return t;
4718 /* Recursively remove pointer or array type from TYPE. */
4719 tree
4720 strip_pointer_or_array_types (tree t)
4722 while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
4723 t = TREE_TYPE (t);
4724 return t;
4727 /* Used to compare case labels. K1 and K2 are actually tree nodes
4728 representing case labels, or NULL_TREE for a `default' label.
4729 Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
4730 K2, and 0 if K1 and K2 are equal. */
4733 case_compare (splay_tree_key k1, splay_tree_key k2)
4735 /* Consider a NULL key (such as arises with a `default' label) to be
4736 smaller than anything else. */
4737 if (!k1)
4738 return k2 ? -1 : 0;
4739 else if (!k2)
4740 return k1 ? 1 : 0;
4742 return tree_int_cst_compare ((tree) k1, (tree) k2);
4745 /* Process a case label, located at LOC, for the range LOW_VALUE
4746 ... HIGH_VALUE. If LOW_VALUE and HIGH_VALUE are both NULL_TREE
4747 then this case label is actually a `default' label. If only
4748 HIGH_VALUE is NULL_TREE, then case label was declared using the
4749 usual C/C++ syntax, rather than the GNU case range extension.
4750 CASES is a tree containing all the case ranges processed so far;
4751 COND is the condition for the switch-statement itself.
4752 OUTSIDE_RANGE_P says whether there was a case value that doesn't
4753 fit into the range of the ORIG_TYPE. Returns the CASE_LABEL_EXPR
4754 created, or ERROR_MARK_NODE if no CASE_LABEL_EXPR is created. */
4756 tree
4757 c_add_case_label (location_t loc, splay_tree cases, tree cond, tree orig_type,
4758 tree low_value, tree high_value, bool *outside_range_p)
4760 tree type;
4761 tree label;
4762 tree case_label;
4763 splay_tree_node node;
4765 /* Create the LABEL_DECL itself. */
4766 label = create_artificial_label (loc);
4768 /* If there was an error processing the switch condition, bail now
4769 before we get more confused. */
4770 if (!cond || cond == error_mark_node)
4771 goto error_out;
4773 if ((low_value && TREE_TYPE (low_value)
4774 && POINTER_TYPE_P (TREE_TYPE (low_value)))
4775 || (high_value && TREE_TYPE (high_value)
4776 && POINTER_TYPE_P (TREE_TYPE (high_value))))
4778 error_at (loc, "pointers are not permitted as case values");
4779 goto error_out;
4782 /* Case ranges are a GNU extension. */
4783 if (high_value)
4784 pedwarn (loc, OPT_Wpedantic,
4785 "range expressions in switch statements are non-standard");
4787 type = TREE_TYPE (cond);
4788 if (low_value)
4790 low_value = check_case_value (loc, low_value);
4791 low_value = convert_and_check (loc, type, low_value);
4792 if (low_value == error_mark_node)
4793 goto error_out;
4795 if (high_value)
4797 high_value = check_case_value (loc, high_value);
4798 high_value = convert_and_check (loc, type, high_value);
4799 if (high_value == error_mark_node)
4800 goto error_out;
4803 if (low_value && high_value)
4805 /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
4806 really a case range, even though it was written that way.
4807 Remove the HIGH_VALUE to simplify later processing. */
4808 if (tree_int_cst_equal (low_value, high_value))
4809 high_value = NULL_TREE;
4810 else if (!tree_int_cst_lt (low_value, high_value))
4811 warning_at (loc, 0, "empty range specified");
4814 /* See if the case is in range of the type of the original testing
4815 expression. If both low_value and high_value are out of range,
4816 don't insert the case label and return NULL_TREE. */
4817 if (low_value
4818 && !check_case_bounds (loc, type, orig_type,
4819 &low_value, high_value ? &high_value : NULL,
4820 outside_range_p))
4821 return NULL_TREE;
4823 /* Look up the LOW_VALUE in the table of case labels we already
4824 have. */
4825 node = splay_tree_lookup (cases, (splay_tree_key) low_value);
4826 /* If there was not an exact match, check for overlapping ranges.
4827 There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
4828 that's a `default' label and the only overlap is an exact match. */
4829 if (!node && (low_value || high_value))
4831 splay_tree_node low_bound;
4832 splay_tree_node high_bound;
4834 /* Even though there wasn't an exact match, there might be an
4835 overlap between this case range and another case range.
4836 Since we've (inductively) not allowed any overlapping case
4837 ranges, we simply need to find the greatest low case label
4838 that is smaller that LOW_VALUE, and the smallest low case
4839 label that is greater than LOW_VALUE. If there is an overlap
4840 it will occur in one of these two ranges. */
4841 low_bound = splay_tree_predecessor (cases,
4842 (splay_tree_key) low_value);
4843 high_bound = splay_tree_successor (cases,
4844 (splay_tree_key) low_value);
4846 /* Check to see if the LOW_BOUND overlaps. It is smaller than
4847 the LOW_VALUE, so there is no need to check unless the
4848 LOW_BOUND is in fact itself a case range. */
4849 if (low_bound
4850 && CASE_HIGH ((tree) low_bound->value)
4851 && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
4852 low_value) >= 0)
4853 node = low_bound;
4854 /* Check to see if the HIGH_BOUND overlaps. The low end of that
4855 range is bigger than the low end of the current range, so we
4856 are only interested if the current range is a real range, and
4857 not an ordinary case label. */
4858 else if (high_bound
4859 && high_value
4860 && (tree_int_cst_compare ((tree) high_bound->key,
4861 high_value)
4862 <= 0))
4863 node = high_bound;
4865 /* If there was an overlap, issue an error. */
4866 if (node)
4868 tree duplicate = CASE_LABEL ((tree) node->value);
4870 if (high_value)
4872 error_at (loc, "duplicate (or overlapping) case value");
4873 inform (DECL_SOURCE_LOCATION (duplicate),
4874 "this is the first entry overlapping that value");
4876 else if (low_value)
4878 error_at (loc, "duplicate case value") ;
4879 inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
4881 else
4883 error_at (loc, "multiple default labels in one switch");
4884 inform (DECL_SOURCE_LOCATION (duplicate),
4885 "this is the first default label");
4887 goto error_out;
4890 /* Add a CASE_LABEL to the statement-tree. */
4891 case_label = add_stmt (build_case_label (low_value, high_value, label));
4892 /* Register this case label in the splay tree. */
4893 splay_tree_insert (cases,
4894 (splay_tree_key) low_value,
4895 (splay_tree_value) case_label);
4897 return case_label;
4899 error_out:
4900 /* Add a label so that the back-end doesn't think that the beginning of
4901 the switch is unreachable. Note that we do not add a case label, as
4902 that just leads to duplicates and thence to failure later on. */
4903 if (!cases->root)
4905 tree t = create_artificial_label (loc);
4906 add_stmt (build_stmt (loc, LABEL_EXPR, t));
4908 return error_mark_node;
4911 /* Subroutine of c_switch_covers_all_cases_p, called via
4912 splay_tree_foreach. Return 1 if it doesn't cover all the cases.
4913 ARGS[0] is initially NULL and after the first iteration is the
4914 so far highest case label. ARGS[1] is the minimum of SWITCH_COND's
4915 type. */
4917 static int
4918 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
4920 tree label = (tree) node->value;
4921 tree *args = (tree *) data;
4923 /* If there is a default case, we shouldn't have called this. */
4924 gcc_assert (CASE_LOW (label));
4926 if (args[0] == NULL_TREE)
4928 if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
4929 return 1;
4931 else if (wi::add (wi::to_widest (args[0]), 1)
4932 != wi::to_widest (CASE_LOW (label)))
4933 return 1;
4934 if (CASE_HIGH (label))
4935 args[0] = CASE_HIGH (label);
4936 else
4937 args[0] = CASE_LOW (label);
4938 return 0;
4941 /* Return true if switch with CASES and switch condition with type
4942 covers all possible values in the case labels. */
4944 bool
4945 c_switch_covers_all_cases_p (splay_tree cases, tree type)
4947 /* If there is default:, this is always the case. */
4948 splay_tree_node default_node
4949 = splay_tree_lookup (cases, (splay_tree_key) NULL);
4950 if (default_node)
4951 return true;
4953 if (!INTEGRAL_TYPE_P (type))
4954 return false;
4956 tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
4957 if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
4958 return false;
4960 /* If there are no cases at all, or if the highest case label
4961 is smaller than TYPE_MAX_VALUE, return false. */
4962 if (args[0] == NULL_TREE
4963 || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
4964 return false;
4966 return true;
4969 /* Finish an expression taking the address of LABEL (an
4970 IDENTIFIER_NODE). Returns an expression for the address.
4972 LOC is the location for the expression returned. */
4974 tree
4975 finish_label_address_expr (tree label, location_t loc)
4977 tree result;
4979 pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
4981 if (label == error_mark_node)
4982 return error_mark_node;
4984 label = lookup_label (label);
4985 if (label == NULL_TREE)
4986 result = null_pointer_node;
4987 else
4989 TREE_USED (label) = 1;
4990 result = build1 (ADDR_EXPR, ptr_type_node, label);
4991 /* The current function is not necessarily uninlinable.
4992 Computed gotos are incompatible with inlining, but the value
4993 here could be used only in a diagnostic, for example. */
4994 protected_set_expr_location (result, loc);
4997 return result;
5001 /* Given a boolean expression ARG, return a tree representing an increment
5002 or decrement (as indicated by CODE) of ARG. The front end must check for
5003 invalid cases (e.g., decrement in C++). */
5004 tree
5005 boolean_increment (enum tree_code code, tree arg)
5007 tree val;
5008 tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5010 arg = stabilize_reference (arg);
5011 switch (code)
5013 case PREINCREMENT_EXPR:
5014 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5015 break;
5016 case POSTINCREMENT_EXPR:
5017 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5018 arg = save_expr (arg);
5019 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5020 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5021 break;
5022 case PREDECREMENT_EXPR:
5023 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5024 invert_truthvalue_loc (input_location, arg));
5025 break;
5026 case POSTDECREMENT_EXPR:
5027 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5028 invert_truthvalue_loc (input_location, arg));
5029 arg = save_expr (arg);
5030 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5031 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5032 break;
5033 default:
5034 gcc_unreachable ();
5036 TREE_SIDE_EFFECTS (val) = 1;
5037 return val;
5040 /* Built-in macros for stddef.h and stdint.h, that require macros
5041 defined in this file. */
5042 void
5043 c_stddef_cpp_builtins(void)
5045 builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5046 builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5047 builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5048 builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5049 builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5050 builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5051 builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5052 builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5053 if (SIG_ATOMIC_TYPE)
5054 builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5055 if (INT8_TYPE)
5056 builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5057 if (INT16_TYPE)
5058 builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5059 if (INT32_TYPE)
5060 builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5061 if (INT64_TYPE)
5062 builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5063 if (UINT8_TYPE)
5064 builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5065 if (UINT16_TYPE)
5066 builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5067 if (UINT32_TYPE)
5068 builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5069 if (UINT64_TYPE)
5070 builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5071 if (INT_LEAST8_TYPE)
5072 builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5073 if (INT_LEAST16_TYPE)
5074 builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5075 if (INT_LEAST32_TYPE)
5076 builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5077 if (INT_LEAST64_TYPE)
5078 builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5079 if (UINT_LEAST8_TYPE)
5080 builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5081 if (UINT_LEAST16_TYPE)
5082 builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5083 if (UINT_LEAST32_TYPE)
5084 builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5085 if (UINT_LEAST64_TYPE)
5086 builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5087 if (INT_FAST8_TYPE)
5088 builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5089 if (INT_FAST16_TYPE)
5090 builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5091 if (INT_FAST32_TYPE)
5092 builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5093 if (INT_FAST64_TYPE)
5094 builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5095 if (UINT_FAST8_TYPE)
5096 builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5097 if (UINT_FAST16_TYPE)
5098 builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5099 if (UINT_FAST32_TYPE)
5100 builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5101 if (UINT_FAST64_TYPE)
5102 builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5103 if (INTPTR_TYPE)
5104 builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5105 if (UINTPTR_TYPE)
5106 builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5109 static void
5110 c_init_attributes (void)
5112 /* Fill in the built_in_attributes array. */
5113 #define DEF_ATTR_NULL_TREE(ENUM) \
5114 built_in_attributes[(int) ENUM] = NULL_TREE;
5115 #define DEF_ATTR_INT(ENUM, VALUE) \
5116 built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5117 #define DEF_ATTR_STRING(ENUM, VALUE) \
5118 built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5119 #define DEF_ATTR_IDENT(ENUM, STRING) \
5120 built_in_attributes[(int) ENUM] = get_identifier (STRING);
5121 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5122 built_in_attributes[(int) ENUM] \
5123 = tree_cons (built_in_attributes[(int) PURPOSE], \
5124 built_in_attributes[(int) VALUE], \
5125 built_in_attributes[(int) CHAIN]);
5126 #include "builtin-attrs.def"
5127 #undef DEF_ATTR_NULL_TREE
5128 #undef DEF_ATTR_INT
5129 #undef DEF_ATTR_IDENT
5130 #undef DEF_ATTR_TREE_LIST
5133 /* Check whether ALIGN is a valid user-specified alignment. If so,
5134 return its base-2 log; if not, output an error and return -1. If
5135 ALLOW_ZERO then 0 is valid and should result in a return of -1 with
5136 no error. */
5138 check_user_alignment (const_tree align, bool allow_zero)
5140 int i;
5142 if (error_operand_p (align))
5143 return -1;
5144 if (TREE_CODE (align) != INTEGER_CST
5145 || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5147 error ("requested alignment is not an integer constant");
5148 return -1;
5150 else if (allow_zero && integer_zerop (align))
5151 return -1;
5152 else if (tree_int_cst_sgn (align) == -1
5153 || (i = tree_log2 (align)) == -1)
5155 error ("requested alignment is not a positive power of 2");
5156 return -1;
5158 else if (i >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5160 error ("requested alignment is too large");
5161 return -1;
5163 return i;
5166 /* Determine the ELF symbol visibility for DECL, which is either a
5167 variable or a function. It is an error to use this function if a
5168 definition of DECL is not available in this translation unit.
5169 Returns true if the final visibility has been determined by this
5170 function; false if the caller is free to make additional
5171 modifications. */
5173 bool
5174 c_determine_visibility (tree decl)
5176 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5178 /* If the user explicitly specified the visibility with an
5179 attribute, honor that. DECL_VISIBILITY will have been set during
5180 the processing of the attribute. We check for an explicit
5181 attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5182 to distinguish the use of an attribute from the use of a "#pragma
5183 GCC visibility push(...)"; in the latter case we still want other
5184 considerations to be able to overrule the #pragma. */
5185 if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5186 || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5187 && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5188 || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5189 return true;
5191 /* Set default visibility to whatever the user supplied with
5192 visibility_specified depending on #pragma GCC visibility. */
5193 if (!DECL_VISIBILITY_SPECIFIED (decl))
5195 if (visibility_options.inpragma
5196 || DECL_VISIBILITY (decl) != default_visibility)
5198 DECL_VISIBILITY (decl) = default_visibility;
5199 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5200 /* If visibility changed and DECL already has DECL_RTL, ensure
5201 symbol flags are updated. */
5202 if (((VAR_P (decl) && TREE_STATIC (decl))
5203 || TREE_CODE (decl) == FUNCTION_DECL)
5204 && DECL_RTL_SET_P (decl))
5205 make_decl_rtl (decl);
5208 return false;
5211 /* Data to communicate through check_function_arguments_recurse between
5212 check_function_nonnull and check_nonnull_arg. */
5214 struct nonnull_arg_ctx
5216 location_t loc;
5217 bool warned_p;
5220 /* Check the argument list of a function call for null in argument slots
5221 that are marked as requiring a non-null pointer argument. The NARGS
5222 arguments are passed in the array ARGARRAY. Return true if we have
5223 warned. */
5225 static bool
5226 check_function_nonnull (location_t loc, tree attrs, int nargs, tree *argarray)
5228 tree a;
5229 int i;
5231 attrs = lookup_attribute ("nonnull", attrs);
5232 if (attrs == NULL_TREE)
5233 return false;
5235 a = attrs;
5236 /* See if any of the nonnull attributes has no arguments. If so,
5237 then every pointer argument is checked (in which case the check
5238 for pointer type is done in check_nonnull_arg). */
5239 if (TREE_VALUE (a) != NULL_TREE)
5241 a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5242 while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5244 struct nonnull_arg_ctx ctx = { loc, false };
5245 if (a != NULL_TREE)
5246 for (i = 0; i < nargs; i++)
5247 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5248 i + 1);
5249 else
5251 /* Walk the argument list. If we encounter an argument number we
5252 should check for non-null, do it. */
5253 for (i = 0; i < nargs; i++)
5255 for (a = attrs; ; a = TREE_CHAIN (a))
5257 a = lookup_attribute ("nonnull", a);
5258 if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5259 break;
5262 if (a != NULL_TREE)
5263 check_function_arguments_recurse (check_nonnull_arg, &ctx,
5264 argarray[i], i + 1);
5267 return ctx.warned_p;
5270 /* Check that the Nth argument of a function call (counting backwards
5271 from the end) is a (pointer)0. The NARGS arguments are passed in the
5272 array ARGARRAY. */
5274 static void
5275 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5277 tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5279 if (attr)
5281 int len = 0;
5282 int pos = 0;
5283 tree sentinel;
5284 function_args_iterator iter;
5285 tree t;
5287 /* Skip over the named arguments. */
5288 FOREACH_FUNCTION_ARGS (fntype, t, iter)
5290 if (len == nargs)
5291 break;
5292 len++;
5295 if (TREE_VALUE (attr))
5297 tree p = TREE_VALUE (TREE_VALUE (attr));
5298 pos = TREE_INT_CST_LOW (p);
5301 /* The sentinel must be one of the varargs, i.e.
5302 in position >= the number of fixed arguments. */
5303 if ((nargs - 1 - pos) < len)
5305 warning (OPT_Wformat_,
5306 "not enough variable arguments to fit a sentinel");
5307 return;
5310 /* Validate the sentinel. */
5311 sentinel = argarray[nargs - 1 - pos];
5312 if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5313 || !integer_zerop (sentinel))
5314 /* Although __null (in C++) is only an integer we allow it
5315 nevertheless, as we are guaranteed that it's exactly
5316 as wide as a pointer, and we don't want to force
5317 users to cast the NULL they have written there.
5318 We warn with -Wstrict-null-sentinel, though. */
5319 && (warn_strict_null_sentinel || null_node != sentinel))
5320 warning (OPT_Wformat_, "missing sentinel in function call");
5324 /* Check that the same argument isn't passed to restrict arguments
5325 and other arguments. */
5327 static void
5328 check_function_restrict (const_tree fndecl, const_tree fntype,
5329 int nargs, tree *argarray)
5331 int i;
5332 tree parms = TYPE_ARG_TYPES (fntype);
5334 if (fndecl
5335 && TREE_CODE (fndecl) == FUNCTION_DECL)
5337 /* Skip checking built-ins here. They are checked in more
5338 detail elsewhere. */
5339 if (DECL_BUILT_IN (fndecl)
5340 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
5341 return;
5343 if (DECL_ARGUMENTS (fndecl))
5344 parms = DECL_ARGUMENTS (fndecl);
5347 for (i = 0; i < nargs; i++)
5348 TREE_VISITED (argarray[i]) = 0;
5350 for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5352 tree type;
5353 if (TREE_CODE (parms) == PARM_DECL)
5355 type = TREE_TYPE (parms);
5356 parms = DECL_CHAIN (parms);
5358 else
5360 type = TREE_VALUE (parms);
5361 parms = TREE_CHAIN (parms);
5363 if (POINTER_TYPE_P (type)
5364 && TYPE_RESTRICT (type)
5365 && !TYPE_READONLY (TREE_TYPE (type)))
5366 warn_for_restrict (i, argarray, nargs);
5369 for (i = 0; i < nargs; i++)
5370 TREE_VISITED (argarray[i]) = 0;
5373 /* Helper for check_function_nonnull; given a list of operands which
5374 must be non-null in ARGS, determine if operand PARAM_NUM should be
5375 checked. */
5377 static bool
5378 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5380 unsigned HOST_WIDE_INT arg_num = 0;
5382 for (; args; args = TREE_CHAIN (args))
5384 bool found = get_nonnull_operand (TREE_VALUE (args), &arg_num);
5386 gcc_assert (found);
5388 if (arg_num == param_num)
5389 return true;
5391 return false;
5394 /* Check that the function argument PARAM (which is operand number
5395 PARAM_NUM) is non-null. This is called by check_function_nonnull
5396 via check_function_arguments_recurse. */
5398 static void
5399 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5401 struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5403 /* Just skip checking the argument if it's not a pointer. This can
5404 happen if the "nonnull" attribute was given without an operand
5405 list (which means to check every pointer argument). */
5407 if (TREE_CODE (TREE_TYPE (param)) != POINTER_TYPE)
5408 return;
5410 /* When not optimizing diagnose the simple cases of null arguments.
5411 When optimization is enabled defer the checking until expansion
5412 when more cases can be detected. */
5413 if (integer_zerop (param))
5415 warning_at (pctx->loc, OPT_Wnonnull, "null argument where non-null "
5416 "required (argument %lu)", (unsigned long) param_num);
5417 pctx->warned_p = true;
5421 /* Helper for nonnull attribute handling; fetch the operand number
5422 from the attribute argument list. */
5424 bool
5425 get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5427 /* Verify the arg number is a small constant. */
5428 if (tree_fits_uhwi_p (arg_num_expr))
5430 *valp = tree_to_uhwi (arg_num_expr);
5431 return true;
5433 else
5434 return false;
5437 /* Arguments being collected for optimization. */
5438 typedef const char *const_char_p; /* For DEF_VEC_P. */
5439 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5442 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5443 options in ARGS. ATTR_P is true if this is for attribute(optimize), and
5444 false for #pragma GCC optimize. */
5446 bool
5447 parse_optimize_options (tree args, bool attr_p)
5449 bool ret = true;
5450 unsigned opt_argc;
5451 unsigned i;
5452 const char **opt_argv;
5453 struct cl_decoded_option *decoded_options;
5454 unsigned int decoded_options_count;
5455 tree ap;
5457 /* Build up argv vector. Just in case the string is stored away, use garbage
5458 collected strings. */
5459 vec_safe_truncate (optimize_args, 0);
5460 vec_safe_push (optimize_args, (const char *) NULL);
5462 for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5464 tree value = TREE_VALUE (ap);
5466 if (TREE_CODE (value) == INTEGER_CST)
5468 char buffer[20];
5469 sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5470 vec_safe_push (optimize_args, ggc_strdup (buffer));
5473 else if (TREE_CODE (value) == STRING_CST)
5475 /* Split string into multiple substrings. */
5476 size_t len = TREE_STRING_LENGTH (value);
5477 char *p = ASTRDUP (TREE_STRING_POINTER (value));
5478 char *end = p + len;
5479 char *comma;
5480 char *next_p = p;
5482 while (next_p != NULL)
5484 size_t len2;
5485 char *q, *r;
5487 p = next_p;
5488 comma = strchr (p, ',');
5489 if (comma)
5491 len2 = comma - p;
5492 *comma = '\0';
5493 next_p = comma+1;
5495 else
5497 len2 = end - p;
5498 next_p = NULL;
5501 r = q = (char *) ggc_alloc_atomic (len2 + 3);
5503 /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5504 options. */
5505 if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5507 ret = false;
5508 if (attr_p)
5509 warning (OPT_Wattributes,
5510 "bad option %qs to attribute %<optimize%>", p);
5511 else
5512 warning (OPT_Wpragmas,
5513 "bad option %qs to pragma %<optimize%>", p);
5514 continue;
5517 if (*p != '-')
5519 *r++ = '-';
5521 /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5522 itself is -Os, and any other switch begins with a -f. */
5523 if ((*p >= '0' && *p <= '9')
5524 || (p[0] == 's' && p[1] == '\0'))
5525 *r++ = 'O';
5526 else if (*p != 'O')
5527 *r++ = 'f';
5530 memcpy (r, p, len2);
5531 r[len2] = '\0';
5532 vec_safe_push (optimize_args, (const char *) q);
5538 opt_argc = optimize_args->length ();
5539 opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5541 for (i = 1; i < opt_argc; i++)
5542 opt_argv[i] = (*optimize_args)[i];
5544 /* Now parse the options. */
5545 decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
5546 &decoded_options,
5547 &decoded_options_count);
5548 /* Drop non-Optimization options. */
5549 unsigned j = 1;
5550 for (i = 1; i < decoded_options_count; ++i)
5552 if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
5554 ret = false;
5555 if (attr_p)
5556 warning (OPT_Wattributes,
5557 "bad option %qs to attribute %<optimize%>",
5558 decoded_options[i].orig_option_with_args_text);
5559 else
5560 warning (OPT_Wpragmas,
5561 "bad option %qs to pragma %<optimize%>",
5562 decoded_options[i].orig_option_with_args_text);
5563 continue;
5565 if (i != j)
5566 decoded_options[j] = decoded_options[i];
5567 j++;
5569 decoded_options_count = j;
5570 /* And apply them. */
5571 decode_options (&global_options, &global_options_set,
5572 decoded_options, decoded_options_count,
5573 input_location, global_dc, NULL);
5575 targetm.override_options_after_change();
5577 optimize_args->truncate (0);
5578 return ret;
5581 /* Check whether ATTR is a valid attribute fallthrough. */
5583 bool
5584 attribute_fallthrough_p (tree attr)
5586 if (attr == error_mark_node)
5587 return false;
5588 tree t = lookup_attribute ("fallthrough", attr);
5589 if (t == NULL_TREE)
5590 return false;
5591 /* This attribute shall appear at most once in each attribute-list. */
5592 if (lookup_attribute ("fallthrough", TREE_CHAIN (t)))
5593 warning (OPT_Wattributes, "%<fallthrough%> attribute specified multiple "
5594 "times");
5595 /* No attribute-argument-clause shall be present. */
5596 else if (TREE_VALUE (t) != NULL_TREE)
5597 warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
5598 "a parameter");
5599 /* Warn if other attributes are found. */
5600 for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
5602 tree name = get_attribute_name (t);
5603 if (!is_attribute_p ("fallthrough", name))
5604 warning (OPT_Wattributes, "%qE attribute ignored", name);
5606 return true;
5610 /* Check for valid arguments being passed to a function with FNTYPE.
5611 There are NARGS arguments in the array ARGARRAY. LOC should be used for
5612 diagnostics. Return true if -Wnonnull warning has been diagnosed. */
5613 bool
5614 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
5615 int nargs, tree *argarray, vec<location_t> *arglocs)
5617 bool warned_p = false;
5619 /* Check for null being passed in a pointer argument that must be
5620 non-null. We also need to do this if format checking is enabled. */
5622 if (warn_nonnull)
5623 warned_p = check_function_nonnull (loc, TYPE_ATTRIBUTES (fntype),
5624 nargs, argarray);
5626 /* Check for errors in format strings. */
5628 if (warn_format || warn_suggest_attribute_format)
5629 check_function_format (TYPE_ATTRIBUTES (fntype), nargs, argarray, arglocs);
5631 if (warn_format)
5632 check_function_sentinel (fntype, nargs, argarray);
5634 if (warn_restrict)
5635 check_function_restrict (fndecl, fntype, nargs, argarray);
5636 return warned_p;
5639 /* Generic argument checking recursion routine. PARAM is the argument to
5640 be checked. PARAM_NUM is the number of the argument. CALLBACK is invoked
5641 once the argument is resolved. CTX is context for the callback. */
5642 void
5643 check_function_arguments_recurse (void (*callback)
5644 (void *, tree, unsigned HOST_WIDE_INT),
5645 void *ctx, tree param,
5646 unsigned HOST_WIDE_INT param_num)
5648 if (CONVERT_EXPR_P (param)
5649 && (TYPE_PRECISION (TREE_TYPE (param))
5650 == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
5652 /* Strip coercion. */
5653 check_function_arguments_recurse (callback, ctx,
5654 TREE_OPERAND (param, 0), param_num);
5655 return;
5658 if (TREE_CODE (param) == CALL_EXPR)
5660 tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
5661 tree attrs;
5662 bool found_format_arg = false;
5664 /* See if this is a call to a known internationalization function
5665 that modifies a format arg. Such a function may have multiple
5666 format_arg attributes (for example, ngettext). */
5668 for (attrs = TYPE_ATTRIBUTES (type);
5669 attrs;
5670 attrs = TREE_CHAIN (attrs))
5671 if (is_attribute_p ("format_arg", TREE_PURPOSE (attrs)))
5673 tree inner_arg;
5674 tree format_num_expr;
5675 int format_num;
5676 int i;
5677 call_expr_arg_iterator iter;
5679 /* Extract the argument number, which was previously checked
5680 to be valid. */
5681 format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
5683 format_num = tree_to_uhwi (format_num_expr);
5685 for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
5686 inner_arg != NULL_TREE;
5687 inner_arg = next_call_expr_arg (&iter), i++)
5688 if (i == format_num)
5690 check_function_arguments_recurse (callback, ctx,
5691 inner_arg, param_num);
5692 found_format_arg = true;
5693 break;
5697 /* If we found a format_arg attribute and did a recursive check,
5698 we are done with checking this argument. Otherwise, we continue
5699 and this will be considered a non-literal. */
5700 if (found_format_arg)
5701 return;
5704 if (TREE_CODE (param) == COND_EXPR)
5706 /* Simplify to avoid warning for an impossible case. */
5707 param = fold_for_warn (param);
5708 if (TREE_CODE (param) == COND_EXPR)
5710 /* Check both halves of the conditional expression. */
5711 check_function_arguments_recurse (callback, ctx,
5712 TREE_OPERAND (param, 1),
5713 param_num);
5714 check_function_arguments_recurse (callback, ctx,
5715 TREE_OPERAND (param, 2),
5716 param_num);
5717 return;
5721 (*callback) (ctx, param, param_num);
5724 /* Checks for a builtin function FNDECL that the number of arguments
5725 NARGS against the required number REQUIRED and issues an error if
5726 there is a mismatch. Returns true if the number of arguments is
5727 correct, otherwise false. LOC is the location of FNDECL. */
5729 static bool
5730 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
5731 int required)
5733 if (nargs < required)
5735 error_at (loc, "too few arguments to function %qE", fndecl);
5736 return false;
5738 else if (nargs > required)
5740 error_at (loc, "too many arguments to function %qE", fndecl);
5741 return false;
5743 return true;
5746 /* Helper macro for check_builtin_function_arguments. */
5747 #define ARG_LOCATION(N) \
5748 (arg_loc.is_empty () \
5749 ? EXPR_LOC_OR_LOC (args[(N)], input_location) \
5750 : expansion_point_location (arg_loc[(N)]))
5752 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
5753 Returns false if there was an error, otherwise true. LOC is the
5754 location of the function; ARG_LOC is a vector of locations of the
5755 arguments. */
5757 bool
5758 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
5759 tree fndecl, int nargs, tree *args)
5761 if (!DECL_BUILT_IN (fndecl)
5762 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
5763 return true;
5765 switch (DECL_FUNCTION_CODE (fndecl))
5767 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
5768 if (!tree_fits_uhwi_p (args[2]))
5770 error_at (ARG_LOCATION (2),
5771 "third argument to function %qE must be a constant integer",
5772 fndecl);
5773 return false;
5775 /* fall through */
5777 case BUILT_IN_ALLOCA_WITH_ALIGN:
5779 /* Get the requested alignment (in bits) if it's a constant
5780 integer expression. */
5781 unsigned HOST_WIDE_INT align
5782 = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
5784 /* Determine if the requested alignment is a power of 2. */
5785 if ((align & (align - 1)))
5786 align = 0;
5788 /* The maximum alignment in bits corresponding to the same
5789 maximum in bytes enforced in check_user_alignment(). */
5790 unsigned maxalign = (UINT_MAX >> 1) + 1;
5792 /* Reject invalid alignments. */
5793 if (align < BITS_PER_UNIT || maxalign < align)
5795 error_at (ARG_LOCATION (1),
5796 "second argument to function %qE must be a constant "
5797 "integer power of 2 between %qi and %qu bits",
5798 fndecl, BITS_PER_UNIT, maxalign);
5799 return false;
5801 return true;
5804 case BUILT_IN_CONSTANT_P:
5805 return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
5807 case BUILT_IN_ISFINITE:
5808 case BUILT_IN_ISINF:
5809 case BUILT_IN_ISINF_SIGN:
5810 case BUILT_IN_ISNAN:
5811 case BUILT_IN_ISNORMAL:
5812 case BUILT_IN_SIGNBIT:
5813 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
5815 if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
5817 error_at (ARG_LOCATION (0), "non-floating-point argument in "
5818 "call to function %qE", fndecl);
5819 return false;
5821 return true;
5823 return false;
5825 case BUILT_IN_ISGREATER:
5826 case BUILT_IN_ISGREATEREQUAL:
5827 case BUILT_IN_ISLESS:
5828 case BUILT_IN_ISLESSEQUAL:
5829 case BUILT_IN_ISLESSGREATER:
5830 case BUILT_IN_ISUNORDERED:
5831 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
5833 enum tree_code code0, code1;
5834 code0 = TREE_CODE (TREE_TYPE (args[0]));
5835 code1 = TREE_CODE (TREE_TYPE (args[1]));
5836 if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
5837 || (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
5838 || (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
5840 error_at (loc, "non-floating-point arguments in call to "
5841 "function %qE", fndecl);
5842 return false;
5844 return true;
5846 return false;
5848 case BUILT_IN_FPCLASSIFY:
5849 if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
5851 for (unsigned int i = 0; i < 5; i++)
5852 if (TREE_CODE (args[i]) != INTEGER_CST)
5854 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
5855 "call to function %qE", i + 1, fndecl);
5856 return false;
5859 if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
5861 error_at (ARG_LOCATION (5), "non-floating-point argument in "
5862 "call to function %qE", fndecl);
5863 return false;
5865 return true;
5867 return false;
5869 case BUILT_IN_ASSUME_ALIGNED:
5870 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
5872 if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
5874 error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
5875 "function %qE", fndecl);
5876 return false;
5878 return true;
5880 return false;
5882 case BUILT_IN_ADD_OVERFLOW:
5883 case BUILT_IN_SUB_OVERFLOW:
5884 case BUILT_IN_MUL_OVERFLOW:
5885 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
5887 unsigned i;
5888 for (i = 0; i < 2; i++)
5889 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
5891 error_at (ARG_LOCATION (i), "argument %u in call to function "
5892 "%qE does not have integral type", i + 1, fndecl);
5893 return false;
5895 if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
5896 || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
5898 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5899 "does not have pointer to integral type", fndecl);
5900 return false;
5902 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
5904 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5905 "has pointer to enumerated type", fndecl);
5906 return false;
5908 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
5910 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5911 "has pointer to boolean type", fndecl);
5912 return false;
5914 return true;
5916 return false;
5918 case BUILT_IN_ADD_OVERFLOW_P:
5919 case BUILT_IN_SUB_OVERFLOW_P:
5920 case BUILT_IN_MUL_OVERFLOW_P:
5921 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
5923 unsigned i;
5924 for (i = 0; i < 3; i++)
5925 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
5927 error_at (ARG_LOCATION (i), "argument %u in call to function "
5928 "%qE does not have integral type", i + 1, fndecl);
5929 return false;
5931 if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
5933 error_at (ARG_LOCATION (2), "argument 3 in call to function "
5934 "%qE has enumerated type", fndecl);
5935 return false;
5937 else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
5939 error_at (ARG_LOCATION (2), "argument 3 in call to function "
5940 "%qE has boolean type", fndecl);
5941 return false;
5943 return true;
5945 return false;
5947 default:
5948 return true;
5952 /* Subroutine of c_parse_error.
5953 Return the result of concatenating LHS and RHS. RHS is really
5954 a string literal, its first character is indicated by RHS_START and
5955 RHS_SIZE is its length (including the terminating NUL character).
5957 The caller is responsible for deleting the returned pointer. */
5959 static char *
5960 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
5962 const size_t lhs_size = strlen (lhs);
5963 char *result = XNEWVEC (char, lhs_size + rhs_size);
5964 memcpy (result, lhs, lhs_size);
5965 memcpy (result + lhs_size, rhs_start, rhs_size);
5966 return result;
5969 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
5970 before TOKEN, which had the associated VALUE. */
5972 void
5973 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
5974 tree value, unsigned char token_flags,
5975 rich_location *richloc)
5977 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
5979 char *message = NULL;
5981 if (token_type == CPP_EOF)
5982 message = catenate_messages (gmsgid, " at end of input");
5983 else if (token_type == CPP_CHAR
5984 || token_type == CPP_WCHAR
5985 || token_type == CPP_CHAR16
5986 || token_type == CPP_CHAR32
5987 || token_type == CPP_UTF8CHAR)
5989 unsigned int val = TREE_INT_CST_LOW (value);
5990 const char *prefix;
5992 switch (token_type)
5994 default:
5995 prefix = "";
5996 break;
5997 case CPP_WCHAR:
5998 prefix = "L";
5999 break;
6000 case CPP_CHAR16:
6001 prefix = "u";
6002 break;
6003 case CPP_CHAR32:
6004 prefix = "U";
6005 break;
6006 case CPP_UTF8CHAR:
6007 prefix = "u8";
6008 break;
6011 if (val <= UCHAR_MAX && ISGRAPH (val))
6012 message = catenate_messages (gmsgid, " before %s'%c'");
6013 else
6014 message = catenate_messages (gmsgid, " before %s'\\x%x'");
6016 error_at (richloc, message, prefix, val);
6017 free (message);
6018 message = NULL;
6020 else if (token_type == CPP_CHAR_USERDEF
6021 || token_type == CPP_WCHAR_USERDEF
6022 || token_type == CPP_CHAR16_USERDEF
6023 || token_type == CPP_CHAR32_USERDEF
6024 || token_type == CPP_UTF8CHAR_USERDEF)
6025 message = catenate_messages (gmsgid,
6026 " before user-defined character literal");
6027 else if (token_type == CPP_STRING_USERDEF
6028 || token_type == CPP_WSTRING_USERDEF
6029 || token_type == CPP_STRING16_USERDEF
6030 || token_type == CPP_STRING32_USERDEF
6031 || token_type == CPP_UTF8STRING_USERDEF)
6032 message = catenate_messages (gmsgid, " before user-defined string literal");
6033 else if (token_type == CPP_STRING
6034 || token_type == CPP_WSTRING
6035 || token_type == CPP_STRING16
6036 || token_type == CPP_STRING32
6037 || token_type == CPP_UTF8STRING)
6038 message = catenate_messages (gmsgid, " before string constant");
6039 else if (token_type == CPP_NUMBER)
6040 message = catenate_messages (gmsgid, " before numeric constant");
6041 else if (token_type == CPP_NAME)
6043 message = catenate_messages (gmsgid, " before %qE");
6044 error_at (richloc, message, value);
6045 free (message);
6046 message = NULL;
6048 else if (token_type == CPP_PRAGMA)
6049 message = catenate_messages (gmsgid, " before %<#pragma%>");
6050 else if (token_type == CPP_PRAGMA_EOL)
6051 message = catenate_messages (gmsgid, " before end of line");
6052 else if (token_type == CPP_DECLTYPE)
6053 message = catenate_messages (gmsgid, " before %<decltype%>");
6054 else if (token_type < N_TTYPES)
6056 message = catenate_messages (gmsgid, " before %qs token");
6057 error_at (richloc, message, cpp_type2name (token_type, token_flags));
6058 free (message);
6059 message = NULL;
6061 else
6062 error_at (richloc, gmsgid);
6064 if (message)
6066 error_at (richloc, message);
6067 free (message);
6069 #undef catenate_messages
6072 /* Return the gcc option code associated with the reason for a cpp
6073 message, or 0 if none. */
6075 static int
6076 c_option_controlling_cpp_error (int reason)
6078 const struct cpp_reason_option_codes_t *entry;
6080 for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6082 if (entry->reason == reason)
6083 return entry->option_code;
6085 return 0;
6088 /* Callback from cpp_error for PFILE to print diagnostics from the
6089 preprocessor. The diagnostic is of type LEVEL, with REASON set
6090 to the reason code if LEVEL is represents a warning, at location
6091 RICHLOC unless this is after lexing and the compiler's location
6092 should be used instead; MSG is the translated message and AP
6093 the arguments. Returns true if a diagnostic was emitted, false
6094 otherwise. */
6096 bool
6097 c_cpp_error (cpp_reader *pfile ATTRIBUTE_UNUSED, int level, int reason,
6098 rich_location *richloc,
6099 const char *msg, va_list *ap)
6101 diagnostic_info diagnostic;
6102 diagnostic_t dlevel;
6103 bool save_warn_system_headers = global_dc->dc_warn_system_headers;
6104 bool ret;
6106 switch (level)
6108 case CPP_DL_WARNING_SYSHDR:
6109 if (flag_no_output)
6110 return false;
6111 global_dc->dc_warn_system_headers = 1;
6112 /* Fall through. */
6113 case CPP_DL_WARNING:
6114 if (flag_no_output)
6115 return false;
6116 dlevel = DK_WARNING;
6117 break;
6118 case CPP_DL_PEDWARN:
6119 if (flag_no_output && !flag_pedantic_errors)
6120 return false;
6121 dlevel = DK_PEDWARN;
6122 break;
6123 case CPP_DL_ERROR:
6124 dlevel = DK_ERROR;
6125 break;
6126 case CPP_DL_ICE:
6127 dlevel = DK_ICE;
6128 break;
6129 case CPP_DL_NOTE:
6130 dlevel = DK_NOTE;
6131 break;
6132 case CPP_DL_FATAL:
6133 dlevel = DK_FATAL;
6134 break;
6135 default:
6136 gcc_unreachable ();
6138 if (done_lexing)
6139 richloc->set_range (line_table, 0, input_location, true);
6140 diagnostic_set_info_translated (&diagnostic, msg, ap,
6141 richloc, dlevel);
6142 diagnostic_override_option_index (&diagnostic,
6143 c_option_controlling_cpp_error (reason));
6144 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6145 if (level == CPP_DL_WARNING_SYSHDR)
6146 global_dc->dc_warn_system_headers = save_warn_system_headers;
6147 return ret;
6150 /* Convert a character from the host to the target execution character
6151 set. cpplib handles this, mostly. */
6153 HOST_WIDE_INT
6154 c_common_to_target_charset (HOST_WIDE_INT c)
6156 /* Character constants in GCC proper are sign-extended under -fsigned-char,
6157 zero-extended under -fno-signed-char. cpplib insists that characters
6158 and character constants are always unsigned. Hence we must convert
6159 back and forth. */
6160 cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6162 uc = cpp_host_to_exec_charset (parse_in, uc);
6164 if (flag_signed_char)
6165 return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6166 >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6167 else
6168 return uc;
6171 /* Fold an offsetof-like expression. EXPR is a nested sequence of component
6172 references with an INDIRECT_REF of a constant at the bottom; much like the
6173 traditional rendering of offsetof as a macro. Return the folded result. */
6175 tree
6176 fold_offsetof_1 (tree expr, enum tree_code ctx)
6178 tree base, off, t;
6179 tree_code code = TREE_CODE (expr);
6180 switch (code)
6182 case ERROR_MARK:
6183 return expr;
6185 case VAR_DECL:
6186 error ("cannot apply %<offsetof%> to static data member %qD", expr);
6187 return error_mark_node;
6189 case CALL_EXPR:
6190 case TARGET_EXPR:
6191 error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6192 return error_mark_node;
6194 case NOP_EXPR:
6195 case INDIRECT_REF:
6196 if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6198 error ("cannot apply %<offsetof%> to a non constant address");
6199 return error_mark_node;
6201 return TREE_OPERAND (expr, 0);
6203 case COMPONENT_REF:
6204 base = fold_offsetof_1 (TREE_OPERAND (expr, 0), code);
6205 if (base == error_mark_node)
6206 return base;
6208 t = TREE_OPERAND (expr, 1);
6209 if (DECL_C_BIT_FIELD (t))
6211 error ("attempt to take address of bit-field structure "
6212 "member %qD", t);
6213 return error_mark_node;
6215 off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6216 size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6217 / BITS_PER_UNIT));
6218 break;
6220 case ARRAY_REF:
6221 base = fold_offsetof_1 (TREE_OPERAND (expr, 0), code);
6222 if (base == error_mark_node)
6223 return base;
6225 t = TREE_OPERAND (expr, 1);
6227 /* Check if the offset goes beyond the upper bound of the array. */
6228 if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6230 tree upbound = array_ref_up_bound (expr);
6231 if (upbound != NULL_TREE
6232 && TREE_CODE (upbound) == INTEGER_CST
6233 && !tree_int_cst_equal (upbound,
6234 TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6236 if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6237 upbound = size_binop (PLUS_EXPR, upbound,
6238 build_int_cst (TREE_TYPE (upbound), 1));
6239 if (tree_int_cst_lt (upbound, t))
6241 tree v;
6243 for (v = TREE_OPERAND (expr, 0);
6244 TREE_CODE (v) == COMPONENT_REF;
6245 v = TREE_OPERAND (v, 0))
6246 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6247 == RECORD_TYPE)
6249 tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6250 for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6251 if (TREE_CODE (fld_chain) == FIELD_DECL)
6252 break;
6254 if (fld_chain)
6255 break;
6257 /* Don't warn if the array might be considered a poor
6258 man's flexible array member with a very permissive
6259 definition thereof. */
6260 if (TREE_CODE (v) == ARRAY_REF
6261 || TREE_CODE (v) == COMPONENT_REF)
6262 warning (OPT_Warray_bounds,
6263 "index %E denotes an offset "
6264 "greater than size of %qT",
6265 t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6270 t = convert (sizetype, t);
6271 off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6272 break;
6274 case COMPOUND_EXPR:
6275 /* Handle static members of volatile structs. */
6276 t = TREE_OPERAND (expr, 1);
6277 gcc_assert (VAR_P (t));
6278 return fold_offsetof_1 (t);
6280 default:
6281 gcc_unreachable ();
6284 return fold_build_pointer_plus (base, off);
6287 /* Likewise, but convert it to the return type of offsetof. */
6289 tree
6290 fold_offsetof (tree expr)
6292 return convert (size_type_node, fold_offsetof_1 (expr));
6296 /* *PTYPE is an incomplete array. Complete it with a domain based on
6297 INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6298 is true. Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6299 2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty. */
6302 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6304 tree maxindex, type, main_type, elt, unqual_elt;
6305 int failure = 0, quals;
6306 bool overflow_p = false;
6308 maxindex = size_zero_node;
6309 if (initial_value)
6311 if (TREE_CODE (initial_value) == STRING_CST)
6313 int eltsize
6314 = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6315 maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6317 else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6319 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6321 if (vec_safe_is_empty (v))
6323 if (pedantic)
6324 failure = 3;
6325 maxindex = ssize_int (-1);
6327 else
6329 tree curindex;
6330 unsigned HOST_WIDE_INT cnt;
6331 constructor_elt *ce;
6332 bool fold_p = false;
6334 if ((*v)[0].index)
6335 maxindex = (*v)[0].index, fold_p = true;
6337 curindex = maxindex;
6339 for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
6341 bool curfold_p = false;
6342 if (ce->index)
6343 curindex = ce->index, curfold_p = true;
6344 else
6346 if (fold_p)
6348 /* Since we treat size types now as ordinary
6349 unsigned types, we need an explicit overflow
6350 check. */
6351 tree orig = curindex;
6352 curindex = fold_convert (sizetype, curindex);
6353 overflow_p |= tree_int_cst_lt (curindex, orig);
6355 curindex = size_binop (PLUS_EXPR, curindex,
6356 size_one_node);
6358 if (tree_int_cst_lt (maxindex, curindex))
6359 maxindex = curindex, fold_p = curfold_p;
6361 if (fold_p)
6363 tree orig = maxindex;
6364 maxindex = fold_convert (sizetype, maxindex);
6365 overflow_p |= tree_int_cst_lt (maxindex, orig);
6369 else
6371 /* Make an error message unless that happened already. */
6372 if (initial_value != error_mark_node)
6373 failure = 1;
6376 else
6378 failure = 2;
6379 if (!do_default)
6380 return failure;
6383 type = *ptype;
6384 elt = TREE_TYPE (type);
6385 quals = TYPE_QUALS (strip_array_types (elt));
6386 if (quals == 0)
6387 unqual_elt = elt;
6388 else
6389 unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
6391 /* Using build_distinct_type_copy and modifying things afterward instead
6392 of using build_array_type to create a new type preserves all of the
6393 TYPE_LANG_FLAG_? bits that the front end may have set. */
6394 main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
6395 TREE_TYPE (main_type) = unqual_elt;
6396 TYPE_DOMAIN (main_type)
6397 = build_range_type (TREE_TYPE (maxindex),
6398 build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
6399 TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
6400 layout_type (main_type);
6402 /* Make sure we have the canonical MAIN_TYPE. */
6403 hashval_t hashcode = type_hash_canon_hash (main_type);
6404 main_type = type_hash_canon (hashcode, main_type);
6406 /* Fix the canonical type. */
6407 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
6408 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
6409 SET_TYPE_STRUCTURAL_EQUALITY (main_type);
6410 else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
6411 || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
6412 != TYPE_DOMAIN (main_type)))
6413 TYPE_CANONICAL (main_type)
6414 = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
6415 TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
6416 TYPE_TYPELESS_STORAGE (main_type));
6417 else
6418 TYPE_CANONICAL (main_type) = main_type;
6420 if (quals == 0)
6421 type = main_type;
6422 else
6423 type = c_build_qualified_type (main_type, quals);
6425 if (COMPLETE_TYPE_P (type)
6426 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
6427 && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
6429 error ("size of array is too large");
6430 /* If we proceed with the array type as it is, we'll eventually
6431 crash in tree_to_[su]hwi(). */
6432 type = error_mark_node;
6435 *ptype = type;
6436 return failure;
6439 /* Like c_mark_addressable but don't check register qualifier. */
6440 void
6441 c_common_mark_addressable_vec (tree t)
6443 if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
6444 t = C_MAYBE_CONST_EXPR_EXPR (t);
6445 while (handled_component_p (t))
6446 t = TREE_OPERAND (t, 0);
6447 if (!VAR_P (t)
6448 && TREE_CODE (t) != PARM_DECL
6449 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR)
6450 return;
6451 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
6452 TREE_ADDRESSABLE (t) = 1;
6457 /* Used to help initialize the builtin-types.def table. When a type of
6458 the correct size doesn't exist, use error_mark_node instead of NULL.
6459 The later results in segfaults even when a decl using the type doesn't
6460 get invoked. */
6462 tree
6463 builtin_type_for_size (int size, bool unsignedp)
6465 tree type = c_common_type_for_size (size, unsignedp);
6466 return type ? type : error_mark_node;
6469 /* A helper function for resolve_overloaded_builtin in resolving the
6470 overloaded __sync_ builtins. Returns a positive power of 2 if the
6471 first operand of PARAMS is a pointer to a supported data type.
6472 Returns 0 if an error is encountered.
6473 FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
6474 built-ins. */
6476 static int
6477 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch)
6479 /* Type of the argument. */
6480 tree argtype;
6481 /* Type the argument points to. */
6482 tree type;
6483 int size;
6485 if (vec_safe_is_empty (params))
6487 error ("too few arguments to function %qE", function);
6488 return 0;
6491 argtype = type = TREE_TYPE ((*params)[0]);
6492 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6494 /* Force array-to-pointer decay for C++. */
6495 (*params)[0] = default_conversion ((*params)[0]);
6496 type = TREE_TYPE ((*params)[0]);
6498 if (TREE_CODE (type) != POINTER_TYPE)
6499 goto incompatible;
6501 type = TREE_TYPE (type);
6502 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
6503 goto incompatible;
6505 if (!COMPLETE_TYPE_P (type))
6506 goto incompatible;
6508 if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
6509 goto incompatible;
6511 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
6512 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
6513 return size;
6515 incompatible:
6516 /* Issue the diagnostic only if the argument is valid, otherwise
6517 it would be redundant at best and could be misleading. */
6518 if (argtype != error_mark_node)
6519 error ("operand type %qT is incompatible with argument %d of %qE",
6520 argtype, 1, function);
6521 return 0;
6524 /* A helper function for resolve_overloaded_builtin. Adds casts to
6525 PARAMS to make arguments match up with those of FUNCTION. Drops
6526 the variadic arguments at the end. Returns false if some error
6527 was encountered; true on success. */
6529 static bool
6530 sync_resolve_params (location_t loc, tree orig_function, tree function,
6531 vec<tree, va_gc> *params, bool orig_format)
6533 function_args_iterator iter;
6534 tree ptype;
6535 unsigned int parmnum;
6537 function_args_iter_init (&iter, TREE_TYPE (function));
6538 /* We've declared the implementation functions to use "volatile void *"
6539 as the pointer parameter, so we shouldn't get any complaints from the
6540 call to check_function_arguments what ever type the user used. */
6541 function_args_iter_next (&iter);
6542 ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
6543 ptype = TYPE_MAIN_VARIANT (ptype);
6545 /* For the rest of the values, we need to cast these to FTYPE, so that we
6546 don't get warnings for passing pointer types, etc. */
6547 parmnum = 0;
6548 while (1)
6550 tree val, arg_type;
6552 arg_type = function_args_iter_cond (&iter);
6553 /* XXX void_type_node belies the abstraction. */
6554 if (arg_type == void_type_node)
6555 break;
6557 ++parmnum;
6558 if (params->length () <= parmnum)
6560 error_at (loc, "too few arguments to function %qE", orig_function);
6561 return false;
6564 /* Only convert parameters if arg_type is unsigned integer type with
6565 new format sync routines, i.e. don't attempt to convert pointer
6566 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
6567 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
6568 kinds). */
6569 if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
6571 /* Ideally for the first conversion we'd use convert_for_assignment
6572 so that we get warnings for anything that doesn't match the pointer
6573 type. This isn't portable across the C and C++ front ends atm. */
6574 val = (*params)[parmnum];
6575 val = convert (ptype, val);
6576 val = convert (arg_type, val);
6577 (*params)[parmnum] = val;
6580 function_args_iter_next (&iter);
6583 /* __atomic routines are not variadic. */
6584 if (!orig_format && params->length () != parmnum + 1)
6586 error_at (loc, "too many arguments to function %qE", orig_function);
6587 return false;
6590 /* The definition of these primitives is variadic, with the remaining
6591 being "an optional list of variables protected by the memory barrier".
6592 No clue what that's supposed to mean, precisely, but we consider all
6593 call-clobbered variables to be protected so we're safe. */
6594 params->truncate (parmnum + 1);
6596 return true;
6599 /* A helper function for resolve_overloaded_builtin. Adds a cast to
6600 RESULT to make it match the type of the first pointer argument in
6601 PARAMS. */
6603 static tree
6604 sync_resolve_return (tree first_param, tree result, bool orig_format)
6606 tree ptype = TREE_TYPE (TREE_TYPE (first_param));
6607 tree rtype = TREE_TYPE (result);
6608 ptype = TYPE_MAIN_VARIANT (ptype);
6610 /* New format doesn't require casting unless the types are the same size. */
6611 if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
6612 return convert (ptype, result);
6613 else
6614 return result;
6617 /* This function verifies the PARAMS to generic atomic FUNCTION.
6618 It returns the size if all the parameters are the same size, otherwise
6619 0 is returned if the parameters are invalid. */
6621 static int
6622 get_atomic_generic_size (location_t loc, tree function,
6623 vec<tree, va_gc> *params)
6625 unsigned int n_param;
6626 unsigned int n_model;
6627 unsigned int x;
6628 int size_0;
6629 tree type_0;
6631 /* Determine the parameter makeup. */
6632 switch (DECL_FUNCTION_CODE (function))
6634 case BUILT_IN_ATOMIC_EXCHANGE:
6635 n_param = 4;
6636 n_model = 1;
6637 break;
6638 case BUILT_IN_ATOMIC_LOAD:
6639 case BUILT_IN_ATOMIC_STORE:
6640 n_param = 3;
6641 n_model = 1;
6642 break;
6643 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
6644 n_param = 6;
6645 n_model = 2;
6646 break;
6647 default:
6648 gcc_unreachable ();
6651 if (vec_safe_length (params) != n_param)
6653 error_at (loc, "incorrect number of arguments to function %qE", function);
6654 return 0;
6657 /* Get type of first parameter, and determine its size. */
6658 type_0 = TREE_TYPE ((*params)[0]);
6659 if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
6661 /* Force array-to-pointer decay for C++. */
6662 (*params)[0] = default_conversion ((*params)[0]);
6663 type_0 = TREE_TYPE ((*params)[0]);
6665 if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
6667 error_at (loc, "argument 1 of %qE must be a non-void pointer type",
6668 function);
6669 return 0;
6672 /* Types must be compile time constant sizes. */
6673 if (TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))) != INTEGER_CST)
6675 error_at (loc,
6676 "argument 1 of %qE must be a pointer to a constant size type",
6677 function);
6678 return 0;
6681 size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
6683 /* Zero size objects are not allowed. */
6684 if (size_0 == 0)
6686 error_at (loc,
6687 "argument 1 of %qE must be a pointer to a nonzero size object",
6688 function);
6689 return 0;
6692 /* Check each other parameter is a pointer and the same size. */
6693 for (x = 0; x < n_param - n_model; x++)
6695 int size;
6696 tree type = TREE_TYPE ((*params)[x]);
6697 /* __atomic_compare_exchange has a bool in the 4th position, skip it. */
6698 if (n_param == 6 && x == 3)
6699 continue;
6700 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6702 /* Force array-to-pointer decay for C++. */
6703 (*params)[x] = default_conversion ((*params)[x]);
6704 type = TREE_TYPE ((*params)[x]);
6706 if (!POINTER_TYPE_P (type))
6708 error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
6709 function);
6710 return 0;
6712 else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
6713 && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
6714 != INTEGER_CST)
6716 error_at (loc, "argument %d of %qE must be a pointer to a constant "
6717 "size type", x + 1, function);
6718 return 0;
6720 else if (FUNCTION_POINTER_TYPE_P (type))
6722 error_at (loc, "argument %d of %qE must not be a pointer to a "
6723 "function", x + 1, function);
6724 return 0;
6726 tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
6727 size = type_size ? tree_to_uhwi (type_size) : 0;
6728 if (size != size_0)
6730 error_at (loc, "size mismatch in argument %d of %qE", x + 1,
6731 function);
6732 return 0;
6736 /* Check memory model parameters for validity. */
6737 for (x = n_param - n_model ; x < n_param; x++)
6739 tree p = (*params)[x];
6740 if (TREE_CODE (p) == INTEGER_CST)
6742 /* memmodel_base masks the low 16 bits, thus ignore any bits above
6743 it by using TREE_INT_CST_LOW instead of tree_to_*hwi. Those high
6744 bits will be checked later during expansion in target specific
6745 way. */
6746 if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
6747 warning_at (loc, OPT_Winvalid_memory_model,
6748 "invalid memory model argument %d of %qE", x + 1,
6749 function);
6751 else
6752 if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
6754 error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
6755 function);
6756 return 0;
6760 return size_0;
6764 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
6765 at the beginning of the parameter list PARAMS representing the size of the
6766 objects. This is to match the library ABI requirement. LOC is the location
6767 of the function call.
6768 The new function is returned if it needed rebuilding, otherwise NULL_TREE is
6769 returned to allow the external call to be constructed. */
6771 static tree
6772 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
6773 vec<tree, va_gc> *params)
6775 tree size_node;
6777 /* Insert a SIZE_T parameter as the first param. If there isn't
6778 enough space, allocate a new vector and recursively re-build with that. */
6779 if (!params->space (1))
6781 unsigned int z, len;
6782 vec<tree, va_gc> *v;
6783 tree f;
6785 len = params->length ();
6786 vec_alloc (v, len + 1);
6787 v->quick_push (build_int_cst (size_type_node, n));
6788 for (z = 0; z < len; z++)
6789 v->quick_push ((*params)[z]);
6790 f = build_function_call_vec (loc, vNULL, function, v, NULL);
6791 vec_free (v);
6792 return f;
6795 /* Add the size parameter and leave as a function call for processing. */
6796 size_node = build_int_cst (size_type_node, n);
6797 params->quick_insert (0, size_node);
6798 return NULL_TREE;
6802 /* Return whether atomic operations for naturally aligned N-byte
6803 arguments are supported, whether inline or through libatomic. */
6804 static bool
6805 atomic_size_supported_p (int n)
6807 switch (n)
6809 case 1:
6810 case 2:
6811 case 4:
6812 case 8:
6813 return true;
6815 case 16:
6816 return targetm.scalar_mode_supported_p (TImode);
6818 default:
6819 return false;
6823 /* This will process an __atomic_exchange function call, determine whether it
6824 needs to be mapped to the _N variation, or turned into a library call.
6825 LOC is the location of the builtin call.
6826 FUNCTION is the DECL that has been invoked;
6827 PARAMS is the argument list for the call. The return value is non-null
6828 TRUE is returned if it is translated into the proper format for a call to the
6829 external library, and NEW_RETURN is set the tree for that function.
6830 FALSE is returned if processing for the _N variation is required, and
6831 NEW_RETURN is set to the return value the result is copied into. */
6832 static bool
6833 resolve_overloaded_atomic_exchange (location_t loc, tree function,
6834 vec<tree, va_gc> *params, tree *new_return)
6836 tree p0, p1, p2, p3;
6837 tree I_type, I_type_ptr;
6838 int n = get_atomic_generic_size (loc, function, params);
6840 /* Size of 0 is an error condition. */
6841 if (n == 0)
6843 *new_return = error_mark_node;
6844 return true;
6847 /* If not a lock-free size, change to the library generic format. */
6848 if (!atomic_size_supported_p (n))
6850 *new_return = add_atomic_size_parameter (n, loc, function, params);
6851 return true;
6854 /* Otherwise there is a lockfree match, transform the call from:
6855 void fn(T* mem, T* desired, T* return, model)
6856 into
6857 *return = (T) (fn (In* mem, (In) *desired, model)) */
6859 p0 = (*params)[0];
6860 p1 = (*params)[1];
6861 p2 = (*params)[2];
6862 p3 = (*params)[3];
6864 /* Create pointer to appropriate size. */
6865 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6866 I_type_ptr = build_pointer_type (I_type);
6868 /* Convert object pointer to required type. */
6869 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6870 (*params)[0] = p0;
6871 /* Convert new value to required type, and dereference it. */
6872 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
6873 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
6874 (*params)[1] = p1;
6876 /* Move memory model to the 3rd position, and end param list. */
6877 (*params)[2] = p3;
6878 params->truncate (3);
6880 /* Convert return pointer and dereference it for later assignment. */
6881 *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
6883 return false;
6887 /* This will process an __atomic_compare_exchange function call, determine
6888 whether it needs to be mapped to the _N variation, or turned into a lib call.
6889 LOC is the location of the builtin call.
6890 FUNCTION is the DECL that has been invoked;
6891 PARAMS is the argument list for the call. The return value is non-null
6892 TRUE is returned if it is translated into the proper format for a call to the
6893 external library, and NEW_RETURN is set the tree for that function.
6894 FALSE is returned if processing for the _N variation is required. */
6896 static bool
6897 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
6898 vec<tree, va_gc> *params,
6899 tree *new_return)
6901 tree p0, p1, p2;
6902 tree I_type, I_type_ptr;
6903 int n = get_atomic_generic_size (loc, function, params);
6905 /* Size of 0 is an error condition. */
6906 if (n == 0)
6908 *new_return = error_mark_node;
6909 return true;
6912 /* If not a lock-free size, change to the library generic format. */
6913 if (!atomic_size_supported_p (n))
6915 /* The library generic format does not have the weak parameter, so
6916 remove it from the param list. Since a parameter has been removed,
6917 we can be sure that there is room for the SIZE_T parameter, meaning
6918 there will not be a recursive rebuilding of the parameter list, so
6919 there is no danger this will be done twice. */
6920 if (n > 0)
6922 (*params)[3] = (*params)[4];
6923 (*params)[4] = (*params)[5];
6924 params->truncate (5);
6926 *new_return = add_atomic_size_parameter (n, loc, function, params);
6927 return true;
6930 /* Otherwise, there is a match, so the call needs to be transformed from:
6931 bool fn(T* mem, T* desired, T* return, weak, success, failure)
6932 into
6933 bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail) */
6935 p0 = (*params)[0];
6936 p1 = (*params)[1];
6937 p2 = (*params)[2];
6939 /* Create pointer to appropriate size. */
6940 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6941 I_type_ptr = build_pointer_type (I_type);
6943 /* Convert object pointer to required type. */
6944 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6945 (*params)[0] = p0;
6947 /* Convert expected pointer to required type. */
6948 p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
6949 (*params)[1] = p1;
6951 /* Convert desired value to required type, and dereference it. */
6952 p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
6953 p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
6954 (*params)[2] = p2;
6956 /* The rest of the parameters are fine. NULL means no special return value
6957 processing.*/
6958 *new_return = NULL;
6959 return false;
6963 /* This will process an __atomic_load function call, determine whether it
6964 needs to be mapped to the _N variation, or turned into a library call.
6965 LOC is the location of the builtin call.
6966 FUNCTION is the DECL that has been invoked;
6967 PARAMS is the argument list for the call. The return value is non-null
6968 TRUE is returned if it is translated into the proper format for a call to the
6969 external library, and NEW_RETURN is set the tree for that function.
6970 FALSE is returned if processing for the _N variation is required, and
6971 NEW_RETURN is set to the return value the result is copied into. */
6973 static bool
6974 resolve_overloaded_atomic_load (location_t loc, tree function,
6975 vec<tree, va_gc> *params, tree *new_return)
6977 tree p0, p1, p2;
6978 tree I_type, I_type_ptr;
6979 int n = get_atomic_generic_size (loc, function, params);
6981 /* Size of 0 is an error condition. */
6982 if (n == 0)
6984 *new_return = error_mark_node;
6985 return true;
6988 /* If not a lock-free size, change to the library generic format. */
6989 if (!atomic_size_supported_p (n))
6991 *new_return = add_atomic_size_parameter (n, loc, function, params);
6992 return true;
6995 /* Otherwise, there is a match, so the call needs to be transformed from:
6996 void fn(T* mem, T* return, model)
6997 into
6998 *return = (T) (fn ((In *) mem, model)) */
7000 p0 = (*params)[0];
7001 p1 = (*params)[1];
7002 p2 = (*params)[2];
7004 /* Create pointer to appropriate size. */
7005 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7006 I_type_ptr = build_pointer_type (I_type);
7008 /* Convert object pointer to required type. */
7009 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7010 (*params)[0] = p0;
7012 /* Move memory model to the 2nd position, and end param list. */
7013 (*params)[1] = p2;
7014 params->truncate (2);
7016 /* Convert return pointer and dereference it for later assignment. */
7017 *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7019 return false;
7023 /* This will process an __atomic_store function call, determine whether it
7024 needs to be mapped to the _N variation, or turned into a library call.
7025 LOC is the location of the builtin call.
7026 FUNCTION is the DECL that has been invoked;
7027 PARAMS is the argument list for the call. The return value is non-null
7028 TRUE is returned if it is translated into the proper format for a call to the
7029 external library, and NEW_RETURN is set the tree for that function.
7030 FALSE is returned if processing for the _N variation is required, and
7031 NEW_RETURN is set to the return value the result is copied into. */
7033 static bool
7034 resolve_overloaded_atomic_store (location_t loc, tree function,
7035 vec<tree, va_gc> *params, tree *new_return)
7037 tree p0, p1;
7038 tree I_type, I_type_ptr;
7039 int n = get_atomic_generic_size (loc, function, params);
7041 /* Size of 0 is an error condition. */
7042 if (n == 0)
7044 *new_return = error_mark_node;
7045 return true;
7048 /* If not a lock-free size, change to the library generic format. */
7049 if (!atomic_size_supported_p (n))
7051 *new_return = add_atomic_size_parameter (n, loc, function, params);
7052 return true;
7055 /* Otherwise, there is a match, so the call needs to be transformed from:
7056 void fn(T* mem, T* value, model)
7057 into
7058 fn ((In *) mem, (In) *value, model) */
7060 p0 = (*params)[0];
7061 p1 = (*params)[1];
7063 /* Create pointer to appropriate size. */
7064 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7065 I_type_ptr = build_pointer_type (I_type);
7067 /* Convert object pointer to required type. */
7068 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7069 (*params)[0] = p0;
7071 /* Convert new value to required type, and dereference it. */
7072 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7073 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7074 (*params)[1] = p1;
7076 /* The memory model is in the right spot already. Return is void. */
7077 *new_return = NULL_TREE;
7079 return false;
7083 /* Some builtin functions are placeholders for other expressions. This
7084 function should be called immediately after parsing the call expression
7085 before surrounding code has committed to the type of the expression.
7087 LOC is the location of the builtin call.
7089 FUNCTION is the DECL that has been invoked; it is known to be a builtin.
7090 PARAMS is the argument list for the call. The return value is non-null
7091 when expansion is complete, and null if normal processing should
7092 continue. */
7094 tree
7095 resolve_overloaded_builtin (location_t loc, tree function,
7096 vec<tree, va_gc> *params)
7098 enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
7100 /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
7101 Those are not valid to call with a pointer to _Bool (or C++ bool)
7102 and so must be rejected. */
7103 bool fetch_op = true;
7104 bool orig_format = true;
7105 tree new_return = NULL_TREE;
7107 switch (DECL_BUILT_IN_CLASS (function))
7109 case BUILT_IN_NORMAL:
7110 break;
7111 case BUILT_IN_MD:
7112 if (targetm.resolve_overloaded_builtin)
7113 return targetm.resolve_overloaded_builtin (loc, function, params);
7114 else
7115 return NULL_TREE;
7116 default:
7117 return NULL_TREE;
7120 /* Handle BUILT_IN_NORMAL here. */
7121 switch (orig_code)
7123 case BUILT_IN_ATOMIC_EXCHANGE:
7124 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7125 case BUILT_IN_ATOMIC_LOAD:
7126 case BUILT_IN_ATOMIC_STORE:
7128 /* Handle these 4 together so that they can fall through to the next
7129 case if the call is transformed to an _N variant. */
7130 switch (orig_code)
7132 case BUILT_IN_ATOMIC_EXCHANGE:
7134 if (resolve_overloaded_atomic_exchange (loc, function, params,
7135 &new_return))
7136 return new_return;
7137 /* Change to the _N variant. */
7138 orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
7139 break;
7142 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7144 if (resolve_overloaded_atomic_compare_exchange (loc, function,
7145 params,
7146 &new_return))
7147 return new_return;
7148 /* Change to the _N variant. */
7149 orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
7150 break;
7152 case BUILT_IN_ATOMIC_LOAD:
7154 if (resolve_overloaded_atomic_load (loc, function, params,
7155 &new_return))
7156 return new_return;
7157 /* Change to the _N variant. */
7158 orig_code = BUILT_IN_ATOMIC_LOAD_N;
7159 break;
7161 case BUILT_IN_ATOMIC_STORE:
7163 if (resolve_overloaded_atomic_store (loc, function, params,
7164 &new_return))
7165 return new_return;
7166 /* Change to the _N variant. */
7167 orig_code = BUILT_IN_ATOMIC_STORE_N;
7168 break;
7170 default:
7171 gcc_unreachable ();
7174 /* FALLTHRU */
7175 case BUILT_IN_ATOMIC_EXCHANGE_N:
7176 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
7177 case BUILT_IN_ATOMIC_LOAD_N:
7178 case BUILT_IN_ATOMIC_STORE_N:
7179 fetch_op = false;
7180 /* FALLTHRU */
7181 case BUILT_IN_ATOMIC_ADD_FETCH_N:
7182 case BUILT_IN_ATOMIC_SUB_FETCH_N:
7183 case BUILT_IN_ATOMIC_AND_FETCH_N:
7184 case BUILT_IN_ATOMIC_NAND_FETCH_N:
7185 case BUILT_IN_ATOMIC_XOR_FETCH_N:
7186 case BUILT_IN_ATOMIC_OR_FETCH_N:
7187 case BUILT_IN_ATOMIC_FETCH_ADD_N:
7188 case BUILT_IN_ATOMIC_FETCH_SUB_N:
7189 case BUILT_IN_ATOMIC_FETCH_AND_N:
7190 case BUILT_IN_ATOMIC_FETCH_NAND_N:
7191 case BUILT_IN_ATOMIC_FETCH_XOR_N:
7192 case BUILT_IN_ATOMIC_FETCH_OR_N:
7193 orig_format = false;
7194 /* FALLTHRU */
7195 case BUILT_IN_SYNC_FETCH_AND_ADD_N:
7196 case BUILT_IN_SYNC_FETCH_AND_SUB_N:
7197 case BUILT_IN_SYNC_FETCH_AND_OR_N:
7198 case BUILT_IN_SYNC_FETCH_AND_AND_N:
7199 case BUILT_IN_SYNC_FETCH_AND_XOR_N:
7200 case BUILT_IN_SYNC_FETCH_AND_NAND_N:
7201 case BUILT_IN_SYNC_ADD_AND_FETCH_N:
7202 case BUILT_IN_SYNC_SUB_AND_FETCH_N:
7203 case BUILT_IN_SYNC_OR_AND_FETCH_N:
7204 case BUILT_IN_SYNC_AND_AND_FETCH_N:
7205 case BUILT_IN_SYNC_XOR_AND_FETCH_N:
7206 case BUILT_IN_SYNC_NAND_AND_FETCH_N:
7207 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
7208 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
7209 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
7210 case BUILT_IN_SYNC_LOCK_RELEASE_N:
7212 /* The following are not _FETCH_OPs and must be accepted with
7213 pointers to _Bool (or C++ bool). */
7214 if (fetch_op)
7215 fetch_op =
7216 (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7217 && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
7218 && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
7219 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
7221 int n = sync_resolve_size (function, params, fetch_op);
7222 tree new_function, first_param, result;
7223 enum built_in_function fncode;
7225 if (n == 0)
7226 return error_mark_node;
7228 fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
7229 new_function = builtin_decl_explicit (fncode);
7230 if (!sync_resolve_params (loc, function, new_function, params,
7231 orig_format))
7232 return error_mark_node;
7234 first_param = (*params)[0];
7235 result = build_function_call_vec (loc, vNULL, new_function, params,
7236 NULL);
7237 if (result == error_mark_node)
7238 return result;
7239 if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7240 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
7241 && orig_code != BUILT_IN_ATOMIC_STORE_N
7242 && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
7243 result = sync_resolve_return (first_param, result, orig_format);
7245 if (fetch_op)
7246 /* Prevent -Wunused-value warning. */
7247 TREE_USED (result) = true;
7249 /* If new_return is set, assign function to that expr and cast the
7250 result to void since the generic interface returned void. */
7251 if (new_return)
7253 /* Cast function result from I{1,2,4,8,16} to the required type. */
7254 result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
7255 result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
7256 result);
7257 TREE_SIDE_EFFECTS (result) = 1;
7258 protected_set_expr_location (result, loc);
7259 result = convert (void_type_node, result);
7261 return result;
7264 default:
7265 return NULL_TREE;
7269 /* vector_types_compatible_elements_p is used in type checks of vectors
7270 values used as operands of binary operators. Where it returns true, and
7271 the other checks of the caller succeed (being vector types in he first
7272 place, and matching number of elements), we can just treat the types
7273 as essentially the same.
7274 Contrast with vector_targets_convertible_p, which is used for vector
7275 pointer types, and vector_types_convertible_p, which will allow
7276 language-specific matches under the control of flag_lax_vector_conversions,
7277 and might still require a conversion. */
7278 /* True if vector types T1 and T2 can be inputs to the same binary
7279 operator without conversion.
7280 We don't check the overall vector size here because some of our callers
7281 want to give different error messages when the vectors are compatible
7282 except for the element count. */
7284 bool
7285 vector_types_compatible_elements_p (tree t1, tree t2)
7287 bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
7288 t1 = TREE_TYPE (t1);
7289 t2 = TREE_TYPE (t2);
7291 enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
7293 gcc_assert ((c1 == INTEGER_TYPE || c1 == REAL_TYPE || c1 == FIXED_POINT_TYPE)
7294 && (c2 == INTEGER_TYPE || c2 == REAL_TYPE
7295 || c2 == FIXED_POINT_TYPE));
7297 t1 = c_common_signed_type (t1);
7298 t2 = c_common_signed_type (t2);
7299 /* Equality works here because c_common_signed_type uses
7300 TYPE_MAIN_VARIANT. */
7301 if (t1 == t2)
7302 return true;
7303 if (opaque && c1 == c2
7304 && (c1 == INTEGER_TYPE || c1 == REAL_TYPE)
7305 && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
7306 return true;
7307 return false;
7310 /* Check for missing format attributes on function pointers. LTYPE is
7311 the new type or left-hand side type. RTYPE is the old type or
7312 right-hand side type. Returns TRUE if LTYPE is missing the desired
7313 attribute. */
7315 bool
7316 check_missing_format_attribute (tree ltype, tree rtype)
7318 tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
7319 tree ra;
7321 for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
7322 if (is_attribute_p ("format", TREE_PURPOSE (ra)))
7323 break;
7324 if (ra)
7326 tree la;
7327 for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
7328 if (is_attribute_p ("format", TREE_PURPOSE (la)))
7329 break;
7330 return !la;
7332 else
7333 return false;
7336 /* Setup a TYPE_DECL node as a typedef representation.
7338 X is a TYPE_DECL for a typedef statement. Create a brand new
7339 ..._TYPE node (which will be just a variant of the existing
7340 ..._TYPE node with identical properties) and then install X
7341 as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
7343 The whole point here is to end up with a situation where each
7344 and every ..._TYPE node the compiler creates will be uniquely
7345 associated with AT MOST one node representing a typedef name.
7346 This way, even though the compiler substitutes corresponding
7347 ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
7348 early on, later parts of the compiler can always do the reverse
7349 translation and get back the corresponding typedef name. For
7350 example, given:
7352 typedef struct S MY_TYPE;
7353 MY_TYPE object;
7355 Later parts of the compiler might only know that `object' was of
7356 type `struct S' if it were not for code just below. With this
7357 code however, later parts of the compiler see something like:
7359 struct S' == struct S
7360 typedef struct S' MY_TYPE;
7361 struct S' object;
7363 And they can then deduce (from the node for type struct S') that
7364 the original object declaration was:
7366 MY_TYPE object;
7368 Being able to do this is important for proper support of protoize,
7369 and also for generating precise symbolic debugging information
7370 which takes full account of the programmer's (typedef) vocabulary.
7372 Obviously, we don't want to generate a duplicate ..._TYPE node if
7373 the TYPE_DECL node that we are now processing really represents a
7374 standard built-in type. */
7376 void
7377 set_underlying_type (tree x)
7379 if (x == error_mark_node)
7380 return;
7381 if (DECL_IS_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
7383 if (TYPE_NAME (TREE_TYPE (x)) == 0)
7384 TYPE_NAME (TREE_TYPE (x)) = x;
7386 else if (TREE_TYPE (x) != error_mark_node
7387 && DECL_ORIGINAL_TYPE (x) == NULL_TREE)
7389 tree tt = TREE_TYPE (x);
7390 DECL_ORIGINAL_TYPE (x) = tt;
7391 tt = build_variant_type_copy (tt);
7392 TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
7393 TYPE_NAME (tt) = x;
7395 /* Mark the type as used only when its type decl is decorated
7396 with attribute unused. */
7397 if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
7398 TREE_USED (tt) = 1;
7400 TREE_TYPE (x) = tt;
7404 /* Record the types used by the current global variable declaration
7405 being parsed, so that we can decide later to emit their debug info.
7406 Those types are in types_used_by_cur_var_decl, and we are going to
7407 store them in the types_used_by_vars_hash hash table.
7408 DECL is the declaration of the global variable that has been parsed. */
7410 void
7411 record_types_used_by_current_var_decl (tree decl)
7413 gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
7415 while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
7417 tree type = types_used_by_cur_var_decl->pop ();
7418 types_used_by_var_decl_insert (type, decl);
7422 /* The C and C++ parsers both use vectors to hold function arguments.
7423 For efficiency, we keep a cache of unused vectors. This is the
7424 cache. */
7426 typedef vec<tree, va_gc> *tree_gc_vec;
7427 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
7429 /* Return a new vector from the cache. If the cache is empty,
7430 allocate a new vector. These vectors are GC'ed, so it is OK if the
7431 pointer is not released.. */
7433 vec<tree, va_gc> *
7434 make_tree_vector (void)
7436 if (tree_vector_cache && !tree_vector_cache->is_empty ())
7437 return tree_vector_cache->pop ();
7438 else
7440 /* Passing 0 to vec::alloc returns NULL, and our callers require
7441 that we always return a non-NULL value. The vector code uses
7442 4 when growing a NULL vector, so we do too. */
7443 vec<tree, va_gc> *v;
7444 vec_alloc (v, 4);
7445 return v;
7449 /* Release a vector of trees back to the cache. */
7451 void
7452 release_tree_vector (vec<tree, va_gc> *vec)
7454 if (vec != NULL)
7456 vec->truncate (0);
7457 vec_safe_push (tree_vector_cache, vec);
7461 /* Get a new tree vector holding a single tree. */
7463 vec<tree, va_gc> *
7464 make_tree_vector_single (tree t)
7466 vec<tree, va_gc> *ret = make_tree_vector ();
7467 ret->quick_push (t);
7468 return ret;
7471 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain. */
7473 vec<tree, va_gc> *
7474 make_tree_vector_from_list (tree list)
7476 vec<tree, va_gc> *ret = make_tree_vector ();
7477 for (; list; list = TREE_CHAIN (list))
7478 vec_safe_push (ret, TREE_VALUE (list));
7479 return ret;
7482 /* Get a new tree vector of the values of a CONSTRUCTOR. */
7484 vec<tree, va_gc> *
7485 make_tree_vector_from_ctor (tree ctor)
7487 vec<tree,va_gc> *ret = make_tree_vector ();
7488 vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
7489 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
7490 ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
7491 return ret;
7494 /* Get a new tree vector which is a copy of an existing one. */
7496 vec<tree, va_gc> *
7497 make_tree_vector_copy (const vec<tree, va_gc> *orig)
7499 vec<tree, va_gc> *ret;
7500 unsigned int ix;
7501 tree t;
7503 ret = make_tree_vector ();
7504 vec_safe_reserve (ret, vec_safe_length (orig));
7505 FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
7506 ret->quick_push (t);
7507 return ret;
7510 /* Return true if KEYWORD starts a type specifier. */
7512 bool
7513 keyword_begins_type_specifier (enum rid keyword)
7515 switch (keyword)
7517 case RID_AUTO_TYPE:
7518 case RID_INT:
7519 case RID_CHAR:
7520 case RID_FLOAT:
7521 case RID_DOUBLE:
7522 case RID_VOID:
7523 case RID_UNSIGNED:
7524 case RID_LONG:
7525 case RID_SHORT:
7526 case RID_SIGNED:
7527 CASE_RID_FLOATN_NX:
7528 case RID_DFLOAT32:
7529 case RID_DFLOAT64:
7530 case RID_DFLOAT128:
7531 case RID_FRACT:
7532 case RID_ACCUM:
7533 case RID_BOOL:
7534 case RID_WCHAR:
7535 case RID_CHAR16:
7536 case RID_CHAR32:
7537 case RID_SAT:
7538 case RID_COMPLEX:
7539 case RID_TYPEOF:
7540 case RID_STRUCT:
7541 case RID_CLASS:
7542 case RID_UNION:
7543 case RID_ENUM:
7544 return true;
7545 default:
7546 if (keyword >= RID_FIRST_INT_N
7547 && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
7548 && int_n_enabled_p[keyword-RID_FIRST_INT_N])
7549 return true;
7550 return false;
7554 /* Return true if KEYWORD names a type qualifier. */
7556 bool
7557 keyword_is_type_qualifier (enum rid keyword)
7559 switch (keyword)
7561 case RID_CONST:
7562 case RID_VOLATILE:
7563 case RID_RESTRICT:
7564 case RID_ATOMIC:
7565 return true;
7566 default:
7567 return false;
7571 /* Return true if KEYWORD names a storage class specifier.
7573 RID_TYPEDEF is not included in this list despite `typedef' being
7574 listed in C99 6.7.1.1. 6.7.1.3 indicates that `typedef' is listed as
7575 such for syntactic convenience only. */
7577 bool
7578 keyword_is_storage_class_specifier (enum rid keyword)
7580 switch (keyword)
7582 case RID_STATIC:
7583 case RID_EXTERN:
7584 case RID_REGISTER:
7585 case RID_AUTO:
7586 case RID_MUTABLE:
7587 case RID_THREAD:
7588 return true;
7589 default:
7590 return false;
7594 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec]. */
7596 static bool
7597 keyword_is_function_specifier (enum rid keyword)
7599 switch (keyword)
7601 case RID_INLINE:
7602 case RID_NORETURN:
7603 case RID_VIRTUAL:
7604 case RID_EXPLICIT:
7605 return true;
7606 default:
7607 return false;
7611 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
7612 declaration-specifier (C99 6.7). */
7614 bool
7615 keyword_is_decl_specifier (enum rid keyword)
7617 if (keyword_is_storage_class_specifier (keyword)
7618 || keyword_is_type_qualifier (keyword)
7619 || keyword_is_function_specifier (keyword))
7620 return true;
7622 switch (keyword)
7624 case RID_TYPEDEF:
7625 case RID_FRIEND:
7626 case RID_CONSTEXPR:
7627 return true;
7628 default:
7629 return false;
7633 /* Initialize language-specific-bits of tree_contains_struct. */
7635 void
7636 c_common_init_ts (void)
7638 MARK_TS_TYPED (C_MAYBE_CONST_EXPR);
7639 MARK_TS_TYPED (EXCESS_PRECISION_EXPR);
7642 /* Build a user-defined numeric literal out of an integer constant type VALUE
7643 with identifier SUFFIX. */
7645 tree
7646 build_userdef_literal (tree suffix_id, tree value,
7647 enum overflow_type overflow, tree num_string)
7649 tree literal = make_node (USERDEF_LITERAL);
7650 USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
7651 USERDEF_LITERAL_VALUE (literal) = value;
7652 USERDEF_LITERAL_OVERFLOW (literal) = overflow;
7653 USERDEF_LITERAL_NUM_STRING (literal) = num_string;
7654 return literal;
7657 /* For vector[index], convert the vector to an array of the underlying type.
7658 Return true if the resulting ARRAY_REF should not be an lvalue. */
7660 bool
7661 convert_vector_to_array_for_subscript (location_t loc,
7662 tree *vecp, tree index)
7664 bool ret = false;
7665 if (VECTOR_TYPE_P (TREE_TYPE (*vecp)))
7667 tree type = TREE_TYPE (*vecp);
7669 ret = !lvalue_p (*vecp);
7671 if (TREE_CODE (index) == INTEGER_CST)
7672 if (!tree_fits_uhwi_p (index)
7673 || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
7674 warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
7676 /* We are building an ARRAY_REF so mark the vector as addressable
7677 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
7678 for function parameters. */
7679 c_common_mark_addressable_vec (*vecp);
7681 *vecp = build1 (VIEW_CONVERT_EXPR,
7682 build_array_type_nelts (TREE_TYPE (type),
7683 TYPE_VECTOR_SUBPARTS (type)),
7684 *vecp);
7686 return ret;
7689 /* Determine which of the operands, if any, is a scalar that needs to be
7690 converted to a vector, for the range of operations. */
7691 enum stv_conv
7692 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
7693 bool complain)
7695 tree type0 = TREE_TYPE (op0);
7696 tree type1 = TREE_TYPE (op1);
7697 bool integer_only_op = false;
7698 enum stv_conv ret = stv_firstarg;
7700 gcc_assert (VECTOR_TYPE_P (type0) || VECTOR_TYPE_P (type1));
7701 switch (code)
7703 /* Most GENERIC binary expressions require homogeneous arguments.
7704 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
7705 argument that is a vector and a second one that is a scalar, so
7706 we never return stv_secondarg for them. */
7707 case RSHIFT_EXPR:
7708 case LSHIFT_EXPR:
7709 if (TREE_CODE (type0) == INTEGER_TYPE
7710 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
7712 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7713 NULL_TREE, false))
7715 if (complain)
7716 error_at (loc, "conversion of scalar %qT to vector %qT "
7717 "involves truncation", type0, type1);
7718 return stv_error;
7720 else
7721 return stv_firstarg;
7723 break;
7725 case BIT_IOR_EXPR:
7726 case BIT_XOR_EXPR:
7727 case BIT_AND_EXPR:
7728 integer_only_op = true;
7729 /* fall through */
7731 case VEC_COND_EXPR:
7733 case PLUS_EXPR:
7734 case MINUS_EXPR:
7735 case MULT_EXPR:
7736 case TRUNC_DIV_EXPR:
7737 case CEIL_DIV_EXPR:
7738 case FLOOR_DIV_EXPR:
7739 case ROUND_DIV_EXPR:
7740 case EXACT_DIV_EXPR:
7741 case TRUNC_MOD_EXPR:
7742 case FLOOR_MOD_EXPR:
7743 case RDIV_EXPR:
7744 case EQ_EXPR:
7745 case NE_EXPR:
7746 case LE_EXPR:
7747 case GE_EXPR:
7748 case LT_EXPR:
7749 case GT_EXPR:
7750 /* What about UNLT_EXPR? */
7751 if (VECTOR_TYPE_P (type0))
7753 ret = stv_secondarg;
7754 std::swap (type0, type1);
7755 std::swap (op0, op1);
7758 if (TREE_CODE (type0) == INTEGER_TYPE
7759 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
7761 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7762 NULL_TREE, false))
7764 if (complain)
7765 error_at (loc, "conversion of scalar %qT to vector %qT "
7766 "involves truncation", type0, type1);
7767 return stv_error;
7769 return ret;
7771 else if (!integer_only_op
7772 /* Allow integer --> real conversion if safe. */
7773 && (TREE_CODE (type0) == REAL_TYPE
7774 || TREE_CODE (type0) == INTEGER_TYPE)
7775 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
7777 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7778 NULL_TREE, false))
7780 if (complain)
7781 error_at (loc, "conversion of scalar %qT to vector %qT "
7782 "involves truncation", type0, type1);
7783 return stv_error;
7785 return ret;
7787 default:
7788 break;
7791 return stv_nothing;
7794 /* Return the alignment of std::max_align_t.
7796 [support.types.layout] The type max_align_t is a POD type whose alignment
7797 requirement is at least as great as that of every scalar type, and whose
7798 alignment requirement is supported in every context. */
7800 unsigned
7801 max_align_t_align ()
7803 unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
7804 TYPE_ALIGN (long_double_type_node));
7805 if (float128_type_node != NULL_TREE)
7806 max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
7807 return max_align;
7810 /* Return true iff ALIGN is an integral constant that is a fundamental
7811 alignment, as defined by [basic.align] in the c++-11
7812 specifications.
7814 That is:
7816 [A fundamental alignment is represented by an alignment less than or
7817 equal to the greatest alignment supported by the implementation
7818 in all contexts, which is equal to alignof(max_align_t)]. */
7820 bool
7821 cxx_fundamental_alignment_p (unsigned align)
7823 return (align <= max_align_t_align ());
7826 /* Return true if T is a pointer to a zero-sized aggregate. */
7828 bool
7829 pointer_to_zero_sized_aggr_p (tree t)
7831 if (!POINTER_TYPE_P (t))
7832 return false;
7833 t = TREE_TYPE (t);
7834 return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
7837 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
7838 with no library fallback or for an ADDR_EXPR whose operand is such type
7839 issues an error pointing to the location LOC.
7840 Returns true when the expression has been diagnosed and false
7841 otherwise. */
7843 bool
7844 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
7846 if (TREE_CODE (expr) == ADDR_EXPR)
7847 expr = TREE_OPERAND (expr, 0);
7849 if (TREE_TYPE (expr)
7850 && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
7851 && TREE_CODE (expr) == FUNCTION_DECL
7852 /* The intersection of DECL_BUILT_IN and DECL_IS_BUILTIN avoids
7853 false positives for user-declared built-ins such as abs or
7854 strlen, and for C++ operators new and delete.
7855 The c_decl_implicit() test avoids false positives for implicitly
7856 declared built-ins with library fallbacks (such as abs). */
7857 && DECL_BUILT_IN (expr)
7858 && DECL_IS_BUILTIN (expr)
7859 && !c_decl_implicit (expr)
7860 && !DECL_ASSEMBLER_NAME_SET_P (expr))
7862 if (loc == UNKNOWN_LOCATION)
7863 loc = EXPR_LOC_OR_LOC (expr, input_location);
7865 /* Reject arguments that are built-in functions with
7866 no library fallback. */
7867 error_at (loc, "built-in function %qE must be directly called", expr);
7869 return true;
7872 return false;
7875 /* Check if array size calculations overflow or if the array covers more
7876 than half of the address space. Return true if the size of the array
7877 is valid, false otherwise. TYPE is the type of the array and NAME is
7878 the name of the array, or NULL_TREE for unnamed arrays. */
7880 bool
7881 valid_array_size_p (location_t loc, tree type, tree name)
7883 if (type != error_mark_node
7884 && COMPLETE_TYPE_P (type)
7885 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
7886 && !valid_constant_size_p (TYPE_SIZE_UNIT (type)))
7888 if (name)
7889 error_at (loc, "size of array %qE is too large", name);
7890 else
7891 error_at (loc, "size of unnamed array is too large");
7892 return false;
7894 return true;
7897 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
7898 timestamp to replace embedded current dates to get reproducible
7899 results. Returns -1 if SOURCE_DATE_EPOCH is not defined. */
7901 time_t
7902 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
7904 char *source_date_epoch;
7905 int64_t epoch;
7906 char *endptr;
7908 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
7909 if (!source_date_epoch)
7910 return (time_t) -1;
7912 errno = 0;
7913 #if defined(INT64_T_IS_LONG)
7914 epoch = strtol (source_date_epoch, &endptr, 10);
7915 #else
7916 epoch = strtoll (source_date_epoch, &endptr, 10);
7917 #endif
7918 if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
7919 || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
7921 error_at (input_location, "environment variable SOURCE_DATE_EPOCH must "
7922 "expand to a non-negative integer less than or equal to %wd",
7923 MAX_SOURCE_DATE_EPOCH);
7924 return (time_t) -1;
7927 return (time_t) epoch;
7930 /* Callback for libcpp for offering spelling suggestions for misspelled
7931 directives. GOAL is an unrecognized string; CANDIDATES is a
7932 NULL-terminated array of candidate strings. Return the closest
7933 match to GOAL within CANDIDATES, or NULL if none are good
7934 suggestions. */
7936 const char *
7937 cb_get_suggestion (cpp_reader *, const char *goal,
7938 const char *const *candidates)
7940 best_match<const char *, const char *> bm (goal);
7941 while (*candidates)
7942 bm.consider (*candidates++);
7943 return bm.get_best_meaningful_candidate ();
7946 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
7947 modes X, Y. This isn't just >, as the FLT_EVAL_METHOD values added
7948 by C TS 18661-3 for interchange types that are computed in their
7949 native precision are larger than the C11 values for evaluating in the
7950 precision of float/double/long double. If either mode is
7951 FLT_EVAL_METHOD_UNPREDICTABLE, return that. */
7953 enum flt_eval_method
7954 excess_precision_mode_join (enum flt_eval_method x,
7955 enum flt_eval_method y)
7957 if (x == FLT_EVAL_METHOD_UNPREDICTABLE
7958 || y == FLT_EVAL_METHOD_UNPREDICTABLE)
7959 return FLT_EVAL_METHOD_UNPREDICTABLE;
7961 /* GCC only supports one interchange type right now, _Float16. If
7962 we're evaluating _Float16 in 16-bit precision, then flt_eval_method
7963 will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
7964 if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
7965 return y;
7966 if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
7967 return x;
7969 /* Other values for flt_eval_method are directly comparable, and we want
7970 the maximum. */
7971 return MAX (x, y);
7974 /* Return the value that should be set for FLT_EVAL_METHOD in the
7975 context of ISO/IEC TS 18861-3.
7977 This relates to the effective excess precision seen by the user,
7978 which is the join point of the precision the target requests for
7979 -fexcess-precision={standard,fast} and the implicit excess precision
7980 the target uses. */
7982 static enum flt_eval_method
7983 c_ts18661_flt_eval_method (void)
7985 enum flt_eval_method implicit
7986 = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
7988 enum excess_precision_type flag_type
7989 = (flag_excess_precision_cmdline == EXCESS_PRECISION_STANDARD
7990 ? EXCESS_PRECISION_TYPE_STANDARD
7991 : EXCESS_PRECISION_TYPE_FAST);
7993 enum flt_eval_method requested
7994 = targetm.c.excess_precision (flag_type);
7996 return excess_precision_mode_join (implicit, requested);
7999 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
8000 those that were permitted by C11. That is to say, eliminates
8001 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
8003 static enum flt_eval_method
8004 c_c11_flt_eval_method (void)
8006 return excess_precision_mode_join (c_ts18661_flt_eval_method (),
8007 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
8010 /* Return the value that should be set for FLT_EVAL_METHOD.
8011 MAYBE_C11_ONLY_P is TRUE if we should check
8012 FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
8013 values we can return to those from C99/C11, and FALSE otherwise.
8014 See the comments on c_ts18661_flt_eval_method for what value we choose
8015 to set here. */
8018 c_flt_eval_method (bool maybe_c11_only_p)
8020 if (maybe_c11_only_p
8021 && flag_permitted_flt_eval_methods
8022 == PERMITTED_FLT_EVAL_METHODS_C11)
8023 return c_c11_flt_eval_method ();
8024 else
8025 return c_ts18661_flt_eval_method ();
8028 /* An enum for get_missing_token_insertion_kind for describing the best
8029 place to insert a missing token, if there is one. */
8031 enum missing_token_insertion_kind
8033 MTIK_IMPOSSIBLE,
8034 MTIK_INSERT_BEFORE_NEXT,
8035 MTIK_INSERT_AFTER_PREV
8038 /* Given a missing token of TYPE, determine if it is reasonable to
8039 emit a fix-it hint suggesting the insertion of the token, and,
8040 if so, where the token should be inserted relative to other tokens.
8042 It only makes sense to do this for values of TYPE that are symbols.
8044 Some symbols should go before the next token, e.g. in:
8045 if flag)
8046 we want to insert the missing '(' immediately before "flag",
8047 giving:
8048 if (flag)
8049 rather than:
8050 if( flag)
8051 These use MTIK_INSERT_BEFORE_NEXT.
8053 Other symbols should go after the previous token, e.g. in:
8054 if (flag
8055 do_something ();
8056 we want to insert the missing ')' immediately after the "flag",
8057 giving:
8058 if (flag)
8059 do_something ();
8060 rather than:
8061 if (flag
8062 )do_something ();
8063 These use MTIK_INSERT_AFTER_PREV. */
8065 static enum missing_token_insertion_kind
8066 get_missing_token_insertion_kind (enum cpp_ttype type)
8068 switch (type)
8070 /* Insert missing "opening" brackets immediately
8071 before the next token. */
8072 case CPP_OPEN_SQUARE:
8073 case CPP_OPEN_PAREN:
8074 return MTIK_INSERT_BEFORE_NEXT;
8076 /* Insert other missing symbols immediately after
8077 the previous token. */
8078 case CPP_CLOSE_PAREN:
8079 case CPP_CLOSE_SQUARE:
8080 case CPP_SEMICOLON:
8081 case CPP_COMMA:
8082 case CPP_COLON:
8083 return MTIK_INSERT_AFTER_PREV;
8085 /* Other kinds of token don't get fix-it hints. */
8086 default:
8087 return MTIK_IMPOSSIBLE;
8091 /* Given RICHLOC, a location for a diagnostic describing a missing token
8092 of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
8093 insertion of the token.
8095 The location of the attempted fix-it hint depends on TOKEN_TYPE:
8096 it will either be:
8097 (a) immediately after PREV_TOKEN_LOC, or
8099 (b) immediately before the primary location within RICHLOC (taken to
8100 be that of the token following where the token was expected).
8102 If we manage to add a fix-it hint, then the location of the
8103 fix-it hint is likely to be more useful as the primary location
8104 of the diagnostic than that of the following token, so we swap
8105 these locations.
8107 For example, given this bogus code:
8108 123456789012345678901234567890
8109 1 | int missing_semicolon (void)
8110 2 | {
8111 3 | return 42
8112 4 | }
8114 we will emit:
8116 "expected ';' before '}'"
8118 RICHLOC's primary location is at the closing brace, so before "swapping"
8119 we would emit the error at line 4 column 1:
8121 123456789012345678901234567890
8122 3 | return 42 |< fix-it hint emitted for this line
8123 | ; |
8124 4 | } |< "expected ';' before '}'" emitted at this line
8125 | ^ |
8127 It's more useful for the location of the diagnostic to be at the
8128 fix-it hint, so we swap the locations, so the primary location
8129 is at the fix-it hint, with the old primary location inserted
8130 as a secondary location, giving this, with the error at line 3
8131 column 12:
8133 123456789012345678901234567890
8134 3 | return 42 |< "expected ';' before '}'" emitted at this line,
8135 | ^ | with fix-it hint
8136 4 | ; |
8137 | } |< secondary range emitted here
8138 | ~ |. */
8140 void
8141 maybe_suggest_missing_token_insertion (rich_location *richloc,
8142 enum cpp_ttype token_type,
8143 location_t prev_token_loc)
8145 gcc_assert (richloc);
8147 enum missing_token_insertion_kind mtik
8148 = get_missing_token_insertion_kind (token_type);
8150 switch (mtik)
8152 default:
8153 gcc_unreachable ();
8154 break;
8156 case MTIK_IMPOSSIBLE:
8157 return;
8159 case MTIK_INSERT_BEFORE_NEXT:
8160 /* Attempt to add the fix-it hint before the primary location
8161 of RICHLOC. */
8162 richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
8163 break;
8165 case MTIK_INSERT_AFTER_PREV:
8166 /* Attempt to add the fix-it hint after PREV_TOKEN_LOC. */
8167 richloc->add_fixit_insert_after (prev_token_loc,
8168 cpp_type2name (token_type, 0));
8169 break;
8172 /* If we were successful, use the fix-it hint's location as the
8173 primary location within RICHLOC, adding the old primary location
8174 back as a secondary location. */
8175 if (!richloc->seen_impossible_fixit_p ())
8177 fixit_hint *hint = richloc->get_last_fixit_hint ();
8178 location_t hint_loc = hint->get_start_loc ();
8179 location_t old_loc = richloc->get_loc ();
8181 richloc->set_range (line_table, 0, hint_loc, true);
8182 richloc->add_range (old_loc, false);
8186 #if CHECKING_P
8188 namespace selftest {
8190 /* Run all of the tests within c-family. */
8192 void
8193 c_family_tests (void)
8195 c_format_c_tests ();
8196 c_spellcheck_cc_tests ();
8199 } // namespace selftest
8201 #endif /* #if CHECKING_P */
8203 /* Attempt to locate a suitable location within FILE for a
8204 #include directive to be inserted before. FILE should
8205 be a string from libcpp (pointer equality is used).
8206 LOC is the location of the relevant diagnostic.
8208 Attempt to return the location within FILE immediately
8209 after the last #include within that file, or the start of
8210 that file if it has no #include directives.
8212 Return UNKNOWN_LOCATION if no suitable location is found,
8213 or if an error occurs. */
8215 static location_t
8216 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
8218 /* Locate the last ordinary map within FILE that ended with a #include. */
8219 const line_map_ordinary *last_include_ord_map = NULL;
8221 /* ...and the next ordinary map within FILE after that one. */
8222 const line_map_ordinary *last_ord_map_after_include = NULL;
8224 /* ...and the first ordinary map within FILE. */
8225 const line_map_ordinary *first_ord_map_in_file = NULL;
8227 /* Get ordinary map containing LOC (or its expansion). */
8228 const line_map_ordinary *ord_map_for_loc = NULL;
8229 loc = linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
8230 &ord_map_for_loc);
8231 gcc_assert (ord_map_for_loc);
8233 for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
8235 const line_map_ordinary *ord_map
8236 = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
8238 const line_map_ordinary *from = INCLUDED_FROM (line_table, ord_map);
8239 if (from)
8240 if (from->to_file == file)
8242 last_include_ord_map = from;
8243 last_ord_map_after_include = NULL;
8246 if (ord_map->to_file == file)
8248 if (!first_ord_map_in_file)
8249 first_ord_map_in_file = ord_map;
8250 if (last_include_ord_map && !last_ord_map_after_include)
8251 last_ord_map_after_include = ord_map;
8254 /* Stop searching when reaching the ord_map containing LOC,
8255 as it makes no sense to provide fix-it hints that appear
8256 after the diagnostic in question. */
8257 if (ord_map == ord_map_for_loc)
8258 break;
8261 /* Determine where to insert the #include. */
8262 const line_map_ordinary *ord_map_for_insertion;
8264 /* We want the next ordmap in the file after the last one that's a
8265 #include, but failing that, the start of the file. */
8266 if (last_ord_map_after_include)
8267 ord_map_for_insertion = last_ord_map_after_include;
8268 else
8269 ord_map_for_insertion = first_ord_map_in_file;
8271 if (!ord_map_for_insertion)
8272 return UNKNOWN_LOCATION;
8274 /* The "start_location" is column 0, meaning "the whole line".
8275 rich_location and edit_context can't cope with this, so use
8276 column 1 instead. */
8277 location_t col_0 = ord_map_for_insertion->start_location;
8278 return linemap_position_for_loc_and_offset (line_table, col_0, 1);
8281 /* A map from filenames to sets of headers added to them, for
8282 ensuring idempotency within maybe_add_include_fixit. */
8284 /* The values within the map. We need string comparison as there's
8285 no guarantee that two different diagnostics that are recommending
8286 adding e.g. "<stdio.h>" are using the same buffer. */
8288 typedef hash_set <const char *, nofree_string_hash> per_file_includes_t;
8290 /* The map itself. We don't need string comparison for the filename keys,
8291 as they come from libcpp. */
8293 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
8294 static added_includes_t *added_includes;
8296 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
8297 in a suitable location within the file of RICHLOC's primary
8298 location.
8300 This function is idempotent: a header will be added at most once to
8301 any given file. */
8303 void
8304 maybe_add_include_fixit (rich_location *richloc, const char *header)
8306 location_t loc = richloc->get_loc ();
8307 const char *file = LOCATION_FILE (loc);
8308 if (!file)
8309 return;
8311 /* Idempotency: don't add the same header more than once to a given file. */
8312 if (!added_includes)
8313 added_includes = new added_includes_t ();
8314 per_file_includes_t *&set = added_includes->get_or_insert (file);
8315 if (set)
8316 if (set->contains (header))
8317 /* ...then we've already added HEADER to that file. */
8318 return;
8319 if (!set)
8320 set = new per_file_includes_t ();
8321 set->add (header);
8323 /* Attempt to locate a suitable place for the new directive. */
8324 location_t include_insert_loc
8325 = try_to_locate_new_include_insertion_point (file, loc);
8326 if (include_insert_loc == UNKNOWN_LOCATION)
8327 return;
8329 char *text = xasprintf ("#include %s\n", header);
8330 richloc->add_fixit_insert_before (include_insert_loc, text);
8331 free (text);
8334 #include "gt-c-family-c-common.h"