Suppress -fstack-protector warning on hppa.
[official-gcc.git] / gcc / attribs.cc
blob095def4d6b053668eb16a68bfe9274cb6ac02424
1 /* Functions dealing with attribute handling, used by most front ends.
2 Copyright (C) 1992-2022 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 INCLUDE_STRING
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "target.h"
25 #include "tree.h"
26 #include "stringpool.h"
27 #include "diagnostic-core.h"
28 #include "attribs.h"
29 #include "fold-const.h"
30 #include "stor-layout.h"
31 #include "langhooks.h"
32 #include "plugin.h"
33 #include "selftest.h"
34 #include "hash-set.h"
35 #include "diagnostic.h"
36 #include "pretty-print.h"
37 #include "tree-pretty-print.h"
38 #include "intl.h"
40 /* Table of the tables of attributes (common, language, format, machine)
41 searched. */
42 static const struct attribute_spec *attribute_tables[4];
44 /* Substring representation. */
46 struct substring
48 const char *str;
49 int length;
52 /* Simple hash function to avoid need to scan whole string. */
54 static inline hashval_t
55 substring_hash (const char *str, int l)
57 return str[0] + str[l - 1] * 256 + l * 65536;
60 /* Used for attribute_hash. */
62 struct attribute_hasher : nofree_ptr_hash <attribute_spec>
64 typedef substring *compare_type;
65 static inline hashval_t hash (const attribute_spec *);
66 static inline bool equal (const attribute_spec *, const substring *);
69 inline hashval_t
70 attribute_hasher::hash (const attribute_spec *spec)
72 const int l = strlen (spec->name);
73 return substring_hash (spec->name, l);
76 inline bool
77 attribute_hasher::equal (const attribute_spec *spec, const substring *str)
79 return (strncmp (spec->name, str->str, str->length) == 0
80 && !spec->name[str->length]);
83 /* Scoped attribute name representation. */
85 struct scoped_attributes
87 const char *ns;
88 vec<attribute_spec> attributes;
89 hash_table<attribute_hasher> *attribute_hash;
90 /* True if we should not warn about unknown attributes in this NS. */
91 bool ignored_p;
94 /* The table of scope attributes. */
95 static vec<scoped_attributes> attributes_table;
97 static scoped_attributes* find_attribute_namespace (const char*);
98 static void register_scoped_attribute (const struct attribute_spec *,
99 scoped_attributes *);
100 static const struct attribute_spec *lookup_scoped_attribute_spec (const_tree,
101 const_tree);
103 static bool attributes_initialized = false;
105 /* Default empty table of attributes. */
107 static const struct attribute_spec empty_attribute_table[] =
109 { NULL, 0, 0, false, false, false, false, NULL, NULL }
112 /* Return base name of the attribute. Ie '__attr__' is turned into 'attr'.
113 To avoid need for copying, we simply return length of the string. */
115 static void
116 extract_attribute_substring (struct substring *str)
118 canonicalize_attr_name (str->str, str->length);
121 /* Insert an array of attributes ATTRIBUTES into a namespace. This
122 array must be NULL terminated. NS is the name of attribute
123 namespace. IGNORED_P is true iff all unknown attributes in this
124 namespace should be ignored for the purposes of -Wattributes. The
125 function returns the namespace into which the attributes have been
126 registered. */
128 scoped_attributes *
129 register_scoped_attributes (const struct attribute_spec *attributes,
130 const char *ns, bool ignored_p /*=false*/)
132 scoped_attributes *result = NULL;
134 /* See if we already have attributes in the namespace NS. */
135 result = find_attribute_namespace (ns);
137 if (result == NULL)
139 /* We don't have any namespace NS yet. Create one. */
140 scoped_attributes sa;
142 if (attributes_table.is_empty ())
143 attributes_table.create (64);
145 memset (&sa, 0, sizeof (sa));
146 sa.ns = ns;
147 sa.attributes.create (64);
148 sa.ignored_p = ignored_p;
149 result = attributes_table.safe_push (sa);
150 result->attribute_hash = new hash_table<attribute_hasher> (200);
152 else
153 result->ignored_p |= ignored_p;
155 /* Really add the attributes to their namespace now. */
156 for (unsigned i = 0; attributes[i].name != NULL; ++i)
158 result->attributes.safe_push (attributes[i]);
159 register_scoped_attribute (&attributes[i], result);
162 gcc_assert (result != NULL);
164 return result;
167 /* Return the namespace which name is NS, NULL if none exist. */
169 static scoped_attributes*
170 find_attribute_namespace (const char* ns)
172 for (scoped_attributes &iter : attributes_table)
173 if (ns == iter.ns
174 || (iter.ns != NULL
175 && ns != NULL
176 && !strcmp (iter.ns, ns)))
177 return &iter;
178 return NULL;
181 /* Make some sanity checks on the attribute tables. */
183 static void
184 check_attribute_tables (void)
186 for (size_t i = 0; i < ARRAY_SIZE (attribute_tables); i++)
187 for (size_t j = 0; attribute_tables[i][j].name != NULL; j++)
189 /* The name must not begin and end with __. */
190 const char *name = attribute_tables[i][j].name;
191 int len = strlen (name);
193 gcc_assert (!(name[0] == '_' && name[1] == '_'
194 && name[len - 1] == '_' && name[len - 2] == '_'));
196 /* The minimum and maximum lengths must be consistent. */
197 gcc_assert (attribute_tables[i][j].min_length >= 0);
199 gcc_assert (attribute_tables[i][j].max_length == -1
200 || (attribute_tables[i][j].max_length
201 >= attribute_tables[i][j].min_length));
203 /* An attribute cannot require both a DECL and a TYPE. */
204 gcc_assert (!attribute_tables[i][j].decl_required
205 || !attribute_tables[i][j].type_required);
207 /* If an attribute requires a function type, in particular
208 it requires a type. */
209 gcc_assert (!attribute_tables[i][j].function_type_required
210 || attribute_tables[i][j].type_required);
213 /* Check that each name occurs just once in each table. */
214 for (size_t i = 0; i < ARRAY_SIZE (attribute_tables); i++)
215 for (size_t j = 0; attribute_tables[i][j].name != NULL; j++)
216 for (size_t k = j + 1; attribute_tables[i][k].name != NULL; k++)
217 gcc_assert (strcmp (attribute_tables[i][j].name,
218 attribute_tables[i][k].name));
220 /* Check that no name occurs in more than one table. Names that
221 begin with '*' are exempt, and may be overridden. */
222 for (size_t i = 0; i < ARRAY_SIZE (attribute_tables); i++)
223 for (size_t j = i + 1; j < ARRAY_SIZE (attribute_tables); j++)
224 for (size_t k = 0; attribute_tables[i][k].name != NULL; k++)
225 for (size_t l = 0; attribute_tables[j][l].name != NULL; l++)
226 gcc_assert (attribute_tables[i][k].name[0] == '*'
227 || strcmp (attribute_tables[i][k].name,
228 attribute_tables[j][l].name));
231 /* Used to stash pointers to allocated memory so that we can free them at
232 the end of parsing of all TUs. */
233 static vec<attribute_spec *> ignored_attributes_table;
235 /* Parse arguments V of -Wno-attributes=.
236 Currently we accept:
237 vendor::attr
238 vendor::
239 This functions also registers the parsed attributes so that we don't
240 warn that we don't recognize them. */
242 void
243 handle_ignored_attributes_option (vec<char *> *v)
245 if (v == nullptr)
246 return;
248 for (auto opt : v)
250 char *cln = strstr (opt, "::");
251 /* We don't accept '::attr'. */
252 if (cln == nullptr || cln == opt)
254 auto_diagnostic_group d;
255 error ("wrong argument to ignored attributes");
256 inform (input_location, "valid format is %<ns::attr%> or %<ns::%>");
257 continue;
259 const char *vendor_start = opt;
260 ptrdiff_t vendor_len = cln - opt;
261 const char *attr_start = cln + 2;
262 /* This could really use rawmemchr :(. */
263 ptrdiff_t attr_len = strchr (attr_start, '\0') - attr_start;
264 /* Verify that they look valid. */
265 auto valid_p = [](const char *const s, ptrdiff_t len) {
266 bool ok = false;
268 for (int i = 0; i < len; ++i)
269 if (ISALNUM (s[i]))
270 ok = true;
271 else if (s[i] != '_')
272 return false;
274 return ok;
276 if (!valid_p (vendor_start, vendor_len))
278 error ("wrong argument to ignored attributes");
279 continue;
281 canonicalize_attr_name (vendor_start, vendor_len);
282 /* We perform all this hijinks so that we don't have to copy OPT. */
283 tree vendor_id = get_identifier_with_length (vendor_start, vendor_len);
284 const char *attr;
285 /* In the "vendor::" case, we should ignore *any* attribute coming
286 from this attribute namespace. */
287 if (attr_len > 0)
289 if (!valid_p (attr_start, attr_len))
291 error ("wrong argument to ignored attributes");
292 continue;
294 canonicalize_attr_name (attr_start, attr_len);
295 tree attr_id = get_identifier_with_length (attr_start, attr_len);
296 attr = IDENTIFIER_POINTER (attr_id);
297 /* If we've already seen this vendor::attr, ignore it. Attempting to
298 register it twice would lead to a crash. */
299 if (lookup_scoped_attribute_spec (vendor_id, attr_id))
300 continue;
302 else
303 attr = nullptr;
304 /* Create a table with extra attributes which we will register.
305 We can't free it here, so squirrel away the pointers. */
306 attribute_spec *table = new attribute_spec[2];
307 ignored_attributes_table.safe_push (table);
308 table[0] = { attr, 0, -2, false, false, false, false, nullptr, nullptr };
309 table[1] = { nullptr, 0, 0, false, false, false, false, nullptr,
310 nullptr };
311 register_scoped_attributes (table, IDENTIFIER_POINTER (vendor_id), !attr);
315 /* Free data we might have allocated when adding extra attributes. */
317 void
318 free_attr_data ()
320 for (auto x : ignored_attributes_table)
321 delete[] x;
322 ignored_attributes_table.release ();
325 /* Initialize attribute tables, and make some sanity checks if checking is
326 enabled. */
328 void
329 init_attributes (void)
331 size_t i;
333 if (attributes_initialized)
334 return;
336 attribute_tables[0] = lang_hooks.common_attribute_table;
337 attribute_tables[1] = lang_hooks.attribute_table;
338 attribute_tables[2] = lang_hooks.format_attribute_table;
339 attribute_tables[3] = targetm.attribute_table;
341 /* Translate NULL pointers to pointers to the empty table. */
342 for (i = 0; i < ARRAY_SIZE (attribute_tables); i++)
343 if (attribute_tables[i] == NULL)
344 attribute_tables[i] = empty_attribute_table;
346 if (flag_checking)
347 check_attribute_tables ();
349 for (i = 0; i < ARRAY_SIZE (attribute_tables); ++i)
350 /* Put all the GNU attributes into the "gnu" namespace. */
351 register_scoped_attributes (attribute_tables[i], "gnu");
353 vec<char *> *ignored = (vec<char *> *) flag_ignored_attributes;
354 handle_ignored_attributes_option (ignored);
356 invoke_plugin_callbacks (PLUGIN_ATTRIBUTES, NULL);
357 attributes_initialized = true;
360 /* Insert a single ATTR into the attribute table. */
362 void
363 register_attribute (const struct attribute_spec *attr)
365 register_scoped_attribute (attr, find_attribute_namespace ("gnu"));
368 /* Insert a single attribute ATTR into a namespace of attributes. */
370 static void
371 register_scoped_attribute (const struct attribute_spec *attr,
372 scoped_attributes *name_space)
374 struct substring str;
375 attribute_spec **slot;
377 gcc_assert (attr != NULL && name_space != NULL);
379 gcc_assert (name_space->attribute_hash);
381 str.str = attr->name;
382 str.length = strlen (str.str);
384 /* Attribute names in the table must be in the form 'text' and not
385 in the form '__text__'. */
386 gcc_checking_assert (!canonicalize_attr_name (str.str, str.length));
388 slot = name_space->attribute_hash
389 ->find_slot_with_hash (&str, substring_hash (str.str, str.length),
390 INSERT);
391 gcc_assert (!*slot || attr->name[0] == '*');
392 *slot = CONST_CAST (struct attribute_spec *, attr);
395 /* Return the spec for the scoped attribute with namespace NS and
396 name NAME. */
398 static const struct attribute_spec *
399 lookup_scoped_attribute_spec (const_tree ns, const_tree name)
401 struct substring attr;
402 scoped_attributes *attrs;
404 const char *ns_str = (ns != NULL_TREE) ? IDENTIFIER_POINTER (ns): NULL;
406 attrs = find_attribute_namespace (ns_str);
408 if (attrs == NULL)
409 return NULL;
411 attr.str = IDENTIFIER_POINTER (name);
412 attr.length = IDENTIFIER_LENGTH (name);
413 extract_attribute_substring (&attr);
414 return attrs->attribute_hash->find_with_hash (&attr,
415 substring_hash (attr.str,
416 attr.length));
419 /* Return the spec for the attribute named NAME. If NAME is a TREE_LIST,
420 it also specifies the attribute namespace. */
422 const struct attribute_spec *
423 lookup_attribute_spec (const_tree name)
425 tree ns;
426 if (TREE_CODE (name) == TREE_LIST)
428 ns = TREE_PURPOSE (name);
429 name = TREE_VALUE (name);
431 else
432 ns = get_identifier ("gnu");
433 return lookup_scoped_attribute_spec (ns, name);
437 /* Return the namespace of the attribute ATTR. This accessor works on
438 GNU and C++11 (scoped) attributes. On GNU attributes,
439 it returns an identifier tree for the string "gnu".
441 Please read the comments of cxx11_attribute_p to understand the
442 format of attributes. */
444 tree
445 get_attribute_namespace (const_tree attr)
447 if (cxx11_attribute_p (attr))
448 return TREE_PURPOSE (TREE_PURPOSE (attr));
449 return get_identifier ("gnu");
452 /* Check LAST_DECL and NODE of the same symbol for attributes that are
453 recorded in SPEC to be mutually exclusive with ATTRNAME, diagnose
454 them, and return true if any have been found. NODE can be a DECL
455 or a TYPE. */
457 static bool
458 diag_attr_exclusions (tree last_decl, tree node, tree attrname,
459 const attribute_spec *spec)
461 const attribute_spec::exclusions *excl = spec->exclude;
463 tree_code code = TREE_CODE (node);
465 if ((code == FUNCTION_DECL && !excl->function
466 && (!excl->type || !spec->affects_type_identity))
467 || (code == VAR_DECL && !excl->variable
468 && (!excl->type || !spec->affects_type_identity))
469 || (((code == TYPE_DECL || RECORD_OR_UNION_TYPE_P (node)) && !excl->type)))
470 return false;
472 /* True if an attribute that's mutually exclusive with ATTRNAME
473 has been found. */
474 bool found = false;
476 if (last_decl && last_decl != node && TREE_TYPE (last_decl) != node)
478 /* Check both the last DECL and its type for conflicts with
479 the attribute being added to the current decl or type. */
480 found |= diag_attr_exclusions (last_decl, last_decl, attrname, spec);
481 tree decl_type = TREE_TYPE (last_decl);
482 found |= diag_attr_exclusions (last_decl, decl_type, attrname, spec);
485 /* NODE is either the current DECL to which the attribute is being
486 applied or its TYPE. For the former, consider the attributes on
487 both the DECL and its type. */
488 tree attrs[2];
490 if (DECL_P (node))
492 attrs[0] = DECL_ATTRIBUTES (node);
493 attrs[1] = TYPE_ATTRIBUTES (TREE_TYPE (node));
495 else
497 attrs[0] = TYPE_ATTRIBUTES (node);
498 attrs[1] = NULL_TREE;
501 /* Iterate over the mutually exclusive attribute names and verify
502 that the symbol doesn't contain it. */
503 for (unsigned i = 0; i != ARRAY_SIZE (attrs); ++i)
505 if (!attrs[i])
506 continue;
508 for ( ; excl->name; ++excl)
510 /* Avoid checking the attribute against itself. */
511 if (is_attribute_p (excl->name, attrname))
512 continue;
514 if (!lookup_attribute (excl->name, attrs[i]))
515 continue;
517 /* An exclusion may apply either to a function declaration,
518 type declaration, or a field/variable declaration, or
519 any subset of the three. */
520 if (TREE_CODE (node) == FUNCTION_DECL
521 && !excl->function)
522 continue;
524 if (TREE_CODE (node) == TYPE_DECL
525 && !excl->type)
526 continue;
528 if ((TREE_CODE (node) == FIELD_DECL
529 || TREE_CODE (node) == VAR_DECL)
530 && !excl->variable)
531 continue;
533 found = true;
535 /* Print a note? */
536 bool note = last_decl != NULL_TREE;
537 auto_diagnostic_group d;
538 if (TREE_CODE (node) == FUNCTION_DECL
539 && fndecl_built_in_p (node))
540 note &= warning (OPT_Wattributes,
541 "ignoring attribute %qE in declaration of "
542 "a built-in function %qD because it conflicts "
543 "with attribute %qs",
544 attrname, node, excl->name);
545 else
546 note &= warning (OPT_Wattributes,
547 "ignoring attribute %qE because "
548 "it conflicts with attribute %qs",
549 attrname, excl->name);
551 if (note)
552 inform (DECL_SOURCE_LOCATION (last_decl),
553 "previous declaration here");
557 return found;
560 /* Return true iff we should not complain about unknown attributes
561 coming from the attribute namespace NS. This is the case for
562 the -Wno-attributes=ns:: command-line option. */
564 static bool
565 attr_namespace_ignored_p (tree ns)
567 if (ns == NULL_TREE)
568 return false;
569 scoped_attributes *r = find_attribute_namespace (IDENTIFIER_POINTER (ns));
570 return r && r->ignored_p;
573 /* Return true if the attribute ATTR should not be warned about. */
575 bool
576 attribute_ignored_p (tree attr)
578 if (!cxx11_attribute_p (attr))
579 return false;
580 if (tree ns = get_attribute_namespace (attr))
582 if (attr_namespace_ignored_p (ns))
583 return true;
584 const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (attr));
585 if (as && as->max_length == -2)
586 return true;
588 return false;
591 /* Like above, but takes an attribute_spec AS, which must be nonnull. */
593 bool
594 attribute_ignored_p (const attribute_spec *const as)
596 return as->max_length == -2;
599 /* Process the attributes listed in ATTRIBUTES and install them in *NODE,
600 which is either a DECL (including a TYPE_DECL) or a TYPE. If a DECL,
601 it should be modified in place; if a TYPE, a copy should be created
602 unless ATTR_FLAG_TYPE_IN_PLACE is set in FLAGS. FLAGS gives further
603 information, in the form of a bitwise OR of flags in enum attribute_flags
604 from tree.h. Depending on these flags, some attributes may be
605 returned to be applied at a later stage (for example, to apply
606 a decl attribute to the declaration rather than to its type). */
608 tree
609 decl_attributes (tree *node, tree attributes, int flags,
610 tree last_decl /* = NULL_TREE */)
612 tree returned_attrs = NULL_TREE;
614 if (TREE_TYPE (*node) == error_mark_node || attributes == error_mark_node)
615 return NULL_TREE;
617 if (!attributes_initialized)
618 init_attributes ();
620 /* If this is a function and the user used #pragma GCC optimize, add the
621 options to the attribute((optimize(...))) list. */
622 if (TREE_CODE (*node) == FUNCTION_DECL && current_optimize_pragma)
624 tree cur_attr = lookup_attribute ("optimize", attributes);
625 tree opts = copy_list (current_optimize_pragma);
627 if (! cur_attr)
628 attributes
629 = tree_cons (get_identifier ("optimize"), opts, attributes);
630 else
631 TREE_VALUE (cur_attr) = chainon (opts, TREE_VALUE (cur_attr));
634 if (TREE_CODE (*node) == FUNCTION_DECL
635 && (optimization_current_node != optimization_default_node
636 || target_option_current_node != target_option_default_node)
637 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (*node))
639 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (*node) = optimization_current_node;
640 /* Don't set DECL_FUNCTION_SPECIFIC_TARGET for targets that don't
641 support #pragma GCC target or target attribute. */
642 if (target_option_default_node)
644 tree cur_tree
645 = build_target_option_node (&global_options, &global_options_set);
646 tree old_tree = DECL_FUNCTION_SPECIFIC_TARGET (*node);
647 if (!old_tree)
648 old_tree = target_option_default_node;
649 /* The changes on optimization options can cause the changes in
650 target options, update it accordingly if it's changed. */
651 if (old_tree != cur_tree)
652 DECL_FUNCTION_SPECIFIC_TARGET (*node) = cur_tree;
656 /* If this is a function and the user used #pragma GCC target, add the
657 options to the attribute((target(...))) list. */
658 if (TREE_CODE (*node) == FUNCTION_DECL
659 && current_target_pragma
660 && targetm.target_option.valid_attribute_p (*node, NULL_TREE,
661 current_target_pragma, 0))
663 tree cur_attr = lookup_attribute ("target", attributes);
664 tree opts = copy_list (current_target_pragma);
666 if (! cur_attr)
667 attributes = tree_cons (get_identifier ("target"), opts, attributes);
668 else
669 TREE_VALUE (cur_attr) = chainon (opts, TREE_VALUE (cur_attr));
672 /* A "naked" function attribute implies "noinline" and "noclone" for
673 those targets that support it. */
674 if (TREE_CODE (*node) == FUNCTION_DECL
675 && attributes
676 && lookup_attribute ("naked", attributes) != NULL
677 && lookup_attribute_spec (get_identifier ("naked"))
678 && lookup_attribute ("noipa", attributes) == NULL)
679 attributes = tree_cons (get_identifier ("noipa"), NULL, attributes);
681 /* A "noipa" function attribute implies "noinline", "noclone" and "no_icf"
682 for those targets that support it. */
683 if (TREE_CODE (*node) == FUNCTION_DECL
684 && attributes
685 && lookup_attribute ("noipa", attributes) != NULL
686 && lookup_attribute_spec (get_identifier ("noipa")))
688 if (lookup_attribute ("noinline", attributes) == NULL)
689 attributes = tree_cons (get_identifier ("noinline"), NULL, attributes);
691 if (lookup_attribute ("noclone", attributes) == NULL)
692 attributes = tree_cons (get_identifier ("noclone"), NULL, attributes);
694 if (lookup_attribute ("no_icf", attributes) == NULL)
695 attributes = tree_cons (get_identifier ("no_icf"), NULL, attributes);
698 targetm.insert_attributes (*node, &attributes);
700 /* Note that attributes on the same declaration are not necessarily
701 in the same order as in the source. */
702 for (tree attr = attributes; attr; attr = TREE_CHAIN (attr))
704 tree ns = get_attribute_namespace (attr);
705 tree name = get_attribute_name (attr);
706 tree args = TREE_VALUE (attr);
707 tree *anode = node;
708 const struct attribute_spec *spec
709 = lookup_scoped_attribute_spec (ns, name);
710 int fn_ptr_quals = 0;
711 tree fn_ptr_tmp = NULL_TREE;
712 const bool cxx11_attr_p = cxx11_attribute_p (attr);
714 if (spec == NULL)
716 if (!(flags & (int) ATTR_FLAG_BUILT_IN)
717 && !attr_namespace_ignored_p (ns))
719 if (ns == NULL_TREE || !cxx11_attr_p)
720 warning (OPT_Wattributes, "%qE attribute directive ignored",
721 name);
722 else
723 warning (OPT_Wattributes,
724 "%<%E::%E%> scoped attribute directive ignored",
725 ns, name);
727 continue;
729 else
731 int nargs = list_length (args);
732 if (nargs < spec->min_length
733 || (spec->max_length >= 0
734 && nargs > spec->max_length))
736 auto_diagnostic_group d;
737 error ("wrong number of arguments specified for %qE attribute",
738 name);
739 if (spec->max_length < 0)
740 inform (input_location, "expected %i or more, found %i",
741 spec->min_length, nargs);
742 else if (spec->min_length == spec->max_length)
743 inform (input_location, "expected %i, found %i",
744 spec->min_length, nargs);
745 else
746 inform (input_location, "expected between %i and %i, found %i",
747 spec->min_length, spec->max_length, nargs);
748 continue;
751 gcc_assert (is_attribute_p (spec->name, name));
753 if (spec->decl_required && !DECL_P (*anode))
755 if (flags & ((int) ATTR_FLAG_DECL_NEXT
756 | (int) ATTR_FLAG_FUNCTION_NEXT
757 | (int) ATTR_FLAG_ARRAY_NEXT))
759 /* Pass on this attribute to be tried again. */
760 tree attr = tree_cons (name, args, NULL_TREE);
761 returned_attrs = chainon (returned_attrs, attr);
762 continue;
764 else
766 warning (OPT_Wattributes, "%qE attribute does not apply to types",
767 name);
768 continue;
772 /* If we require a type, but were passed a decl, set up to make a
773 new type and update the one in the decl. ATTR_FLAG_TYPE_IN_PLACE
774 would have applied if we'd been passed a type, but we cannot modify
775 the decl's type in place here. */
776 if (spec->type_required && DECL_P (*anode))
778 anode = &TREE_TYPE (*anode);
779 flags &= ~(int) ATTR_FLAG_TYPE_IN_PLACE;
782 if (spec->function_type_required && TREE_CODE (*anode) != FUNCTION_TYPE
783 && TREE_CODE (*anode) != METHOD_TYPE)
785 if (TREE_CODE (*anode) == POINTER_TYPE
786 && (TREE_CODE (TREE_TYPE (*anode)) == FUNCTION_TYPE
787 || TREE_CODE (TREE_TYPE (*anode)) == METHOD_TYPE))
789 /* OK, this is a bit convoluted. We can't just make a copy
790 of the pointer type and modify its TREE_TYPE, because if
791 we change the attributes of the target type the pointer
792 type needs to have a different TYPE_MAIN_VARIANT. So we
793 pull out the target type now, frob it as appropriate, and
794 rebuild the pointer type later.
796 This would all be simpler if attributes were part of the
797 declarator, grumble grumble. */
798 fn_ptr_tmp = TREE_TYPE (*anode);
799 fn_ptr_quals = TYPE_QUALS (*anode);
800 anode = &fn_ptr_tmp;
801 flags &= ~(int) ATTR_FLAG_TYPE_IN_PLACE;
803 else if (flags & (int) ATTR_FLAG_FUNCTION_NEXT)
805 /* Pass on this attribute to be tried again. */
806 tree attr = tree_cons (name, args, NULL_TREE);
807 returned_attrs = chainon (returned_attrs, attr);
808 continue;
811 if (TREE_CODE (*anode) != FUNCTION_TYPE
812 && TREE_CODE (*anode) != METHOD_TYPE)
814 warning (OPT_Wattributes,
815 "%qE attribute only applies to function types",
816 name);
817 continue;
821 if (TYPE_P (*anode)
822 && (flags & (int) ATTR_FLAG_TYPE_IN_PLACE)
823 && TYPE_SIZE (*anode) != NULL_TREE)
825 warning (OPT_Wattributes, "type attributes ignored after type is already defined");
826 continue;
829 bool no_add_attrs = false;
831 /* Check for exclusions with other attributes on the current
832 declation as well as the last declaration of the same
833 symbol already processed (if one exists). Detect and
834 reject incompatible attributes. */
835 bool built_in = flags & ATTR_FLAG_BUILT_IN;
836 if (spec->exclude
837 && (flag_checking || !built_in)
838 && !error_operand_p (last_decl))
840 /* Always check attributes on user-defined functions.
841 Check them on built-ins only when -fchecking is set.
842 Ignore __builtin_unreachable -- it's both const and
843 noreturn. */
845 if (!built_in
846 || !DECL_P (*anode)
847 || DECL_BUILT_IN_CLASS (*anode) != BUILT_IN_NORMAL
848 || (DECL_FUNCTION_CODE (*anode) != BUILT_IN_UNREACHABLE
849 && (DECL_FUNCTION_CODE (*anode)
850 != BUILT_IN_UBSAN_HANDLE_BUILTIN_UNREACHABLE)))
852 bool no_add = diag_attr_exclusions (last_decl, *anode, name, spec);
853 if (!no_add && anode != node)
854 no_add = diag_attr_exclusions (last_decl, *node, name, spec);
855 no_add_attrs |= no_add;
859 if (no_add_attrs)
860 continue;
862 if (spec->handler != NULL)
864 int cxx11_flag = (cxx11_attr_p ? ATTR_FLAG_CXX11 : 0);
866 /* Pass in an array of the current declaration followed
867 by the last pushed/merged declaration if one exists.
868 For calls that modify the type attributes of a DECL
869 and for which *ANODE is *NODE's type, also pass in
870 the DECL as the third element to use in diagnostics.
871 If the handler changes CUR_AND_LAST_DECL[0] replace
872 *ANODE with its value. */
873 tree cur_and_last_decl[3] = { *anode, last_decl };
874 if (anode != node && DECL_P (*node))
875 cur_and_last_decl[2] = *node;
877 tree ret = (spec->handler) (cur_and_last_decl, name, args,
878 flags|cxx11_flag, &no_add_attrs);
880 /* Fix up typedefs clobbered by attribute handlers. */
881 if (TREE_CODE (*node) == TYPE_DECL
882 && anode == &TREE_TYPE (*node)
883 && DECL_ORIGINAL_TYPE (*node)
884 && TYPE_NAME (*anode) == *node
885 && TYPE_NAME (cur_and_last_decl[0]) != *node)
887 tree t = cur_and_last_decl[0];
888 DECL_ORIGINAL_TYPE (*node) = t;
889 tree tt = build_variant_type_copy (t);
890 cur_and_last_decl[0] = tt;
891 TREE_TYPE (*node) = tt;
892 TYPE_NAME (tt) = *node;
895 *anode = cur_and_last_decl[0];
896 if (ret == error_mark_node)
898 warning (OPT_Wattributes, "%qE attribute ignored", name);
899 no_add_attrs = true;
901 else
902 returned_attrs = chainon (ret, returned_attrs);
905 /* Layout the decl in case anything changed. */
906 if (spec->type_required && DECL_P (*node)
907 && (VAR_P (*node)
908 || TREE_CODE (*node) == PARM_DECL
909 || TREE_CODE (*node) == RESULT_DECL))
910 relayout_decl (*node);
912 if (!no_add_attrs)
914 tree old_attrs;
915 tree a;
917 if (DECL_P (*anode))
918 old_attrs = DECL_ATTRIBUTES (*anode);
919 else
920 old_attrs = TYPE_ATTRIBUTES (*anode);
922 for (a = lookup_attribute (spec->name, old_attrs);
923 a != NULL_TREE;
924 a = lookup_attribute (spec->name, TREE_CHAIN (a)))
926 if (simple_cst_equal (TREE_VALUE (a), args) == 1)
927 break;
930 if (a == NULL_TREE)
932 /* This attribute isn't already in the list. */
933 tree r;
934 /* Preserve the C++11 form. */
935 if (cxx11_attr_p)
936 r = tree_cons (build_tree_list (ns, name), args, old_attrs);
937 else
938 r = tree_cons (name, args, old_attrs);
940 if (DECL_P (*anode))
941 DECL_ATTRIBUTES (*anode) = r;
942 else if (flags & (int) ATTR_FLAG_TYPE_IN_PLACE)
944 TYPE_ATTRIBUTES (*anode) = r;
945 /* If this is the main variant, also push the attributes
946 out to the other variants. */
947 if (*anode == TYPE_MAIN_VARIANT (*anode))
949 for (tree variant = *anode; variant;
950 variant = TYPE_NEXT_VARIANT (variant))
952 if (TYPE_ATTRIBUTES (variant) == old_attrs)
953 TYPE_ATTRIBUTES (variant)
954 = TYPE_ATTRIBUTES (*anode);
955 else if (!lookup_attribute
956 (spec->name, TYPE_ATTRIBUTES (variant)))
957 TYPE_ATTRIBUTES (variant) = tree_cons
958 (name, args, TYPE_ATTRIBUTES (variant));
962 else
963 *anode = build_type_attribute_variant (*anode, r);
967 if (fn_ptr_tmp)
969 /* Rebuild the function pointer type and put it in the
970 appropriate place. */
971 fn_ptr_tmp = build_pointer_type (fn_ptr_tmp);
972 if (fn_ptr_quals)
973 fn_ptr_tmp = build_qualified_type (fn_ptr_tmp, fn_ptr_quals);
974 if (DECL_P (*node))
975 TREE_TYPE (*node) = fn_ptr_tmp;
976 else
978 gcc_assert (TREE_CODE (*node) == POINTER_TYPE);
979 *node = fn_ptr_tmp;
984 return returned_attrs;
987 /* Return TRUE iff ATTR has been parsed by the front-end as a C++-11
988 attribute.
990 When G++ parses a C++11 attribute, it is represented as
991 a TREE_LIST which TREE_PURPOSE is itself a TREE_LIST. TREE_PURPOSE
992 (TREE_PURPOSE (ATTR)) is the namespace of the attribute, and the
993 TREE_VALUE (TREE_PURPOSE (ATTR)) is its non-qualified name. Please
994 use get_attribute_namespace and get_attribute_name to retrieve the
995 namespace and name of the attribute, as these accessors work with
996 GNU attributes as well. */
998 bool
999 cxx11_attribute_p (const_tree attr)
1001 if (attr == NULL_TREE
1002 || TREE_CODE (attr) != TREE_LIST)
1003 return false;
1005 return (TREE_CODE (TREE_PURPOSE (attr)) == TREE_LIST);
1008 /* Return the name of the attribute ATTR. This accessor works on GNU
1009 and C++11 (scoped) attributes.
1011 Please read the comments of cxx11_attribute_p to understand the
1012 format of attributes. */
1014 tree
1015 get_attribute_name (const_tree attr)
1017 if (cxx11_attribute_p (attr))
1018 return TREE_VALUE (TREE_PURPOSE (attr));
1019 return TREE_PURPOSE (attr);
1022 /* Subroutine of set_method_tm_attributes. Apply TM attribute ATTR
1023 to the method FNDECL. */
1025 void
1026 apply_tm_attr (tree fndecl, tree attr)
1028 decl_attributes (&TREE_TYPE (fndecl), tree_cons (attr, NULL, NULL), 0);
1031 /* Makes a function attribute of the form NAME(ARG_NAME) and chains
1032 it to CHAIN. */
1034 tree
1035 make_attribute (const char *name, const char *arg_name, tree chain)
1037 tree attr_name;
1038 tree attr_arg_name;
1039 tree attr_args;
1040 tree attr;
1042 attr_name = get_identifier (name);
1043 attr_arg_name = build_string (strlen (arg_name), arg_name);
1044 attr_args = tree_cons (NULL_TREE, attr_arg_name, NULL_TREE);
1045 attr = tree_cons (attr_name, attr_args, chain);
1046 return attr;
1050 /* Common functions used for target clone support. */
1052 /* Comparator function to be used in qsort routine to sort attribute
1053 specification strings to "target". */
1055 static int
1056 attr_strcmp (const void *v1, const void *v2)
1058 const char *c1 = *(char *const*)v1;
1059 const char *c2 = *(char *const*)v2;
1060 return strcmp (c1, c2);
1063 /* ARGLIST is the argument to target attribute. This function tokenizes
1064 the comma separated arguments, sorts them and returns a string which
1065 is a unique identifier for the comma separated arguments. It also
1066 replaces non-identifier characters "=,-" with "_". */
1068 char *
1069 sorted_attr_string (tree arglist)
1071 tree arg;
1072 size_t str_len_sum = 0;
1073 char **args = NULL;
1074 char *attr_str, *ret_str;
1075 char *attr = NULL;
1076 unsigned int argnum = 1;
1077 unsigned int i;
1079 for (arg = arglist; arg; arg = TREE_CHAIN (arg))
1081 const char *str = TREE_STRING_POINTER (TREE_VALUE (arg));
1082 size_t len = strlen (str);
1083 str_len_sum += len + 1;
1084 if (arg != arglist)
1085 argnum++;
1086 for (i = 0; i < strlen (str); i++)
1087 if (str[i] == ',')
1088 argnum++;
1091 attr_str = XNEWVEC (char, str_len_sum);
1092 str_len_sum = 0;
1093 for (arg = arglist; arg; arg = TREE_CHAIN (arg))
1095 const char *str = TREE_STRING_POINTER (TREE_VALUE (arg));
1096 size_t len = strlen (str);
1097 memcpy (attr_str + str_len_sum, str, len);
1098 attr_str[str_len_sum + len] = TREE_CHAIN (arg) ? ',' : '\0';
1099 str_len_sum += len + 1;
1102 /* Replace "=,-" with "_". */
1103 for (i = 0; i < strlen (attr_str); i++)
1104 if (attr_str[i] == '=' || attr_str[i]== '-')
1105 attr_str[i] = '_';
1107 if (argnum == 1)
1108 return attr_str;
1110 args = XNEWVEC (char *, argnum);
1112 i = 0;
1113 attr = strtok (attr_str, ",");
1114 while (attr != NULL)
1116 args[i] = attr;
1117 i++;
1118 attr = strtok (NULL, ",");
1121 qsort (args, argnum, sizeof (char *), attr_strcmp);
1123 ret_str = XNEWVEC (char, str_len_sum);
1124 str_len_sum = 0;
1125 for (i = 0; i < argnum; i++)
1127 size_t len = strlen (args[i]);
1128 memcpy (ret_str + str_len_sum, args[i], len);
1129 ret_str[str_len_sum + len] = i < argnum - 1 ? '_' : '\0';
1130 str_len_sum += len + 1;
1133 XDELETEVEC (args);
1134 XDELETEVEC (attr_str);
1135 return ret_str;
1139 /* This function returns true if FN1 and FN2 are versions of the same function,
1140 that is, the target strings of the function decls are different. This assumes
1141 that FN1 and FN2 have the same signature. */
1143 bool
1144 common_function_versions (tree fn1, tree fn2)
1146 tree attr1, attr2;
1147 char *target1, *target2;
1148 bool result;
1150 if (TREE_CODE (fn1) != FUNCTION_DECL
1151 || TREE_CODE (fn2) != FUNCTION_DECL)
1152 return false;
1154 attr1 = lookup_attribute ("target", DECL_ATTRIBUTES (fn1));
1155 attr2 = lookup_attribute ("target", DECL_ATTRIBUTES (fn2));
1157 /* At least one function decl should have the target attribute specified. */
1158 if (attr1 == NULL_TREE && attr2 == NULL_TREE)
1159 return false;
1161 /* Diagnose missing target attribute if one of the decls is already
1162 multi-versioned. */
1163 if (attr1 == NULL_TREE || attr2 == NULL_TREE)
1165 if (DECL_FUNCTION_VERSIONED (fn1) || DECL_FUNCTION_VERSIONED (fn2))
1167 if (attr2 != NULL_TREE)
1169 std::swap (fn1, fn2);
1170 attr1 = attr2;
1172 auto_diagnostic_group d;
1173 error_at (DECL_SOURCE_LOCATION (fn2),
1174 "missing %<target%> attribute for multi-versioned %qD",
1175 fn2);
1176 inform (DECL_SOURCE_LOCATION (fn1),
1177 "previous declaration of %qD", fn1);
1178 /* Prevent diagnosing of the same error multiple times. */
1179 DECL_ATTRIBUTES (fn2)
1180 = tree_cons (get_identifier ("target"),
1181 copy_node (TREE_VALUE (attr1)),
1182 DECL_ATTRIBUTES (fn2));
1184 return false;
1187 target1 = sorted_attr_string (TREE_VALUE (attr1));
1188 target2 = sorted_attr_string (TREE_VALUE (attr2));
1190 /* The sorted target strings must be different for fn1 and fn2
1191 to be versions. */
1192 if (strcmp (target1, target2) == 0)
1193 result = false;
1194 else
1195 result = true;
1197 XDELETEVEC (target1);
1198 XDELETEVEC (target2);
1200 return result;
1203 /* Make a dispatcher declaration for the multi-versioned function DECL.
1204 Calls to DECL function will be replaced with calls to the dispatcher
1205 by the front-end. Return the decl created. */
1207 tree
1208 make_dispatcher_decl (const tree decl)
1210 tree func_decl;
1211 char *func_name;
1212 tree fn_type, func_type;
1214 func_name = xstrdup (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
1216 fn_type = TREE_TYPE (decl);
1217 func_type = build_function_type (TREE_TYPE (fn_type),
1218 TYPE_ARG_TYPES (fn_type));
1220 func_decl = build_fn_decl (func_name, func_type);
1221 XDELETEVEC (func_name);
1222 TREE_USED (func_decl) = 1;
1223 DECL_CONTEXT (func_decl) = NULL_TREE;
1224 DECL_INITIAL (func_decl) = error_mark_node;
1225 DECL_ARTIFICIAL (func_decl) = 1;
1226 /* Mark this func as external, the resolver will flip it again if
1227 it gets generated. */
1228 DECL_EXTERNAL (func_decl) = 1;
1229 /* This will be of type IFUNCs have to be externally visible. */
1230 TREE_PUBLIC (func_decl) = 1;
1232 return func_decl;
1235 /* Returns true if decl is multi-versioned and DECL is the default function,
1236 that is it is not tagged with target specific optimization. */
1238 bool
1239 is_function_default_version (const tree decl)
1241 if (TREE_CODE (decl) != FUNCTION_DECL
1242 || !DECL_FUNCTION_VERSIONED (decl))
1243 return false;
1244 tree attr = lookup_attribute ("target", DECL_ATTRIBUTES (decl));
1245 gcc_assert (attr);
1246 attr = TREE_VALUE (TREE_VALUE (attr));
1247 return (TREE_CODE (attr) == STRING_CST
1248 && strcmp (TREE_STRING_POINTER (attr), "default") == 0);
1251 /* Return a declaration like DDECL except that its DECL_ATTRIBUTES
1252 is ATTRIBUTE. */
1254 tree
1255 build_decl_attribute_variant (tree ddecl, tree attribute)
1257 DECL_ATTRIBUTES (ddecl) = attribute;
1258 return ddecl;
1261 /* Return a type like TTYPE except that its TYPE_ATTRIBUTE
1262 is ATTRIBUTE and its qualifiers are QUALS.
1264 Record such modified types already made so we don't make duplicates. */
1266 tree
1267 build_type_attribute_qual_variant (tree otype, tree attribute, int quals)
1269 tree ttype = otype;
1270 if (! attribute_list_equal (TYPE_ATTRIBUTES (ttype), attribute))
1272 tree ntype;
1274 /* Building a distinct copy of a tagged type is inappropriate; it
1275 causes breakage in code that expects there to be a one-to-one
1276 relationship between a struct and its fields.
1277 build_duplicate_type is another solution (as used in
1278 handle_transparent_union_attribute), but that doesn't play well
1279 with the stronger C++ type identity model. */
1280 if (TREE_CODE (ttype) == RECORD_TYPE
1281 || TREE_CODE (ttype) == UNION_TYPE
1282 || TREE_CODE (ttype) == QUAL_UNION_TYPE
1283 || TREE_CODE (ttype) == ENUMERAL_TYPE)
1285 warning (OPT_Wattributes,
1286 "ignoring attributes applied to %qT after definition",
1287 TYPE_MAIN_VARIANT (ttype));
1288 return build_qualified_type (ttype, quals);
1291 ttype = build_qualified_type (ttype, TYPE_UNQUALIFIED);
1292 if (lang_hooks.types.copy_lang_qualifiers
1293 && otype != TYPE_MAIN_VARIANT (otype))
1294 ttype = (lang_hooks.types.copy_lang_qualifiers
1295 (ttype, TYPE_MAIN_VARIANT (otype)));
1297 tree dtype = ntype = build_distinct_type_copy (ttype);
1299 TYPE_ATTRIBUTES (ntype) = attribute;
1301 hashval_t hash = type_hash_canon_hash (ntype);
1302 ntype = type_hash_canon (hash, ntype);
1304 if (ntype != dtype)
1305 /* This variant was already in the hash table, don't mess with
1306 TYPE_CANONICAL. */;
1307 else if (TYPE_STRUCTURAL_EQUALITY_P (ttype)
1308 || !comp_type_attributes (ntype, ttype))
1309 /* If the target-dependent attributes make NTYPE different from
1310 its canonical type, we will need to use structural equality
1311 checks for this type.
1313 We shouldn't get here for stripping attributes from a type;
1314 the no-attribute type might not need structural comparison. But
1315 we can if was discarded from type_hash_table. */
1316 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
1317 else if (TYPE_CANONICAL (ntype) == ntype)
1318 TYPE_CANONICAL (ntype) = TYPE_CANONICAL (ttype);
1320 ttype = build_qualified_type (ntype, quals);
1321 if (lang_hooks.types.copy_lang_qualifiers
1322 && otype != TYPE_MAIN_VARIANT (otype))
1323 ttype = lang_hooks.types.copy_lang_qualifiers (ttype, otype);
1325 else if (TYPE_QUALS (ttype) != quals)
1326 ttype = build_qualified_type (ttype, quals);
1328 return ttype;
1331 /* Compare two identifier nodes representing attributes.
1332 Return true if they are the same, false otherwise. */
1334 static bool
1335 cmp_attrib_identifiers (const_tree attr1, const_tree attr2)
1337 /* Make sure we're dealing with IDENTIFIER_NODEs. */
1338 gcc_checking_assert (TREE_CODE (attr1) == IDENTIFIER_NODE
1339 && TREE_CODE (attr2) == IDENTIFIER_NODE);
1341 /* Identifiers can be compared directly for equality. */
1342 if (attr1 == attr2)
1343 return true;
1345 return cmp_attribs (IDENTIFIER_POINTER (attr1), IDENTIFIER_LENGTH (attr1),
1346 IDENTIFIER_POINTER (attr2), IDENTIFIER_LENGTH (attr2));
1349 /* Compare two constructor-element-type constants. Return 1 if the lists
1350 are known to be equal; otherwise return 0. */
1352 bool
1353 simple_cst_list_equal (const_tree l1, const_tree l2)
1355 while (l1 != NULL_TREE && l2 != NULL_TREE)
1357 if (simple_cst_equal (TREE_VALUE (l1), TREE_VALUE (l2)) != 1)
1358 return false;
1360 l1 = TREE_CHAIN (l1);
1361 l2 = TREE_CHAIN (l2);
1364 return l1 == l2;
1367 /* Check if "omp declare simd" attribute arguments, CLAUSES1 and CLAUSES2, are
1368 the same. */
1370 static bool
1371 omp_declare_simd_clauses_equal (tree clauses1, tree clauses2)
1373 tree cl1, cl2;
1374 for (cl1 = clauses1, cl2 = clauses2;
1375 cl1 && cl2;
1376 cl1 = OMP_CLAUSE_CHAIN (cl1), cl2 = OMP_CLAUSE_CHAIN (cl2))
1378 if (OMP_CLAUSE_CODE (cl1) != OMP_CLAUSE_CODE (cl2))
1379 return false;
1380 if (OMP_CLAUSE_CODE (cl1) != OMP_CLAUSE_SIMDLEN)
1382 if (simple_cst_equal (OMP_CLAUSE_DECL (cl1),
1383 OMP_CLAUSE_DECL (cl2)) != 1)
1384 return false;
1386 switch (OMP_CLAUSE_CODE (cl1))
1388 case OMP_CLAUSE_ALIGNED:
1389 if (simple_cst_equal (OMP_CLAUSE_ALIGNED_ALIGNMENT (cl1),
1390 OMP_CLAUSE_ALIGNED_ALIGNMENT (cl2)) != 1)
1391 return false;
1392 break;
1393 case OMP_CLAUSE_LINEAR:
1394 if (simple_cst_equal (OMP_CLAUSE_LINEAR_STEP (cl1),
1395 OMP_CLAUSE_LINEAR_STEP (cl2)) != 1)
1396 return false;
1397 break;
1398 case OMP_CLAUSE_SIMDLEN:
1399 if (simple_cst_equal (OMP_CLAUSE_SIMDLEN_EXPR (cl1),
1400 OMP_CLAUSE_SIMDLEN_EXPR (cl2)) != 1)
1401 return false;
1402 default:
1403 break;
1406 return true;
1410 /* Compare two attributes for their value identity. Return true if the
1411 attribute values are known to be equal; otherwise return false. */
1413 bool
1414 attribute_value_equal (const_tree attr1, const_tree attr2)
1416 if (TREE_VALUE (attr1) == TREE_VALUE (attr2))
1417 return true;
1419 if (TREE_VALUE (attr1) != NULL_TREE
1420 && TREE_CODE (TREE_VALUE (attr1)) == TREE_LIST
1421 && TREE_VALUE (attr2) != NULL_TREE
1422 && TREE_CODE (TREE_VALUE (attr2)) == TREE_LIST)
1424 /* Handle attribute format. */
1425 if (is_attribute_p ("format", get_attribute_name (attr1)))
1427 attr1 = TREE_VALUE (attr1);
1428 attr2 = TREE_VALUE (attr2);
1429 /* Compare the archetypes (printf/scanf/strftime/...). */
1430 if (!cmp_attrib_identifiers (TREE_VALUE (attr1), TREE_VALUE (attr2)))
1431 return false;
1432 /* Archetypes are the same. Compare the rest. */
1433 return (simple_cst_list_equal (TREE_CHAIN (attr1),
1434 TREE_CHAIN (attr2)) == 1);
1436 return (simple_cst_list_equal (TREE_VALUE (attr1),
1437 TREE_VALUE (attr2)) == 1);
1440 if (TREE_VALUE (attr1)
1441 && TREE_CODE (TREE_VALUE (attr1)) == OMP_CLAUSE
1442 && TREE_VALUE (attr2)
1443 && TREE_CODE (TREE_VALUE (attr2)) == OMP_CLAUSE)
1444 return omp_declare_simd_clauses_equal (TREE_VALUE (attr1),
1445 TREE_VALUE (attr2));
1447 return (simple_cst_equal (TREE_VALUE (attr1), TREE_VALUE (attr2)) == 1);
1450 /* Return 0 if the attributes for two types are incompatible, 1 if they
1451 are compatible, and 2 if they are nearly compatible (which causes a
1452 warning to be generated). */
1454 comp_type_attributes (const_tree type1, const_tree type2)
1456 const_tree a1 = TYPE_ATTRIBUTES (type1);
1457 const_tree a2 = TYPE_ATTRIBUTES (type2);
1458 const_tree a;
1460 if (a1 == a2)
1461 return 1;
1462 for (a = a1; a != NULL_TREE; a = TREE_CHAIN (a))
1464 const struct attribute_spec *as;
1465 const_tree attr;
1467 as = lookup_attribute_spec (get_attribute_name (a));
1468 if (!as || as->affects_type_identity == false)
1469 continue;
1471 attr = lookup_attribute (as->name, CONST_CAST_TREE (a2));
1472 if (!attr || !attribute_value_equal (a, attr))
1473 break;
1475 if (!a)
1477 for (a = a2; a != NULL_TREE; a = TREE_CHAIN (a))
1479 const struct attribute_spec *as;
1481 as = lookup_attribute_spec (get_attribute_name (a));
1482 if (!as || as->affects_type_identity == false)
1483 continue;
1485 if (!lookup_attribute (as->name, CONST_CAST_TREE (a1)))
1486 break;
1487 /* We don't need to compare trees again, as we did this
1488 already in first loop. */
1490 /* All types - affecting identity - are equal, so
1491 there is no need to call target hook for comparison. */
1492 if (!a)
1493 return 1;
1495 if (lookup_attribute ("transaction_safe", CONST_CAST_TREE (a)))
1496 return 0;
1497 if ((lookup_attribute ("nocf_check", TYPE_ATTRIBUTES (type1)) != NULL)
1498 ^ (lookup_attribute ("nocf_check", TYPE_ATTRIBUTES (type2)) != NULL))
1499 return 0;
1500 /* As some type combinations - like default calling-convention - might
1501 be compatible, we have to call the target hook to get the final result. */
1502 return targetm.comp_type_attributes (type1, type2);
1505 /* PREDICATE acts as a function of type:
1507 (const_tree attr, const attribute_spec *as) -> bool
1509 where ATTR is an attribute and AS is its possibly-null specification.
1510 Return a list of every attribute in attribute list ATTRS for which
1511 PREDICATE is true. Return ATTRS itself if PREDICATE returns true
1512 for every attribute. */
1514 template<typename Predicate>
1515 tree
1516 remove_attributes_matching (tree attrs, Predicate predicate)
1518 tree new_attrs = NULL_TREE;
1519 tree *ptr = &new_attrs;
1520 const_tree start = attrs;
1521 for (const_tree attr = attrs; attr; attr = TREE_CHAIN (attr))
1523 tree name = get_attribute_name (attr);
1524 const attribute_spec *as = lookup_attribute_spec (name);
1525 const_tree end;
1526 if (!predicate (attr, as))
1527 end = attr;
1528 else if (start == attrs)
1529 continue;
1530 else
1531 end = TREE_CHAIN (attr);
1533 for (; start != end; start = TREE_CHAIN (start))
1535 *ptr = tree_cons (TREE_PURPOSE (start),
1536 TREE_VALUE (start), NULL_TREE);
1537 TREE_CHAIN (*ptr) = NULL_TREE;
1538 ptr = &TREE_CHAIN (*ptr);
1540 start = TREE_CHAIN (attr);
1542 gcc_assert (!start || start == attrs);
1543 return start ? attrs : new_attrs;
1546 /* If VALUE is true, return the subset of ATTRS that affect type identity,
1547 otherwise return the subset of ATTRS that don't affect type identity. */
1549 tree
1550 affects_type_identity_attributes (tree attrs, bool value)
1552 auto predicate = [value](const_tree, const attribute_spec *as) -> bool
1554 return bool (as && as->affects_type_identity) == value;
1556 return remove_attributes_matching (attrs, predicate);
1559 /* Remove attributes that affect type identity from ATTRS unless the
1560 same attributes occur in OK_ATTRS. */
1562 tree
1563 restrict_type_identity_attributes_to (tree attrs, tree ok_attrs)
1565 auto predicate = [ok_attrs](const_tree attr,
1566 const attribute_spec *as) -> bool
1568 if (!as || !as->affects_type_identity)
1569 return true;
1571 for (tree ok_attr = lookup_attribute (as->name, ok_attrs);
1572 ok_attr;
1573 ok_attr = lookup_attribute (as->name, TREE_CHAIN (ok_attr)))
1574 if (simple_cst_equal (TREE_VALUE (ok_attr), TREE_VALUE (attr)) == 1)
1575 return true;
1577 return false;
1579 return remove_attributes_matching (attrs, predicate);
1582 /* Return a type like TTYPE except that its TYPE_ATTRIBUTE
1583 is ATTRIBUTE.
1585 Record such modified types already made so we don't make duplicates. */
1587 tree
1588 build_type_attribute_variant (tree ttype, tree attribute)
1590 return build_type_attribute_qual_variant (ttype, attribute,
1591 TYPE_QUALS (ttype));
1594 /* A variant of lookup_attribute() that can be used with an identifier
1595 as the first argument, and where the identifier can be either
1596 'text' or '__text__'.
1598 Given an attribute ATTR_IDENTIFIER, and a list of attributes LIST,
1599 return a pointer to the attribute's list element if the attribute
1600 is part of the list, or NULL_TREE if not found. If the attribute
1601 appears more than once, this only returns the first occurrence; the
1602 TREE_CHAIN of the return value should be passed back in if further
1603 occurrences are wanted. ATTR_IDENTIFIER must be an identifier but
1604 can be in the form 'text' or '__text__'. */
1605 static tree
1606 lookup_ident_attribute (tree attr_identifier, tree list)
1608 gcc_checking_assert (TREE_CODE (attr_identifier) == IDENTIFIER_NODE);
1610 while (list)
1612 gcc_checking_assert (TREE_CODE (get_attribute_name (list))
1613 == IDENTIFIER_NODE);
1615 if (cmp_attrib_identifiers (attr_identifier,
1616 get_attribute_name (list)))
1617 /* Found it. */
1618 break;
1619 list = TREE_CHAIN (list);
1622 return list;
1625 /* Remove any instances of attribute ATTR_NAME in LIST and return the
1626 modified list. */
1628 tree
1629 remove_attribute (const char *attr_name, tree list)
1631 tree *p;
1632 gcc_checking_assert (attr_name[0] != '_');
1634 for (p = &list; *p;)
1636 tree l = *p;
1638 tree attr = get_attribute_name (l);
1639 if (is_attribute_p (attr_name, attr))
1640 *p = TREE_CHAIN (l);
1641 else
1642 p = &TREE_CHAIN (l);
1645 return list;
1648 /* Similarly but also match namespace on the removed attributes.
1649 ATTR_NS "" stands for NULL or "gnu" namespace. */
1651 tree
1652 remove_attribute (const char *attr_ns, const char *attr_name, tree list)
1654 tree *p;
1655 gcc_checking_assert (attr_name[0] != '_');
1656 gcc_checking_assert (attr_ns == NULL || attr_ns[0] != '_');
1658 for (p = &list; *p;)
1660 tree l = *p;
1662 tree attr = get_attribute_name (l);
1663 if (is_attribute_p (attr_name, attr)
1664 && is_attribute_namespace_p (attr_ns, l))
1666 *p = TREE_CHAIN (l);
1667 continue;
1669 p = &TREE_CHAIN (l);
1672 return list;
1675 /* Return an attribute list that is the union of a1 and a2. */
1677 tree
1678 merge_attributes (tree a1, tree a2)
1680 tree attributes;
1682 /* Either one unset? Take the set one. */
1684 if ((attributes = a1) == 0)
1685 attributes = a2;
1687 /* One that completely contains the other? Take it. */
1689 else if (a2 != 0 && ! attribute_list_contained (a1, a2))
1691 if (attribute_list_contained (a2, a1))
1692 attributes = a2;
1693 else
1695 /* Pick the longest list, and hang on the other list. */
1697 if (list_length (a1) < list_length (a2))
1698 attributes = a2, a2 = a1;
1700 for (; a2 != 0; a2 = TREE_CHAIN (a2))
1702 tree a;
1703 for (a = lookup_ident_attribute (get_attribute_name (a2),
1704 attributes);
1705 a != NULL_TREE && !attribute_value_equal (a, a2);
1706 a = lookup_ident_attribute (get_attribute_name (a2),
1707 TREE_CHAIN (a)))
1709 if (a == NULL_TREE)
1711 a1 = copy_node (a2);
1712 TREE_CHAIN (a1) = attributes;
1713 attributes = a1;
1718 return attributes;
1721 /* Given types T1 and T2, merge their attributes and return
1722 the result. */
1724 tree
1725 merge_type_attributes (tree t1, tree t2)
1727 return merge_attributes (TYPE_ATTRIBUTES (t1),
1728 TYPE_ATTRIBUTES (t2));
1731 /* Given decls OLDDECL and NEWDECL, merge their attributes and return
1732 the result. */
1734 tree
1735 merge_decl_attributes (tree olddecl, tree newdecl)
1737 return merge_attributes (DECL_ATTRIBUTES (olddecl),
1738 DECL_ATTRIBUTES (newdecl));
1741 /* Duplicate all attributes with name NAME in ATTR list to *ATTRS if
1742 they are missing there. */
1744 void
1745 duplicate_one_attribute (tree *attrs, tree attr, const char *name)
1747 attr = lookup_attribute (name, attr);
1748 if (!attr)
1749 return;
1750 tree a = lookup_attribute (name, *attrs);
1751 while (attr)
1753 tree a2;
1754 for (a2 = a; a2; a2 = lookup_attribute (name, TREE_CHAIN (a2)))
1755 if (attribute_value_equal (attr, a2))
1756 break;
1757 if (!a2)
1759 a2 = copy_node (attr);
1760 TREE_CHAIN (a2) = *attrs;
1761 *attrs = a2;
1763 attr = lookup_attribute (name, TREE_CHAIN (attr));
1767 /* Duplicate all attributes from user DECL to the corresponding
1768 builtin that should be propagated. */
1770 void
1771 copy_attributes_to_builtin (tree decl)
1773 tree b = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
1774 if (b)
1775 duplicate_one_attribute (&DECL_ATTRIBUTES (b),
1776 DECL_ATTRIBUTES (decl), "omp declare simd");
1779 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1781 /* Specialization of merge_decl_attributes for various Windows targets.
1783 This handles the following situation:
1785 __declspec (dllimport) int foo;
1786 int foo;
1788 The second instance of `foo' nullifies the dllimport. */
1790 tree
1791 merge_dllimport_decl_attributes (tree old, tree new_tree)
1793 tree a;
1794 int delete_dllimport_p = 1;
1796 /* What we need to do here is remove from `old' dllimport if it doesn't
1797 appear in `new'. dllimport behaves like extern: if a declaration is
1798 marked dllimport and a definition appears later, then the object
1799 is not dllimport'd. We also remove a `new' dllimport if the old list
1800 contains dllexport: dllexport always overrides dllimport, regardless
1801 of the order of declaration. */
1802 if (!VAR_OR_FUNCTION_DECL_P (new_tree))
1803 delete_dllimport_p = 0;
1804 else if (DECL_DLLIMPORT_P (new_tree)
1805 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (old)))
1807 DECL_DLLIMPORT_P (new_tree) = 0;
1808 warning (OPT_Wattributes, "%q+D already declared with dllexport "
1809 "attribute: dllimport ignored", new_tree);
1811 else if (DECL_DLLIMPORT_P (old) && !DECL_DLLIMPORT_P (new_tree))
1813 /* Warn about overriding a symbol that has already been used, e.g.:
1814 extern int __attribute__ ((dllimport)) foo;
1815 int* bar () {return &foo;}
1816 int foo;
1818 if (TREE_USED (old))
1820 warning (0, "%q+D redeclared without dllimport attribute "
1821 "after being referenced with dll linkage", new_tree);
1822 /* If we have used a variable's address with dllimport linkage,
1823 keep the old DECL_DLLIMPORT_P flag: the ADDR_EXPR using the
1824 decl may already have had TREE_CONSTANT computed.
1825 We still remove the attribute so that assembler code refers
1826 to '&foo rather than '_imp__foo'. */
1827 if (VAR_P (old) && TREE_ADDRESSABLE (old))
1828 DECL_DLLIMPORT_P (new_tree) = 1;
1831 /* Let an inline definition silently override the external reference,
1832 but otherwise warn about attribute inconsistency. */
1833 else if (VAR_P (new_tree) || !DECL_DECLARED_INLINE_P (new_tree))
1834 warning (OPT_Wattributes, "%q+D redeclared without dllimport "
1835 "attribute: previous dllimport ignored", new_tree);
1837 else
1838 delete_dllimport_p = 0;
1840 a = merge_attributes (DECL_ATTRIBUTES (old), DECL_ATTRIBUTES (new_tree));
1842 if (delete_dllimport_p)
1843 a = remove_attribute ("dllimport", a);
1845 return a;
1848 /* Handle a "dllimport" or "dllexport" attribute; arguments as in
1849 struct attribute_spec.handler. */
1851 tree
1852 handle_dll_attribute (tree * pnode, tree name, tree args, int flags,
1853 bool *no_add_attrs)
1855 tree node = *pnode;
1856 bool is_dllimport;
1858 /* These attributes may apply to structure and union types being created,
1859 but otherwise should pass to the declaration involved. */
1860 if (!DECL_P (node))
1862 if (flags & ((int) ATTR_FLAG_DECL_NEXT | (int) ATTR_FLAG_FUNCTION_NEXT
1863 | (int) ATTR_FLAG_ARRAY_NEXT))
1865 *no_add_attrs = true;
1866 return tree_cons (name, args, NULL_TREE);
1868 if (TREE_CODE (node) == RECORD_TYPE
1869 || TREE_CODE (node) == UNION_TYPE)
1871 node = TYPE_NAME (node);
1872 if (!node)
1873 return NULL_TREE;
1875 else
1877 warning (OPT_Wattributes, "%qE attribute ignored",
1878 name);
1879 *no_add_attrs = true;
1880 return NULL_TREE;
1884 if (!VAR_OR_FUNCTION_DECL_P (node) && TREE_CODE (node) != TYPE_DECL)
1886 *no_add_attrs = true;
1887 warning (OPT_Wattributes, "%qE attribute ignored",
1888 name);
1889 return NULL_TREE;
1892 if (TREE_CODE (node) == TYPE_DECL
1893 && TREE_CODE (TREE_TYPE (node)) != RECORD_TYPE
1894 && TREE_CODE (TREE_TYPE (node)) != UNION_TYPE)
1896 *no_add_attrs = true;
1897 warning (OPT_Wattributes, "%qE attribute ignored",
1898 name);
1899 return NULL_TREE;
1902 is_dllimport = is_attribute_p ("dllimport", name);
1904 /* Report error on dllimport ambiguities seen now before they cause
1905 any damage. */
1906 if (is_dllimport)
1908 /* Honor any target-specific overrides. */
1909 if (!targetm.valid_dllimport_attribute_p (node))
1910 *no_add_attrs = true;
1912 else if (TREE_CODE (node) == FUNCTION_DECL
1913 && DECL_DECLARED_INLINE_P (node))
1915 warning (OPT_Wattributes, "inline function %q+D declared as "
1916 "dllimport: attribute ignored", node);
1917 *no_add_attrs = true;
1919 /* Like MS, treat definition of dllimported variables and
1920 non-inlined functions on declaration as syntax errors. */
1921 else if (TREE_CODE (node) == FUNCTION_DECL && DECL_INITIAL (node))
1923 error ("function %q+D definition is marked dllimport", node);
1924 *no_add_attrs = true;
1927 else if (VAR_P (node))
1929 if (DECL_INITIAL (node))
1931 error ("variable %q+D definition is marked dllimport",
1932 node);
1933 *no_add_attrs = true;
1936 /* `extern' needn't be specified with dllimport.
1937 Specify `extern' now and hope for the best. Sigh. */
1938 DECL_EXTERNAL (node) = 1;
1939 /* Also, implicitly give dllimport'd variables declared within
1940 a function global scope, unless declared static. */
1941 if (current_function_decl != NULL_TREE && !TREE_STATIC (node))
1942 TREE_PUBLIC (node) = 1;
1943 /* Clear TREE_STATIC because DECL_EXTERNAL is set, unless
1944 it is a C++ static data member. */
1945 if (DECL_CONTEXT (node) == NULL_TREE
1946 || !RECORD_OR_UNION_TYPE_P (DECL_CONTEXT (node)))
1947 TREE_STATIC (node) = 0;
1950 if (*no_add_attrs == false)
1951 DECL_DLLIMPORT_P (node) = 1;
1953 else if (TREE_CODE (node) == FUNCTION_DECL
1954 && DECL_DECLARED_INLINE_P (node)
1955 && flag_keep_inline_dllexport)
1956 /* An exported function, even if inline, must be emitted. */
1957 DECL_EXTERNAL (node) = 0;
1959 /* Report error if symbol is not accessible at global scope. */
1960 if (!TREE_PUBLIC (node) && VAR_OR_FUNCTION_DECL_P (node))
1962 error ("external linkage required for symbol %q+D because of "
1963 "%qE attribute", node, name);
1964 *no_add_attrs = true;
1967 /* A dllexport'd entity must have default visibility so that other
1968 program units (shared libraries or the main executable) can see
1969 it. A dllimport'd entity must have default visibility so that
1970 the linker knows that undefined references within this program
1971 unit can be resolved by the dynamic linker. */
1972 if (!*no_add_attrs)
1974 if (DECL_VISIBILITY_SPECIFIED (node)
1975 && DECL_VISIBILITY (node) != VISIBILITY_DEFAULT)
1976 error ("%qE implies default visibility, but %qD has already "
1977 "been declared with a different visibility",
1978 name, node);
1979 DECL_VISIBILITY (node) = VISIBILITY_DEFAULT;
1980 DECL_VISIBILITY_SPECIFIED (node) = 1;
1983 return NULL_TREE;
1986 #endif /* TARGET_DLLIMPORT_DECL_ATTRIBUTES */
1988 /* Given two lists of attributes, return true if list l2 is
1989 equivalent to l1. */
1992 attribute_list_equal (const_tree l1, const_tree l2)
1994 if (l1 == l2)
1995 return 1;
1997 return attribute_list_contained (l1, l2)
1998 && attribute_list_contained (l2, l1);
2001 /* Given two lists of attributes, return true if list L2 is
2002 completely contained within L1. */
2003 /* ??? This would be faster if attribute names were stored in a canonicalized
2004 form. Otherwise, if L1 uses `foo' and L2 uses `__foo__', the long method
2005 must be used to show these elements are equivalent (which they are). */
2006 /* ??? It's not clear that attributes with arguments will always be handled
2007 correctly. */
2010 attribute_list_contained (const_tree l1, const_tree l2)
2012 const_tree t1, t2;
2014 /* First check the obvious, maybe the lists are identical. */
2015 if (l1 == l2)
2016 return 1;
2018 /* Maybe the lists are similar. */
2019 for (t1 = l1, t2 = l2;
2020 t1 != 0 && t2 != 0
2021 && get_attribute_name (t1) == get_attribute_name (t2)
2022 && TREE_VALUE (t1) == TREE_VALUE (t2);
2023 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
2026 /* Maybe the lists are equal. */
2027 if (t1 == 0 && t2 == 0)
2028 return 1;
2030 for (; t2 != 0; t2 = TREE_CHAIN (t2))
2032 const_tree attr;
2033 /* This CONST_CAST is okay because lookup_attribute does not
2034 modify its argument and the return value is assigned to a
2035 const_tree. */
2036 for (attr = lookup_ident_attribute (get_attribute_name (t2),
2037 CONST_CAST_TREE (l1));
2038 attr != NULL_TREE && !attribute_value_equal (t2, attr);
2039 attr = lookup_ident_attribute (get_attribute_name (t2),
2040 TREE_CHAIN (attr)))
2043 if (attr == NULL_TREE)
2044 return 0;
2047 return 1;
2050 /* The backbone of lookup_attribute(). ATTR_LEN is the string length
2051 of ATTR_NAME, and LIST is not NULL_TREE.
2053 The function is called from lookup_attribute in order to optimize
2054 for size. */
2056 tree
2057 private_lookup_attribute (const char *attr_name, size_t attr_len, tree list)
2059 while (list)
2061 tree attr = get_attribute_name (list);
2062 size_t ident_len = IDENTIFIER_LENGTH (attr);
2063 if (cmp_attribs (attr_name, attr_len, IDENTIFIER_POINTER (attr),
2064 ident_len))
2065 break;
2066 list = TREE_CHAIN (list);
2069 return list;
2072 /* Similarly but with also attribute namespace. */
2074 tree
2075 private_lookup_attribute (const char *attr_ns, const char *attr_name,
2076 size_t attr_ns_len, size_t attr_len, tree list)
2078 while (list)
2080 tree attr = get_attribute_name (list);
2081 size_t ident_len = IDENTIFIER_LENGTH (attr);
2082 if (cmp_attribs (attr_name, attr_len, IDENTIFIER_POINTER (attr),
2083 ident_len))
2085 tree ns = get_attribute_namespace (list);
2086 if (ns == NULL_TREE)
2088 if (attr_ns_len == 0)
2089 break;
2091 else if (attr_ns)
2093 ident_len = IDENTIFIER_LENGTH (ns);
2094 if (attr_ns_len == 0)
2096 if (cmp_attribs ("gnu", strlen ("gnu"),
2097 IDENTIFIER_POINTER (ns), ident_len))
2098 break;
2100 else if (cmp_attribs (attr_ns, attr_ns_len,
2101 IDENTIFIER_POINTER (ns), ident_len))
2102 break;
2105 list = TREE_CHAIN (list);
2108 return list;
2111 /* Return true if the function decl or type NODE has been declared
2112 with attribute ANAME among attributes ATTRS. */
2114 static bool
2115 has_attribute (tree node, tree attrs, const char *aname)
2117 if (!strcmp (aname, "const"))
2119 if (DECL_P (node) && TREE_READONLY (node))
2120 return true;
2122 else if (!strcmp (aname, "malloc"))
2124 if (DECL_P (node) && DECL_IS_MALLOC (node))
2125 return true;
2127 else if (!strcmp (aname, "noreturn"))
2129 if (DECL_P (node) && TREE_THIS_VOLATILE (node))
2130 return true;
2132 else if (!strcmp (aname, "nothrow"))
2134 if (TREE_NOTHROW (node))
2135 return true;
2137 else if (!strcmp (aname, "pure"))
2139 if (DECL_P (node) && DECL_PURE_P (node))
2140 return true;
2143 return lookup_attribute (aname, attrs);
2146 /* Return the number of mismatched function or type attributes between
2147 the "template" function declaration TMPL and DECL. The word "template"
2148 doesn't necessarily refer to a C++ template but rather a declaration
2149 whose attributes should be matched by those on DECL. For a non-zero
2150 return value set *ATTRSTR to a string representation of the list of
2151 mismatched attributes with quoted names.
2152 ATTRLIST is a list of additional attributes that SPEC should be
2153 taken to ultimately be declared with. */
2155 unsigned
2156 decls_mismatched_attributes (tree tmpl, tree decl, tree attrlist,
2157 const char* const blacklist[],
2158 pretty_printer *attrstr)
2160 if (TREE_CODE (tmpl) != FUNCTION_DECL)
2161 return 0;
2163 /* Avoid warning if either declaration or its type is deprecated. */
2164 if (TREE_DEPRECATED (tmpl)
2165 || TREE_DEPRECATED (decl))
2166 return 0;
2168 const tree tmpls[] = { tmpl, TREE_TYPE (tmpl) };
2169 const tree decls[] = { decl, TREE_TYPE (decl) };
2171 if (TREE_DEPRECATED (tmpls[1])
2172 || TREE_DEPRECATED (decls[1])
2173 || TREE_DEPRECATED (TREE_TYPE (tmpls[1]))
2174 || TREE_DEPRECATED (TREE_TYPE (decls[1])))
2175 return 0;
2177 tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpls[1]) };
2178 tree decl_attrs[] = { DECL_ATTRIBUTES (decl), TYPE_ATTRIBUTES (decls[1]) };
2180 if (!decl_attrs[0])
2181 decl_attrs[0] = attrlist;
2182 else if (!decl_attrs[1])
2183 decl_attrs[1] = attrlist;
2185 /* Avoid warning if the template has no attributes. */
2186 if (!tmpl_attrs[0] && !tmpl_attrs[1])
2187 return 0;
2189 /* Avoid warning if either declaration contains an attribute on
2190 the white list below. */
2191 const char* const whitelist[] = {
2192 "error", "warning"
2195 for (unsigned i = 0; i != 2; ++i)
2196 for (unsigned j = 0; j != ARRAY_SIZE (whitelist); ++j)
2197 if (lookup_attribute (whitelist[j], tmpl_attrs[i])
2198 || lookup_attribute (whitelist[j], decl_attrs[i]))
2199 return 0;
2201 /* Put together a list of the black-listed attributes that the template
2202 is declared with and the declaration is not, in case it's not apparent
2203 from the most recent declaration of the template. */
2204 unsigned nattrs = 0;
2206 for (unsigned i = 0; blacklist[i]; ++i)
2208 /* Attribute leaf only applies to extern functions. Avoid mentioning
2209 it when it's missing from a static declaration. */
2210 if (!TREE_PUBLIC (decl)
2211 && !strcmp ("leaf", blacklist[i]))
2212 continue;
2214 for (unsigned j = 0; j != 2; ++j)
2216 if (!has_attribute (tmpls[j], tmpl_attrs[j], blacklist[i]))
2217 continue;
2219 bool found = false;
2220 unsigned kmax = 1 + !!decl_attrs[1];
2221 for (unsigned k = 0; k != kmax; ++k)
2223 if (has_attribute (decls[k], decl_attrs[k], blacklist[i]))
2225 found = true;
2226 break;
2230 if (!found)
2232 if (nattrs)
2233 pp_string (attrstr, ", ");
2234 pp_begin_quote (attrstr, pp_show_color (global_dc->printer));
2235 pp_string (attrstr, blacklist[i]);
2236 pp_end_quote (attrstr, pp_show_color (global_dc->printer));
2237 ++nattrs;
2240 break;
2244 return nattrs;
2247 /* Issue a warning for the declaration ALIAS for TARGET where ALIAS
2248 specifies either attributes that are incompatible with those of
2249 TARGET, or attributes that are missing and that declaring ALIAS
2250 with would benefit. */
2252 void
2253 maybe_diag_alias_attributes (tree alias, tree target)
2255 /* Do not expect attributes to match between aliases and ifunc
2256 resolvers. There is no obvious correspondence between them. */
2257 if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (alias)))
2258 return;
2260 const char* const blacklist[] = {
2261 "alloc_align", "alloc_size", "cold", "const", "hot", "leaf", "malloc",
2262 "nonnull", "noreturn", "nothrow", "pure", "returns_nonnull",
2263 "returns_twice", NULL
2266 pretty_printer attrnames;
2267 if (warn_attribute_alias > 1)
2269 /* With -Wattribute-alias=2 detect alias declarations that are more
2270 restrictive than their targets first. Those indicate potential
2271 codegen bugs. */
2272 if (unsigned n = decls_mismatched_attributes (alias, target, NULL_TREE,
2273 blacklist, &attrnames))
2275 auto_diagnostic_group d;
2276 if (warning_n (DECL_SOURCE_LOCATION (alias),
2277 OPT_Wattribute_alias_, n,
2278 "%qD specifies more restrictive attribute than "
2279 "its target %qD: %s",
2280 "%qD specifies more restrictive attributes than "
2281 "its target %qD: %s",
2282 alias, target, pp_formatted_text (&attrnames)))
2283 inform (DECL_SOURCE_LOCATION (target),
2284 "%qD target declared here", alias);
2285 return;
2289 /* Detect alias declarations that are less restrictive than their
2290 targets. Those suggest potential optimization opportunities
2291 (solved by adding the missing attribute(s) to the alias). */
2292 if (unsigned n = decls_mismatched_attributes (target, alias, NULL_TREE,
2293 blacklist, &attrnames))
2295 auto_diagnostic_group d;
2296 if (warning_n (DECL_SOURCE_LOCATION (alias),
2297 OPT_Wmissing_attributes, n,
2298 "%qD specifies less restrictive attribute than "
2299 "its target %qD: %s",
2300 "%qD specifies less restrictive attributes than "
2301 "its target %qD: %s",
2302 alias, target, pp_formatted_text (&attrnames)))
2303 inform (DECL_SOURCE_LOCATION (target),
2304 "%qD target declared here", alias);
2308 /* Initialize a mapping RWM for a call to a function declared with
2309 attribute access in ATTRS. Each attribute positional operand
2310 inserts one entry into the mapping with the operand number as
2311 the key. */
2313 void
2314 init_attr_rdwr_indices (rdwr_map *rwm, tree attrs)
2316 if (!attrs)
2317 return;
2319 for (tree access = attrs;
2320 (access = lookup_attribute ("access", access));
2321 access = TREE_CHAIN (access))
2323 /* The TREE_VALUE of an attribute is a TREE_LIST whose TREE_VALUE
2324 is the attribute argument's value. */
2325 tree mode = TREE_VALUE (access);
2326 if (!mode)
2327 return;
2329 /* The (optional) list of VLA bounds. */
2330 tree vblist = TREE_CHAIN (mode);
2331 mode = TREE_VALUE (mode);
2332 if (TREE_CODE (mode) != STRING_CST)
2333 continue;
2334 gcc_assert (TREE_CODE (mode) == STRING_CST);
2336 if (vblist)
2337 vblist = nreverse (copy_list (TREE_VALUE (vblist)));
2339 for (const char *m = TREE_STRING_POINTER (mode); *m; )
2341 attr_access acc = { };
2343 /* Skip the internal-only plus sign. */
2344 if (*m == '+')
2345 ++m;
2347 acc.str = m;
2348 acc.mode = acc.from_mode_char (*m);
2349 acc.sizarg = UINT_MAX;
2351 const char *end;
2352 acc.ptrarg = strtoul (++m, const_cast<char**>(&end), 10);
2353 m = end;
2355 if (*m == '[')
2357 /* Forms containing the square bracket are internal-only
2358 (not specified by an attribute declaration), and used
2359 for various forms of array and VLA parameters. */
2360 acc.internal_p = true;
2362 /* Search to the closing bracket and look at the preceding
2363 code: it determines the form of the most significant
2364 bound of the array. Others prior to it encode the form
2365 of interior VLA bounds. They're not of interest here. */
2366 end = strchr (m, ']');
2367 const char *p = end;
2368 gcc_assert (p);
2370 while (ISDIGIT (p[-1]))
2371 --p;
2373 if (ISDIGIT (*p))
2375 /* A digit denotes a constant bound (as in T[3]). */
2376 acc.static_p = p[-1] == 's';
2377 acc.minsize = strtoull (p, NULL, 10);
2379 else if (' ' == p[-1])
2381 /* A space denotes an ordinary array of unspecified bound
2382 (as in T[]). */
2383 acc.minsize = 0;
2385 else if ('*' == p[-1] || '$' == p[-1])
2387 /* An asterisk denotes a VLA. When the closing bracket
2388 is followed by a comma and a dollar sign its bound is
2389 on the list. Otherwise it's a VLA with an unspecified
2390 bound. */
2391 acc.static_p = p[-2] == 's';
2392 acc.minsize = HOST_WIDE_INT_M1U;
2395 m = end + 1;
2398 if (*m == ',')
2400 ++m;
2403 if (*m == '$')
2405 ++m;
2406 if (!acc.size && vblist)
2408 /* Extract the list of VLA bounds for the current
2409 parameter, store it in ACC.SIZE, and advance
2410 to the list of bounds for the next VLA parameter.
2412 acc.size = TREE_VALUE (vblist);
2413 vblist = TREE_CHAIN (vblist);
2417 if (ISDIGIT (*m))
2419 /* Extract the positional argument. It's absent
2420 for VLAs whose bound doesn't name a function
2421 parameter. */
2422 unsigned pos = strtoul (m, const_cast<char**>(&end), 10);
2423 if (acc.sizarg == UINT_MAX)
2424 acc.sizarg = pos;
2425 m = end;
2428 while (*m == '$');
2431 acc.end = m;
2433 bool existing;
2434 auto &ref = rwm->get_or_insert (acc.ptrarg, &existing);
2435 if (existing)
2437 /* Merge the new spec with the existing. */
2438 if (acc.minsize == HOST_WIDE_INT_M1U)
2439 ref.minsize = HOST_WIDE_INT_M1U;
2441 if (acc.sizarg != UINT_MAX)
2442 ref.sizarg = acc.sizarg;
2444 if (acc.mode)
2445 ref.mode = acc.mode;
2447 else
2448 ref = acc;
2450 /* Unconditionally add an entry for the required pointer
2451 operand of the attribute, and one for the optional size
2452 operand when it's specified. */
2453 if (acc.sizarg != UINT_MAX)
2454 rwm->put (acc.sizarg, acc);
2459 /* Get the LEVEL of the strict_flex_array for the ARRAY_FIELD based on the
2460 values of attribute strict_flex_array and the flag_strict_flex_arrays. */
2461 unsigned int
2462 strict_flex_array_level_of (tree array_field)
2464 gcc_assert (TREE_CODE (array_field) == FIELD_DECL);
2465 unsigned int strict_flex_array_level = flag_strict_flex_arrays;
2467 tree attr_strict_flex_array
2468 = lookup_attribute ("strict_flex_array", DECL_ATTRIBUTES (array_field));
2469 /* If there is a strict_flex_array attribute attached to the field,
2470 override the flag_strict_flex_arrays. */
2471 if (attr_strict_flex_array)
2473 /* Get the value of the level first from the attribute. */
2474 unsigned HOST_WIDE_INT attr_strict_flex_array_level = 0;
2475 gcc_assert (TREE_VALUE (attr_strict_flex_array) != NULL_TREE);
2476 attr_strict_flex_array = TREE_VALUE (attr_strict_flex_array);
2477 gcc_assert (TREE_VALUE (attr_strict_flex_array) != NULL_TREE);
2478 attr_strict_flex_array = TREE_VALUE (attr_strict_flex_array);
2479 gcc_assert (tree_fits_uhwi_p (attr_strict_flex_array));
2480 attr_strict_flex_array_level = tree_to_uhwi (attr_strict_flex_array);
2482 /* The attribute has higher priority than flag_struct_flex_array. */
2483 strict_flex_array_level = attr_strict_flex_array_level;
2485 return strict_flex_array_level;
2489 /* Return the access specification for a function parameter PARM
2490 or null if the current function has no such specification. */
2492 attr_access *
2493 get_parm_access (rdwr_map &rdwr_idx, tree parm,
2494 tree fndecl /* = current_function_decl */)
2496 tree fntype = TREE_TYPE (fndecl);
2497 init_attr_rdwr_indices (&rdwr_idx, TYPE_ATTRIBUTES (fntype));
2499 if (rdwr_idx.is_empty ())
2500 return NULL;
2502 unsigned argpos = 0;
2503 tree fnargs = DECL_ARGUMENTS (fndecl);
2504 for (tree arg = fnargs; arg; arg = TREE_CHAIN (arg), ++argpos)
2505 if (arg == parm)
2506 return rdwr_idx.get (argpos);
2508 return NULL;
2511 /* Return the internal representation as STRING_CST. Internal positional
2512 arguments are zero-based. */
2514 tree
2515 attr_access::to_internal_string () const
2517 return build_string (end - str, str);
2520 /* Return the human-readable representation of the external attribute
2521 specification (as it might appear in the source code) as STRING_CST.
2522 External positional arguments are one-based. */
2524 tree
2525 attr_access::to_external_string () const
2527 char buf[80];
2528 gcc_assert (mode != access_deferred);
2529 int len = snprintf (buf, sizeof buf, "access (%s, %u",
2530 mode_names[mode], ptrarg + 1);
2531 if (sizarg != UINT_MAX)
2532 len += snprintf (buf + len, sizeof buf - len, ", %u", sizarg + 1);
2533 strcpy (buf + len, ")");
2534 return build_string (len + 2, buf);
2537 /* Return the number of specified VLA bounds and set *nunspec to
2538 the number of unspecified ones (those designated by [*]). */
2540 unsigned
2541 attr_access::vla_bounds (unsigned *nunspec) const
2543 unsigned nbounds = 0;
2544 *nunspec = 0;
2545 /* STR points to the beginning of the specified string for the current
2546 argument that may be followed by the string for the next argument. */
2547 for (const char* p = strchr (str, ']'); p && *p != '['; --p)
2549 if (*p == '*')
2550 ++*nunspec;
2551 else if (*p == '$')
2552 ++nbounds;
2554 return nbounds;
2557 /* Reset front end-specific attribute access data from ATTRS.
2558 Called from the free_lang_data pass. */
2560 /* static */ void
2561 attr_access::free_lang_data (tree attrs)
2563 for (tree acs = attrs; (acs = lookup_attribute ("access", acs));
2564 acs = TREE_CHAIN (acs))
2566 tree vblist = TREE_VALUE (acs);
2567 vblist = TREE_CHAIN (vblist);
2568 if (!vblist)
2569 continue;
2571 for (vblist = TREE_VALUE (vblist); vblist; vblist = TREE_CHAIN (vblist))
2573 tree *pvbnd = &TREE_VALUE (vblist);
2574 if (!*pvbnd || DECL_P (*pvbnd))
2575 continue;
2577 /* VLA bounds that are expressions as opposed to DECLs are
2578 only used in the front end. Reset them to keep front end
2579 trees leaking into the middle end (see pr97172) and to
2580 free up memory. */
2581 *pvbnd = NULL_TREE;
2585 for (tree argspec = attrs; (argspec = lookup_attribute ("arg spec", argspec));
2586 argspec = TREE_CHAIN (argspec))
2588 /* Same as above. */
2589 tree *pvblist = &TREE_VALUE (argspec);
2590 *pvblist = NULL_TREE;
2594 /* Defined in attr_access. */
2595 constexpr char attr_access::mode_chars[];
2596 constexpr char attr_access::mode_names[][11];
2598 /* Format an array, including a VLA, pointed to by TYPE and used as
2599 a function parameter as a human-readable string. ACC describes
2600 an access to the parameter and is used to determine the outermost
2601 form of the array including its bound which is otherwise obviated
2602 by its decay to pointer. Return the formatted string. */
2604 std::string
2605 attr_access::array_as_string (tree type) const
2607 std::string typstr;
2609 if (type == error_mark_node)
2610 return std::string ();
2612 if (this->str)
2614 /* For array parameters (but not pointers) create a temporary array
2615 type that corresponds to the form of the parameter including its
2616 qualifiers even though they apply to the pointer, not the array
2617 type. */
2618 const bool vla_p = minsize == HOST_WIDE_INT_M1U;
2619 tree eltype = TREE_TYPE (type);
2620 tree index_type = NULL_TREE;
2622 if (minsize == HOST_WIDE_INT_M1U)
2624 /* Determine if this is a VLA (an array whose most significant
2625 bound is nonconstant and whose access string has "$]" in it)
2626 extract the bound expression from SIZE. */
2627 const char *p = end;
2628 for ( ; p != str && *p-- != ']'; );
2629 if (*p == '$')
2630 /* SIZE may have been cleared. Use it with care. */
2631 index_type = build_index_type (size ? TREE_VALUE (size) : size);
2633 else if (minsize)
2634 index_type = build_index_type (size_int (minsize - 1));
2636 tree arat = NULL_TREE;
2637 if (static_p || vla_p)
2639 tree flag = static_p ? integer_one_node : NULL_TREE;
2640 /* Hack: there's no language-independent way to encode
2641 the "static" specifier or the "*" notation in an array type.
2642 Add a "fake" attribute to have the pretty-printer add "static"
2643 or "*". The "[static N]" notation is only valid in the most
2644 significant bound but [*] can be used for any bound. Because
2645 [*] is represented the same as [0] this hack only works for
2646 the most significant bound like static and the others are
2647 rendered as [0]. */
2648 arat = build_tree_list (get_identifier ("array"), flag);
2651 const int quals = TYPE_QUALS (type);
2652 type = build_array_type (eltype, index_type);
2653 type = build_type_attribute_qual_variant (type, arat, quals);
2656 /* Format the type using the current pretty printer. The generic tree
2657 printer does a terrible job. */
2658 pretty_printer *pp = global_dc->printer->clone ();
2659 pp_printf (pp, "%qT", type);
2660 typstr = pp_formatted_text (pp);
2661 delete pp;
2663 return typstr;
2666 #if CHECKING_P
2668 namespace selftest
2671 /* Helper types to verify the consistency attribute exclusions. */
2673 typedef std::pair<const char *, const char *> excl_pair;
2675 struct excl_hash_traits: typed_noop_remove<excl_pair>
2677 typedef excl_pair value_type;
2678 typedef value_type compare_type;
2680 static hashval_t hash (const value_type &x)
2682 hashval_t h1 = htab_hash_string (x.first);
2683 hashval_t h2 = htab_hash_string (x.second);
2684 return h1 ^ h2;
2687 static bool equal (const value_type &x, const value_type &y)
2689 return !strcmp (x.first, y.first) && !strcmp (x.second, y.second);
2692 static void mark_deleted (value_type &x)
2694 x = value_type (NULL, NULL);
2697 static const bool empty_zero_p = false;
2699 static void mark_empty (value_type &x)
2701 x = value_type ("", "");
2704 static bool is_deleted (const value_type &x)
2706 return !x.first && !x.second;
2709 static bool is_empty (const value_type &x)
2711 return !*x.first && !*x.second;
2716 /* Self-test to verify that each attribute exclusion is symmetric,
2717 meaning that if attribute A is encoded as incompatible with
2718 attribute B then the opposite relationship is also encoded.
2719 This test also detects most cases of misspelled attribute names
2720 in exclusions. */
2722 static void
2723 test_attribute_exclusions ()
2725 /* Iterate over the array of attribute tables first (with TI0 as
2726 the index) and over the array of attribute_spec in each table
2727 (with SI0 as the index). */
2728 const size_t ntables = ARRAY_SIZE (attribute_tables);
2730 /* Set of pairs of mutually exclusive attributes. */
2731 typedef hash_set<excl_pair, false, excl_hash_traits> exclusion_set;
2732 exclusion_set excl_set;
2734 for (size_t ti0 = 0; ti0 != ntables; ++ti0)
2735 for (size_t s0 = 0; attribute_tables[ti0][s0].name; ++s0)
2737 const attribute_spec::exclusions *excl
2738 = attribute_tables[ti0][s0].exclude;
2740 /* Skip each attribute that doesn't define exclusions. */
2741 if (!excl)
2742 continue;
2744 const char *attr_name = attribute_tables[ti0][s0].name;
2746 /* Iterate over the set of exclusions for every attribute
2747 (with EI0 as the index) adding the exclusions defined
2748 for each to the set. */
2749 for (size_t ei0 = 0; excl[ei0].name; ++ei0)
2751 const char *excl_name = excl[ei0].name;
2753 if (!strcmp (attr_name, excl_name))
2754 continue;
2756 excl_set.add (excl_pair (attr_name, excl_name));
2760 /* Traverse the set of mutually exclusive pairs of attributes
2761 and verify that they are symmetric. */
2762 for (exclusion_set::iterator it = excl_set.begin ();
2763 it != excl_set.end ();
2764 ++it)
2766 if (!excl_set.contains (excl_pair ((*it).second, (*it).first)))
2768 /* An exclusion for an attribute has been found that
2769 doesn't have a corresponding exclusion in the opposite
2770 direction. */
2771 char desc[120];
2772 sprintf (desc, "'%s' attribute exclusion '%s' must be symmetric",
2773 (*it).first, (*it).second);
2774 fail (SELFTEST_LOCATION, desc);
2779 void
2780 attribs_cc_tests ()
2782 test_attribute_exclusions ();
2785 } /* namespace selftest */
2787 #endif /* CHECKING_P */