Default to dwarf version 4 on hppa64-hpux
[official-gcc.git] / gcc / attribs.c
blob83fafc98b7d215fad482706c7b8182059855d2c8
1 /* Functions dealing with attribute handling, used by most front ends.
2 Copyright (C) 1992-2021 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;
92 /* The table of scope attributes. */
93 static vec<scoped_attributes> attributes_table;
95 static scoped_attributes* find_attribute_namespace (const char*);
96 static void register_scoped_attribute (const struct attribute_spec *,
97 scoped_attributes *);
99 static bool attributes_initialized = false;
101 /* Default empty table of attributes. */
103 static const struct attribute_spec empty_attribute_table[] =
105 { NULL, 0, 0, false, false, false, false, NULL, NULL }
108 /* Return base name of the attribute. Ie '__attr__' is turned into 'attr'.
109 To avoid need for copying, we simply return length of the string. */
111 static void
112 extract_attribute_substring (struct substring *str)
114 if (str->length > 4 && str->str[0] == '_' && str->str[1] == '_'
115 && str->str[str->length - 1] == '_' && str->str[str->length - 2] == '_')
117 str->length -= 4;
118 str->str += 2;
122 /* Insert an array of attributes ATTRIBUTES into a namespace. This
123 array must be NULL terminated. NS is the name of attribute
124 namespace. The function returns the namespace into which the
125 attributes have been registered. */
127 scoped_attributes *
128 register_scoped_attributes (const struct attribute_spec *attributes,
129 const char *ns)
131 scoped_attributes *result = NULL;
133 /* See if we already have attributes in the namespace NS. */
134 result = find_attribute_namespace (ns);
136 if (result == NULL)
138 /* We don't have any namespace NS yet. Create one. */
139 scoped_attributes sa;
141 if (attributes_table.is_empty ())
142 attributes_table.create (64);
144 memset (&sa, 0, sizeof (sa));
145 sa.ns = ns;
146 sa.attributes.create (64);
147 result = attributes_table.safe_push (sa);
148 result->attribute_hash = new hash_table<attribute_hasher> (200);
151 /* Really add the attributes to their namespace now. */
152 for (unsigned i = 0; attributes[i].name != NULL; ++i)
154 result->attributes.safe_push (attributes[i]);
155 register_scoped_attribute (&attributes[i], result);
158 gcc_assert (result != NULL);
160 return result;
163 /* Return the namespace which name is NS, NULL if none exist. */
165 static scoped_attributes*
166 find_attribute_namespace (const char* ns)
168 for (scoped_attributes &iter : attributes_table)
169 if (ns == iter.ns
170 || (iter.ns != NULL
171 && ns != NULL
172 && !strcmp (iter.ns, ns)))
173 return &iter;
174 return NULL;
177 /* Make some sanity checks on the attribute tables. */
179 static void
180 check_attribute_tables (void)
182 for (size_t i = 0; i < ARRAY_SIZE (attribute_tables); i++)
183 for (size_t j = 0; attribute_tables[i][j].name != NULL; j++)
185 /* The name must not begin and end with __. */
186 const char *name = attribute_tables[i][j].name;
187 int len = strlen (name);
189 gcc_assert (!(name[0] == '_' && name[1] == '_'
190 && name[len - 1] == '_' && name[len - 2] == '_'));
192 /* The minimum and maximum lengths must be consistent. */
193 gcc_assert (attribute_tables[i][j].min_length >= 0);
195 gcc_assert (attribute_tables[i][j].max_length == -1
196 || (attribute_tables[i][j].max_length
197 >= attribute_tables[i][j].min_length));
199 /* An attribute cannot require both a DECL and a TYPE. */
200 gcc_assert (!attribute_tables[i][j].decl_required
201 || !attribute_tables[i][j].type_required);
203 /* If an attribute requires a function type, in particular
204 it requires a type. */
205 gcc_assert (!attribute_tables[i][j].function_type_required
206 || attribute_tables[i][j].type_required);
209 /* Check that each name occurs just once in each table. */
210 for (size_t i = 0; i < ARRAY_SIZE (attribute_tables); i++)
211 for (size_t j = 0; attribute_tables[i][j].name != NULL; j++)
212 for (size_t k = j + 1; attribute_tables[i][k].name != NULL; k++)
213 gcc_assert (strcmp (attribute_tables[i][j].name,
214 attribute_tables[i][k].name));
216 /* Check that no name occurs in more than one table. Names that
217 begin with '*' are exempt, and may be overridden. */
218 for (size_t i = 0; i < ARRAY_SIZE (attribute_tables); i++)
219 for (size_t j = i + 1; j < ARRAY_SIZE (attribute_tables); j++)
220 for (size_t k = 0; attribute_tables[i][k].name != NULL; k++)
221 for (size_t l = 0; attribute_tables[j][l].name != NULL; l++)
222 gcc_assert (attribute_tables[i][k].name[0] == '*'
223 || strcmp (attribute_tables[i][k].name,
224 attribute_tables[j][l].name));
227 /* Initialize attribute tables, and make some sanity checks if checking is
228 enabled. */
230 void
231 init_attributes (void)
233 size_t i;
235 if (attributes_initialized)
236 return;
238 attribute_tables[0] = lang_hooks.common_attribute_table;
239 attribute_tables[1] = lang_hooks.attribute_table;
240 attribute_tables[2] = lang_hooks.format_attribute_table;
241 attribute_tables[3] = targetm.attribute_table;
243 /* Translate NULL pointers to pointers to the empty table. */
244 for (i = 0; i < ARRAY_SIZE (attribute_tables); i++)
245 if (attribute_tables[i] == NULL)
246 attribute_tables[i] = empty_attribute_table;
248 if (flag_checking)
249 check_attribute_tables ();
251 for (i = 0; i < ARRAY_SIZE (attribute_tables); ++i)
252 /* Put all the GNU attributes into the "gnu" namespace. */
253 register_scoped_attributes (attribute_tables[i], "gnu");
255 invoke_plugin_callbacks (PLUGIN_ATTRIBUTES, NULL);
256 attributes_initialized = true;
259 /* Insert a single ATTR into the attribute table. */
261 void
262 register_attribute (const struct attribute_spec *attr)
264 register_scoped_attribute (attr, find_attribute_namespace ("gnu"));
267 /* Insert a single attribute ATTR into a namespace of attributes. */
269 static void
270 register_scoped_attribute (const struct attribute_spec *attr,
271 scoped_attributes *name_space)
273 struct substring str;
274 attribute_spec **slot;
276 gcc_assert (attr != NULL && name_space != NULL);
278 gcc_assert (name_space->attribute_hash);
280 str.str = attr->name;
281 str.length = strlen (str.str);
283 /* Attribute names in the table must be in the form 'text' and not
284 in the form '__text__'. */
285 gcc_assert (str.length > 0 && str.str[0] != '_');
287 slot = name_space->attribute_hash
288 ->find_slot_with_hash (&str, substring_hash (str.str, str.length),
289 INSERT);
290 gcc_assert (!*slot || attr->name[0] == '*');
291 *slot = CONST_CAST (struct attribute_spec *, attr);
294 /* Return the spec for the scoped attribute with namespace NS and
295 name NAME. */
297 static const struct attribute_spec *
298 lookup_scoped_attribute_spec (const_tree ns, const_tree name)
300 struct substring attr;
301 scoped_attributes *attrs;
303 const char *ns_str = (ns != NULL_TREE) ? IDENTIFIER_POINTER (ns): NULL;
305 attrs = find_attribute_namespace (ns_str);
307 if (attrs == NULL)
308 return NULL;
310 attr.str = IDENTIFIER_POINTER (name);
311 attr.length = IDENTIFIER_LENGTH (name);
312 extract_attribute_substring (&attr);
313 return attrs->attribute_hash->find_with_hash (&attr,
314 substring_hash (attr.str,
315 attr.length));
318 /* Return the spec for the attribute named NAME. If NAME is a TREE_LIST,
319 it also specifies the attribute namespace. */
321 const struct attribute_spec *
322 lookup_attribute_spec (const_tree name)
324 tree ns;
325 if (TREE_CODE (name) == TREE_LIST)
327 ns = TREE_PURPOSE (name);
328 name = TREE_VALUE (name);
330 else
331 ns = get_identifier ("gnu");
332 return lookup_scoped_attribute_spec (ns, name);
336 /* Return the namespace of the attribute ATTR. This accessor works on
337 GNU and C++11 (scoped) attributes. On GNU attributes,
338 it returns an identifier tree for the string "gnu".
340 Please read the comments of cxx11_attribute_p to understand the
341 format of attributes. */
343 tree
344 get_attribute_namespace (const_tree attr)
346 if (cxx11_attribute_p (attr))
347 return TREE_PURPOSE (TREE_PURPOSE (attr));
348 return get_identifier ("gnu");
351 /* Check LAST_DECL and NODE of the same symbol for attributes that are
352 recorded in SPEC to be mutually exclusive with ATTRNAME, diagnose
353 them, and return true if any have been found. NODE can be a DECL
354 or a TYPE. */
356 static bool
357 diag_attr_exclusions (tree last_decl, tree node, tree attrname,
358 const attribute_spec *spec)
360 const attribute_spec::exclusions *excl = spec->exclude;
362 tree_code code = TREE_CODE (node);
364 if ((code == FUNCTION_DECL && !excl->function
365 && (!excl->type || !spec->affects_type_identity))
366 || (code == VAR_DECL && !excl->variable
367 && (!excl->type || !spec->affects_type_identity))
368 || (((code == TYPE_DECL || RECORD_OR_UNION_TYPE_P (node)) && !excl->type)))
369 return false;
371 /* True if an attribute that's mutually exclusive with ATTRNAME
372 has been found. */
373 bool found = false;
375 if (last_decl && last_decl != node && TREE_TYPE (last_decl) != node)
377 /* Check both the last DECL and its type for conflicts with
378 the attribute being added to the current decl or type. */
379 found |= diag_attr_exclusions (last_decl, last_decl, attrname, spec);
380 tree decl_type = TREE_TYPE (last_decl);
381 found |= diag_attr_exclusions (last_decl, decl_type, attrname, spec);
384 /* NODE is either the current DECL to which the attribute is being
385 applied or its TYPE. For the former, consider the attributes on
386 both the DECL and its type. */
387 tree attrs[2];
389 if (DECL_P (node))
391 attrs[0] = DECL_ATTRIBUTES (node);
392 attrs[1] = TYPE_ATTRIBUTES (TREE_TYPE (node));
394 else
396 attrs[0] = TYPE_ATTRIBUTES (node);
397 attrs[1] = NULL_TREE;
400 /* Iterate over the mutually exclusive attribute names and verify
401 that the symbol doesn't contain it. */
402 for (unsigned i = 0; i != sizeof attrs / sizeof *attrs; ++i)
404 if (!attrs[i])
405 continue;
407 for ( ; excl->name; ++excl)
409 /* Avoid checking the attribute against itself. */
410 if (is_attribute_p (excl->name, attrname))
411 continue;
413 if (!lookup_attribute (excl->name, attrs[i]))
414 continue;
416 /* An exclusion may apply either to a function declaration,
417 type declaration, or a field/variable declaration, or
418 any subset of the three. */
419 if (TREE_CODE (node) == FUNCTION_DECL
420 && !excl->function)
421 continue;
423 if (TREE_CODE (node) == TYPE_DECL
424 && !excl->type)
425 continue;
427 if ((TREE_CODE (node) == FIELD_DECL
428 || TREE_CODE (node) == VAR_DECL)
429 && !excl->variable)
430 continue;
432 found = true;
434 /* Print a note? */
435 bool note = last_decl != NULL_TREE;
436 auto_diagnostic_group d;
437 if (TREE_CODE (node) == FUNCTION_DECL
438 && fndecl_built_in_p (node))
439 note &= warning (OPT_Wattributes,
440 "ignoring attribute %qE in declaration of "
441 "a built-in function %qD because it conflicts "
442 "with attribute %qs",
443 attrname, node, excl->name);
444 else
445 note &= warning (OPT_Wattributes,
446 "ignoring attribute %qE because "
447 "it conflicts with attribute %qs",
448 attrname, excl->name);
450 if (note)
451 inform (DECL_SOURCE_LOCATION (last_decl),
452 "previous declaration here");
456 return found;
459 /* Process the attributes listed in ATTRIBUTES and install them in *NODE,
460 which is either a DECL (including a TYPE_DECL) or a TYPE. If a DECL,
461 it should be modified in place; if a TYPE, a copy should be created
462 unless ATTR_FLAG_TYPE_IN_PLACE is set in FLAGS. FLAGS gives further
463 information, in the form of a bitwise OR of flags in enum attribute_flags
464 from tree.h. Depending on these flags, some attributes may be
465 returned to be applied at a later stage (for example, to apply
466 a decl attribute to the declaration rather than to its type). */
468 tree
469 decl_attributes (tree *node, tree attributes, int flags,
470 tree last_decl /* = NULL_TREE */)
472 tree returned_attrs = NULL_TREE;
474 if (TREE_TYPE (*node) == error_mark_node || attributes == error_mark_node)
475 return NULL_TREE;
477 if (!attributes_initialized)
478 init_attributes ();
480 /* If this is a function and the user used #pragma GCC optimize, add the
481 options to the attribute((optimize(...))) list. */
482 if (TREE_CODE (*node) == FUNCTION_DECL && current_optimize_pragma)
484 tree cur_attr = lookup_attribute ("optimize", attributes);
485 tree opts = copy_list (current_optimize_pragma);
487 if (! cur_attr)
488 attributes
489 = tree_cons (get_identifier ("optimize"), opts, attributes);
490 else
491 TREE_VALUE (cur_attr) = chainon (opts, TREE_VALUE (cur_attr));
494 if (TREE_CODE (*node) == FUNCTION_DECL
495 && optimization_current_node != optimization_default_node
496 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (*node))
497 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (*node) = optimization_current_node;
499 /* If this is a function and the user used #pragma GCC target, add the
500 options to the attribute((target(...))) list. */
501 if (TREE_CODE (*node) == FUNCTION_DECL
502 && current_target_pragma
503 && targetm.target_option.valid_attribute_p (*node, NULL_TREE,
504 current_target_pragma, 0))
506 tree cur_attr = lookup_attribute ("target", attributes);
507 tree opts = copy_list (current_target_pragma);
509 if (! cur_attr)
510 attributes = tree_cons (get_identifier ("target"), opts, attributes);
511 else
512 TREE_VALUE (cur_attr) = chainon (opts, TREE_VALUE (cur_attr));
515 /* A "naked" function attribute implies "noinline" and "noclone" for
516 those targets that support it. */
517 if (TREE_CODE (*node) == FUNCTION_DECL
518 && attributes
519 && lookup_attribute ("naked", attributes) != NULL
520 && lookup_attribute_spec (get_identifier ("naked"))
521 && lookup_attribute ("noipa", attributes) == NULL)
522 attributes = tree_cons (get_identifier ("noipa"), NULL, attributes);
524 /* A "noipa" function attribute implies "noinline", "noclone" and "no_icf"
525 for those targets that support it. */
526 if (TREE_CODE (*node) == FUNCTION_DECL
527 && attributes
528 && lookup_attribute ("noipa", attributes) != NULL
529 && lookup_attribute_spec (get_identifier ("noipa")))
531 if (lookup_attribute ("noinline", attributes) == NULL)
532 attributes = tree_cons (get_identifier ("noinline"), NULL, attributes);
534 if (lookup_attribute ("noclone", attributes) == NULL)
535 attributes = tree_cons (get_identifier ("noclone"), NULL, attributes);
537 if (lookup_attribute ("no_icf", attributes) == NULL)
538 attributes = tree_cons (get_identifier ("no_icf"), NULL, attributes);
541 targetm.insert_attributes (*node, &attributes);
543 /* Note that attributes on the same declaration are not necessarily
544 in the same order as in the source. */
545 for (tree attr = attributes; attr; attr = TREE_CHAIN (attr))
547 tree ns = get_attribute_namespace (attr);
548 tree name = get_attribute_name (attr);
549 tree args = TREE_VALUE (attr);
550 tree *anode = node;
551 const struct attribute_spec *spec
552 = lookup_scoped_attribute_spec (ns, name);
553 int fn_ptr_quals = 0;
554 tree fn_ptr_tmp = NULL_TREE;
555 const bool cxx11_attr_p = cxx11_attribute_p (attr);
557 if (spec == NULL)
559 if (!(flags & (int) ATTR_FLAG_BUILT_IN))
561 if (ns == NULL_TREE || !cxx11_attr_p)
562 warning (OPT_Wattributes, "%qE attribute directive ignored",
563 name);
564 else
565 warning (OPT_Wattributes,
566 "%<%E::%E%> scoped attribute directive ignored",
567 ns, name);
569 continue;
571 else
573 int nargs = list_length (args);
574 if (nargs < spec->min_length
575 || (spec->max_length >= 0
576 && nargs > spec->max_length))
578 error ("wrong number of arguments specified for %qE attribute",
579 name);
580 if (spec->max_length < 0)
581 inform (input_location, "expected %i or more, found %i",
582 spec->min_length, nargs);
583 else
584 inform (input_location, "expected between %i and %i, found %i",
585 spec->min_length, spec->max_length, nargs);
586 continue;
589 gcc_assert (is_attribute_p (spec->name, name));
591 if (spec->decl_required && !DECL_P (*anode))
593 if (flags & ((int) ATTR_FLAG_DECL_NEXT
594 | (int) ATTR_FLAG_FUNCTION_NEXT
595 | (int) ATTR_FLAG_ARRAY_NEXT))
597 /* Pass on this attribute to be tried again. */
598 tree attr = tree_cons (name, args, NULL_TREE);
599 returned_attrs = chainon (returned_attrs, attr);
600 continue;
602 else
604 warning (OPT_Wattributes, "%qE attribute does not apply to types",
605 name);
606 continue;
610 /* If we require a type, but were passed a decl, set up to make a
611 new type and update the one in the decl. ATTR_FLAG_TYPE_IN_PLACE
612 would have applied if we'd been passed a type, but we cannot modify
613 the decl's type in place here. */
614 if (spec->type_required && DECL_P (*anode))
616 anode = &TREE_TYPE (*anode);
617 flags &= ~(int) ATTR_FLAG_TYPE_IN_PLACE;
620 if (spec->function_type_required && TREE_CODE (*anode) != FUNCTION_TYPE
621 && TREE_CODE (*anode) != METHOD_TYPE)
623 if (TREE_CODE (*anode) == POINTER_TYPE
624 && (TREE_CODE (TREE_TYPE (*anode)) == FUNCTION_TYPE
625 || TREE_CODE (TREE_TYPE (*anode)) == METHOD_TYPE))
627 /* OK, this is a bit convoluted. We can't just make a copy
628 of the pointer type and modify its TREE_TYPE, because if
629 we change the attributes of the target type the pointer
630 type needs to have a different TYPE_MAIN_VARIANT. So we
631 pull out the target type now, frob it as appropriate, and
632 rebuild the pointer type later.
634 This would all be simpler if attributes were part of the
635 declarator, grumble grumble. */
636 fn_ptr_tmp = TREE_TYPE (*anode);
637 fn_ptr_quals = TYPE_QUALS (*anode);
638 anode = &fn_ptr_tmp;
639 flags &= ~(int) ATTR_FLAG_TYPE_IN_PLACE;
641 else if (flags & (int) ATTR_FLAG_FUNCTION_NEXT)
643 /* Pass on this attribute to be tried again. */
644 tree attr = tree_cons (name, args, NULL_TREE);
645 returned_attrs = chainon (returned_attrs, attr);
646 continue;
649 if (TREE_CODE (*anode) != FUNCTION_TYPE
650 && TREE_CODE (*anode) != METHOD_TYPE)
652 warning (OPT_Wattributes,
653 "%qE attribute only applies to function types",
654 name);
655 continue;
659 if (TYPE_P (*anode)
660 && (flags & (int) ATTR_FLAG_TYPE_IN_PLACE)
661 && TYPE_SIZE (*anode) != NULL_TREE)
663 warning (OPT_Wattributes, "type attributes ignored after type is already defined");
664 continue;
667 bool no_add_attrs = false;
669 /* Check for exclusions with other attributes on the current
670 declation as well as the last declaration of the same
671 symbol already processed (if one exists). Detect and
672 reject incompatible attributes. */
673 bool built_in = flags & ATTR_FLAG_BUILT_IN;
674 if (spec->exclude
675 && (flag_checking || !built_in)
676 && !error_operand_p (last_decl))
678 /* Always check attributes on user-defined functions.
679 Check them on built-ins only when -fchecking is set.
680 Ignore __builtin_unreachable -- it's both const and
681 noreturn. */
683 if (!built_in
684 || !DECL_P (*anode)
685 || DECL_BUILT_IN_CLASS (*anode) != BUILT_IN_NORMAL
686 || (DECL_FUNCTION_CODE (*anode) != BUILT_IN_UNREACHABLE
687 && (DECL_FUNCTION_CODE (*anode)
688 != BUILT_IN_UBSAN_HANDLE_BUILTIN_UNREACHABLE)))
690 bool no_add = diag_attr_exclusions (last_decl, *anode, name, spec);
691 if (!no_add && anode != node)
692 no_add = diag_attr_exclusions (last_decl, *node, name, spec);
693 no_add_attrs |= no_add;
697 if (no_add_attrs)
698 continue;
700 if (spec->handler != NULL)
702 int cxx11_flag = (cxx11_attr_p ? ATTR_FLAG_CXX11 : 0);
704 /* Pass in an array of the current declaration followed
705 by the last pushed/merged declaration if one exists.
706 For calls that modify the type attributes of a DECL
707 and for which *ANODE is *NODE's type, also pass in
708 the DECL as the third element to use in diagnostics.
709 If the handler changes CUR_AND_LAST_DECL[0] replace
710 *ANODE with its value. */
711 tree cur_and_last_decl[3] = { *anode, last_decl };
712 if (anode != node && DECL_P (*node))
713 cur_and_last_decl[2] = *node;
715 tree ret = (spec->handler) (cur_and_last_decl, name, args,
716 flags|cxx11_flag, &no_add_attrs);
718 *anode = cur_and_last_decl[0];
719 if (ret == error_mark_node)
721 warning (OPT_Wattributes, "%qE attribute ignored", name);
722 no_add_attrs = true;
724 else
725 returned_attrs = chainon (ret, returned_attrs);
728 /* Layout the decl in case anything changed. */
729 if (spec->type_required && DECL_P (*node)
730 && (VAR_P (*node)
731 || TREE_CODE (*node) == PARM_DECL
732 || TREE_CODE (*node) == RESULT_DECL))
733 relayout_decl (*node);
735 if (!no_add_attrs)
737 tree old_attrs;
738 tree a;
740 if (DECL_P (*anode))
741 old_attrs = DECL_ATTRIBUTES (*anode);
742 else
743 old_attrs = TYPE_ATTRIBUTES (*anode);
745 for (a = lookup_attribute (spec->name, old_attrs);
746 a != NULL_TREE;
747 a = lookup_attribute (spec->name, TREE_CHAIN (a)))
749 if (simple_cst_equal (TREE_VALUE (a), args) == 1)
750 break;
753 if (a == NULL_TREE)
755 /* This attribute isn't already in the list. */
756 tree r;
757 /* Preserve the C++11 form. */
758 if (cxx11_attr_p)
759 r = tree_cons (build_tree_list (ns, name), args, old_attrs);
760 else
761 r = tree_cons (name, args, old_attrs);
763 if (DECL_P (*anode))
764 DECL_ATTRIBUTES (*anode) = r;
765 else if (flags & (int) ATTR_FLAG_TYPE_IN_PLACE)
767 TYPE_ATTRIBUTES (*anode) = r;
768 /* If this is the main variant, also push the attributes
769 out to the other variants. */
770 if (*anode == TYPE_MAIN_VARIANT (*anode))
772 for (tree variant = *anode; variant;
773 variant = TYPE_NEXT_VARIANT (variant))
775 if (TYPE_ATTRIBUTES (variant) == old_attrs)
776 TYPE_ATTRIBUTES (variant)
777 = TYPE_ATTRIBUTES (*anode);
778 else if (!lookup_attribute
779 (spec->name, TYPE_ATTRIBUTES (variant)))
780 TYPE_ATTRIBUTES (variant) = tree_cons
781 (name, args, TYPE_ATTRIBUTES (variant));
785 else
786 *anode = build_type_attribute_variant (*anode, r);
790 if (fn_ptr_tmp)
792 /* Rebuild the function pointer type and put it in the
793 appropriate place. */
794 fn_ptr_tmp = build_pointer_type (fn_ptr_tmp);
795 if (fn_ptr_quals)
796 fn_ptr_tmp = build_qualified_type (fn_ptr_tmp, fn_ptr_quals);
797 if (DECL_P (*node))
798 TREE_TYPE (*node) = fn_ptr_tmp;
799 else
801 gcc_assert (TREE_CODE (*node) == POINTER_TYPE);
802 *node = fn_ptr_tmp;
807 return returned_attrs;
810 /* Return TRUE iff ATTR has been parsed by the front-end as a C++-11
811 attribute.
813 When G++ parses a C++11 attribute, it is represented as
814 a TREE_LIST which TREE_PURPOSE is itself a TREE_LIST. TREE_PURPOSE
815 (TREE_PURPOSE (ATTR)) is the namespace of the attribute, and the
816 TREE_VALUE (TREE_PURPOSE (ATTR)) is its non-qualified name. Please
817 use get_attribute_namespace and get_attribute_name to retrieve the
818 namespace and name of the attribute, as these accessors work with
819 GNU attributes as well. */
821 bool
822 cxx11_attribute_p (const_tree attr)
824 if (attr == NULL_TREE
825 || TREE_CODE (attr) != TREE_LIST)
826 return false;
828 return (TREE_CODE (TREE_PURPOSE (attr)) == TREE_LIST);
831 /* Return the name of the attribute ATTR. This accessor works on GNU
832 and C++11 (scoped) attributes.
834 Please read the comments of cxx11_attribute_p to understand the
835 format of attributes. */
837 tree
838 get_attribute_name (const_tree attr)
840 if (cxx11_attribute_p (attr))
841 return TREE_VALUE (TREE_PURPOSE (attr));
842 return TREE_PURPOSE (attr);
845 /* Subroutine of set_method_tm_attributes. Apply TM attribute ATTR
846 to the method FNDECL. */
848 void
849 apply_tm_attr (tree fndecl, tree attr)
851 decl_attributes (&TREE_TYPE (fndecl), tree_cons (attr, NULL, NULL), 0);
854 /* Makes a function attribute of the form NAME(ARG_NAME) and chains
855 it to CHAIN. */
857 tree
858 make_attribute (const char *name, const char *arg_name, tree chain)
860 tree attr_name;
861 tree attr_arg_name;
862 tree attr_args;
863 tree attr;
865 attr_name = get_identifier (name);
866 attr_arg_name = build_string (strlen (arg_name), arg_name);
867 attr_args = tree_cons (NULL_TREE, attr_arg_name, NULL_TREE);
868 attr = tree_cons (attr_name, attr_args, chain);
869 return attr;
873 /* Common functions used for target clone support. */
875 /* Comparator function to be used in qsort routine to sort attribute
876 specification strings to "target". */
878 static int
879 attr_strcmp (const void *v1, const void *v2)
881 const char *c1 = *(char *const*)v1;
882 const char *c2 = *(char *const*)v2;
883 return strcmp (c1, c2);
886 /* ARGLIST is the argument to target attribute. This function tokenizes
887 the comma separated arguments, sorts them and returns a string which
888 is a unique identifier for the comma separated arguments. It also
889 replaces non-identifier characters "=,-" with "_". */
891 char *
892 sorted_attr_string (tree arglist)
894 tree arg;
895 size_t str_len_sum = 0;
896 char **args = NULL;
897 char *attr_str, *ret_str;
898 char *attr = NULL;
899 unsigned int argnum = 1;
900 unsigned int i;
902 for (arg = arglist; arg; arg = TREE_CHAIN (arg))
904 const char *str = TREE_STRING_POINTER (TREE_VALUE (arg));
905 size_t len = strlen (str);
906 str_len_sum += len + 1;
907 if (arg != arglist)
908 argnum++;
909 for (i = 0; i < strlen (str); i++)
910 if (str[i] == ',')
911 argnum++;
914 attr_str = XNEWVEC (char, str_len_sum);
915 str_len_sum = 0;
916 for (arg = arglist; arg; arg = TREE_CHAIN (arg))
918 const char *str = TREE_STRING_POINTER (TREE_VALUE (arg));
919 size_t len = strlen (str);
920 memcpy (attr_str + str_len_sum, str, len);
921 attr_str[str_len_sum + len] = TREE_CHAIN (arg) ? ',' : '\0';
922 str_len_sum += len + 1;
925 /* Replace "=,-" with "_". */
926 for (i = 0; i < strlen (attr_str); i++)
927 if (attr_str[i] == '=' || attr_str[i]== '-')
928 attr_str[i] = '_';
930 if (argnum == 1)
931 return attr_str;
933 args = XNEWVEC (char *, argnum);
935 i = 0;
936 attr = strtok (attr_str, ",");
937 while (attr != NULL)
939 args[i] = attr;
940 i++;
941 attr = strtok (NULL, ",");
944 qsort (args, argnum, sizeof (char *), attr_strcmp);
946 ret_str = XNEWVEC (char, str_len_sum);
947 str_len_sum = 0;
948 for (i = 0; i < argnum; i++)
950 size_t len = strlen (args[i]);
951 memcpy (ret_str + str_len_sum, args[i], len);
952 ret_str[str_len_sum + len] = i < argnum - 1 ? '_' : '\0';
953 str_len_sum += len + 1;
956 XDELETEVEC (args);
957 XDELETEVEC (attr_str);
958 return ret_str;
962 /* This function returns true if FN1 and FN2 are versions of the same function,
963 that is, the target strings of the function decls are different. This assumes
964 that FN1 and FN2 have the same signature. */
966 bool
967 common_function_versions (tree fn1, tree fn2)
969 tree attr1, attr2;
970 char *target1, *target2;
971 bool result;
973 if (TREE_CODE (fn1) != FUNCTION_DECL
974 || TREE_CODE (fn2) != FUNCTION_DECL)
975 return false;
977 attr1 = lookup_attribute ("target", DECL_ATTRIBUTES (fn1));
978 attr2 = lookup_attribute ("target", DECL_ATTRIBUTES (fn2));
980 /* At least one function decl should have the target attribute specified. */
981 if (attr1 == NULL_TREE && attr2 == NULL_TREE)
982 return false;
984 /* Diagnose missing target attribute if one of the decls is already
985 multi-versioned. */
986 if (attr1 == NULL_TREE || attr2 == NULL_TREE)
988 if (DECL_FUNCTION_VERSIONED (fn1) || DECL_FUNCTION_VERSIONED (fn2))
990 if (attr2 != NULL_TREE)
992 std::swap (fn1, fn2);
993 attr1 = attr2;
995 error_at (DECL_SOURCE_LOCATION (fn2),
996 "missing %<target%> attribute for multi-versioned %qD",
997 fn2);
998 inform (DECL_SOURCE_LOCATION (fn1),
999 "previous declaration of %qD", fn1);
1000 /* Prevent diagnosing of the same error multiple times. */
1001 DECL_ATTRIBUTES (fn2)
1002 = tree_cons (get_identifier ("target"),
1003 copy_node (TREE_VALUE (attr1)),
1004 DECL_ATTRIBUTES (fn2));
1006 return false;
1009 target1 = sorted_attr_string (TREE_VALUE (attr1));
1010 target2 = sorted_attr_string (TREE_VALUE (attr2));
1012 /* The sorted target strings must be different for fn1 and fn2
1013 to be versions. */
1014 if (strcmp (target1, target2) == 0)
1015 result = false;
1016 else
1017 result = true;
1019 XDELETEVEC (target1);
1020 XDELETEVEC (target2);
1022 return result;
1025 /* Make a dispatcher declaration for the multi-versioned function DECL.
1026 Calls to DECL function will be replaced with calls to the dispatcher
1027 by the front-end. Return the decl created. */
1029 tree
1030 make_dispatcher_decl (const tree decl)
1032 tree func_decl;
1033 char *func_name;
1034 tree fn_type, func_type;
1036 func_name = xstrdup (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
1038 fn_type = TREE_TYPE (decl);
1039 func_type = build_function_type (TREE_TYPE (fn_type),
1040 TYPE_ARG_TYPES (fn_type));
1042 func_decl = build_fn_decl (func_name, func_type);
1043 XDELETEVEC (func_name);
1044 TREE_USED (func_decl) = 1;
1045 DECL_CONTEXT (func_decl) = NULL_TREE;
1046 DECL_INITIAL (func_decl) = error_mark_node;
1047 DECL_ARTIFICIAL (func_decl) = 1;
1048 /* Mark this func as external, the resolver will flip it again if
1049 it gets generated. */
1050 DECL_EXTERNAL (func_decl) = 1;
1051 /* This will be of type IFUNCs have to be externally visible. */
1052 TREE_PUBLIC (func_decl) = 1;
1054 return func_decl;
1057 /* Returns true if decl is multi-versioned and DECL is the default function,
1058 that is it is not tagged with target specific optimization. */
1060 bool
1061 is_function_default_version (const tree decl)
1063 if (TREE_CODE (decl) != FUNCTION_DECL
1064 || !DECL_FUNCTION_VERSIONED (decl))
1065 return false;
1066 tree attr = lookup_attribute ("target", DECL_ATTRIBUTES (decl));
1067 gcc_assert (attr);
1068 attr = TREE_VALUE (TREE_VALUE (attr));
1069 return (TREE_CODE (attr) == STRING_CST
1070 && strcmp (TREE_STRING_POINTER (attr), "default") == 0);
1073 /* Return a declaration like DDECL except that its DECL_ATTRIBUTES
1074 is ATTRIBUTE. */
1076 tree
1077 build_decl_attribute_variant (tree ddecl, tree attribute)
1079 DECL_ATTRIBUTES (ddecl) = attribute;
1080 return ddecl;
1083 /* Return a type like TTYPE except that its TYPE_ATTRIBUTE
1084 is ATTRIBUTE and its qualifiers are QUALS.
1086 Record such modified types already made so we don't make duplicates. */
1088 tree
1089 build_type_attribute_qual_variant (tree otype, tree attribute, int quals)
1091 tree ttype = otype;
1092 if (! attribute_list_equal (TYPE_ATTRIBUTES (ttype), attribute))
1094 tree ntype;
1096 /* Building a distinct copy of a tagged type is inappropriate; it
1097 causes breakage in code that expects there to be a one-to-one
1098 relationship between a struct and its fields.
1099 build_duplicate_type is another solution (as used in
1100 handle_transparent_union_attribute), but that doesn't play well
1101 with the stronger C++ type identity model. */
1102 if (TREE_CODE (ttype) == RECORD_TYPE
1103 || TREE_CODE (ttype) == UNION_TYPE
1104 || TREE_CODE (ttype) == QUAL_UNION_TYPE
1105 || TREE_CODE (ttype) == ENUMERAL_TYPE)
1107 warning (OPT_Wattributes,
1108 "ignoring attributes applied to %qT after definition",
1109 TYPE_MAIN_VARIANT (ttype));
1110 return build_qualified_type (ttype, quals);
1113 ttype = build_qualified_type (ttype, TYPE_UNQUALIFIED);
1114 if (lang_hooks.types.copy_lang_qualifiers
1115 && otype != TYPE_MAIN_VARIANT (otype))
1116 ttype = (lang_hooks.types.copy_lang_qualifiers
1117 (ttype, TYPE_MAIN_VARIANT (otype)));
1119 tree dtype = ntype = build_distinct_type_copy (ttype);
1121 TYPE_ATTRIBUTES (ntype) = attribute;
1123 hashval_t hash = type_hash_canon_hash (ntype);
1124 ntype = type_hash_canon (hash, ntype);
1126 if (ntype != dtype)
1127 /* This variant was already in the hash table, don't mess with
1128 TYPE_CANONICAL. */;
1129 else if (TYPE_STRUCTURAL_EQUALITY_P (ttype)
1130 || !comp_type_attributes (ntype, ttype))
1131 /* If the target-dependent attributes make NTYPE different from
1132 its canonical type, we will need to use structural equality
1133 checks for this type.
1135 We shouldn't get here for stripping attributes from a type;
1136 the no-attribute type might not need structural comparison. But
1137 we can if was discarded from type_hash_table. */
1138 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
1139 else if (TYPE_CANONICAL (ntype) == ntype)
1140 TYPE_CANONICAL (ntype) = TYPE_CANONICAL (ttype);
1142 ttype = build_qualified_type (ntype, quals);
1143 if (lang_hooks.types.copy_lang_qualifiers
1144 && otype != TYPE_MAIN_VARIANT (otype))
1145 ttype = lang_hooks.types.copy_lang_qualifiers (ttype, otype);
1147 else if (TYPE_QUALS (ttype) != quals)
1148 ttype = build_qualified_type (ttype, quals);
1150 return ttype;
1153 /* Compare two identifier nodes representing attributes.
1154 Return true if they are the same, false otherwise. */
1156 static bool
1157 cmp_attrib_identifiers (const_tree attr1, const_tree attr2)
1159 /* Make sure we're dealing with IDENTIFIER_NODEs. */
1160 gcc_checking_assert (TREE_CODE (attr1) == IDENTIFIER_NODE
1161 && TREE_CODE (attr2) == IDENTIFIER_NODE);
1163 /* Identifiers can be compared directly for equality. */
1164 if (attr1 == attr2)
1165 return true;
1167 return cmp_attribs (IDENTIFIER_POINTER (attr1), IDENTIFIER_LENGTH (attr1),
1168 IDENTIFIER_POINTER (attr2), IDENTIFIER_LENGTH (attr2));
1171 /* Compare two constructor-element-type constants. Return 1 if the lists
1172 are known to be equal; otherwise return 0. */
1174 static bool
1175 simple_cst_list_equal (const_tree l1, const_tree l2)
1177 while (l1 != NULL_TREE && l2 != NULL_TREE)
1179 if (simple_cst_equal (TREE_VALUE (l1), TREE_VALUE (l2)) != 1)
1180 return false;
1182 l1 = TREE_CHAIN (l1);
1183 l2 = TREE_CHAIN (l2);
1186 return l1 == l2;
1189 /* Check if "omp declare simd" attribute arguments, CLAUSES1 and CLAUSES2, are
1190 the same. */
1192 static bool
1193 omp_declare_simd_clauses_equal (tree clauses1, tree clauses2)
1195 tree cl1, cl2;
1196 for (cl1 = clauses1, cl2 = clauses2;
1197 cl1 && cl2;
1198 cl1 = OMP_CLAUSE_CHAIN (cl1), cl2 = OMP_CLAUSE_CHAIN (cl2))
1200 if (OMP_CLAUSE_CODE (cl1) != OMP_CLAUSE_CODE (cl2))
1201 return false;
1202 if (OMP_CLAUSE_CODE (cl1) != OMP_CLAUSE_SIMDLEN)
1204 if (simple_cst_equal (OMP_CLAUSE_DECL (cl1),
1205 OMP_CLAUSE_DECL (cl2)) != 1)
1206 return false;
1208 switch (OMP_CLAUSE_CODE (cl1))
1210 case OMP_CLAUSE_ALIGNED:
1211 if (simple_cst_equal (OMP_CLAUSE_ALIGNED_ALIGNMENT (cl1),
1212 OMP_CLAUSE_ALIGNED_ALIGNMENT (cl2)) != 1)
1213 return false;
1214 break;
1215 case OMP_CLAUSE_LINEAR:
1216 if (simple_cst_equal (OMP_CLAUSE_LINEAR_STEP (cl1),
1217 OMP_CLAUSE_LINEAR_STEP (cl2)) != 1)
1218 return false;
1219 break;
1220 case OMP_CLAUSE_SIMDLEN:
1221 if (simple_cst_equal (OMP_CLAUSE_SIMDLEN_EXPR (cl1),
1222 OMP_CLAUSE_SIMDLEN_EXPR (cl2)) != 1)
1223 return false;
1224 default:
1225 break;
1228 return true;
1232 /* Compare two attributes for their value identity. Return true if the
1233 attribute values are known to be equal; otherwise return false. */
1235 bool
1236 attribute_value_equal (const_tree attr1, const_tree attr2)
1238 if (TREE_VALUE (attr1) == TREE_VALUE (attr2))
1239 return true;
1241 if (TREE_VALUE (attr1) != NULL_TREE
1242 && TREE_CODE (TREE_VALUE (attr1)) == TREE_LIST
1243 && TREE_VALUE (attr2) != NULL_TREE
1244 && TREE_CODE (TREE_VALUE (attr2)) == TREE_LIST)
1246 /* Handle attribute format. */
1247 if (is_attribute_p ("format", get_attribute_name (attr1)))
1249 attr1 = TREE_VALUE (attr1);
1250 attr2 = TREE_VALUE (attr2);
1251 /* Compare the archetypes (printf/scanf/strftime/...). */
1252 if (!cmp_attrib_identifiers (TREE_VALUE (attr1), TREE_VALUE (attr2)))
1253 return false;
1254 /* Archetypes are the same. Compare the rest. */
1255 return (simple_cst_list_equal (TREE_CHAIN (attr1),
1256 TREE_CHAIN (attr2)) == 1);
1258 return (simple_cst_list_equal (TREE_VALUE (attr1),
1259 TREE_VALUE (attr2)) == 1);
1262 if (TREE_VALUE (attr1)
1263 && TREE_CODE (TREE_VALUE (attr1)) == OMP_CLAUSE
1264 && TREE_VALUE (attr2)
1265 && TREE_CODE (TREE_VALUE (attr2)) == OMP_CLAUSE)
1266 return omp_declare_simd_clauses_equal (TREE_VALUE (attr1),
1267 TREE_VALUE (attr2));
1269 return (simple_cst_equal (TREE_VALUE (attr1), TREE_VALUE (attr2)) == 1);
1272 /* Return 0 if the attributes for two types are incompatible, 1 if they
1273 are compatible, and 2 if they are nearly compatible (which causes a
1274 warning to be generated). */
1276 comp_type_attributes (const_tree type1, const_tree type2)
1278 const_tree a1 = TYPE_ATTRIBUTES (type1);
1279 const_tree a2 = TYPE_ATTRIBUTES (type2);
1280 const_tree a;
1282 if (a1 == a2)
1283 return 1;
1284 for (a = a1; a != NULL_TREE; a = TREE_CHAIN (a))
1286 const struct attribute_spec *as;
1287 const_tree attr;
1289 as = lookup_attribute_spec (get_attribute_name (a));
1290 if (!as || as->affects_type_identity == false)
1291 continue;
1293 attr = lookup_attribute (as->name, CONST_CAST_TREE (a2));
1294 if (!attr || !attribute_value_equal (a, attr))
1295 break;
1297 if (!a)
1299 for (a = a2; a != NULL_TREE; a = TREE_CHAIN (a))
1301 const struct attribute_spec *as;
1303 as = lookup_attribute_spec (get_attribute_name (a));
1304 if (!as || as->affects_type_identity == false)
1305 continue;
1307 if (!lookup_attribute (as->name, CONST_CAST_TREE (a1)))
1308 break;
1309 /* We don't need to compare trees again, as we did this
1310 already in first loop. */
1312 /* All types - affecting identity - are equal, so
1313 there is no need to call target hook for comparison. */
1314 if (!a)
1315 return 1;
1317 if (lookup_attribute ("transaction_safe", CONST_CAST_TREE (a)))
1318 return 0;
1319 if ((lookup_attribute ("nocf_check", TYPE_ATTRIBUTES (type1)) != NULL)
1320 ^ (lookup_attribute ("nocf_check", TYPE_ATTRIBUTES (type2)) != NULL))
1321 return 0;
1322 /* As some type combinations - like default calling-convention - might
1323 be compatible, we have to call the target hook to get the final result. */
1324 return targetm.comp_type_attributes (type1, type2);
1327 /* PREDICATE acts as a function of type:
1329 (const_tree attr, const attribute_spec *as) -> bool
1331 where ATTR is an attribute and AS is its possibly-null specification.
1332 Return a list of every attribute in attribute list ATTRS for which
1333 PREDICATE is true. Return ATTRS itself if PREDICATE returns true
1334 for every attribute. */
1336 template<typename Predicate>
1337 tree
1338 remove_attributes_matching (tree attrs, Predicate predicate)
1340 tree new_attrs = NULL_TREE;
1341 tree *ptr = &new_attrs;
1342 const_tree start = attrs;
1343 for (const_tree attr = attrs; attr; attr = TREE_CHAIN (attr))
1345 tree name = get_attribute_name (attr);
1346 const attribute_spec *as = lookup_attribute_spec (name);
1347 const_tree end;
1348 if (!predicate (attr, as))
1349 end = attr;
1350 else if (start == attrs)
1351 continue;
1352 else
1353 end = TREE_CHAIN (attr);
1355 for (; start != end; start = TREE_CHAIN (start))
1357 *ptr = tree_cons (TREE_PURPOSE (start),
1358 TREE_VALUE (start), NULL_TREE);
1359 TREE_CHAIN (*ptr) = NULL_TREE;
1360 ptr = &TREE_CHAIN (*ptr);
1362 start = TREE_CHAIN (attr);
1364 gcc_assert (!start || start == attrs);
1365 return start ? attrs : new_attrs;
1368 /* If VALUE is true, return the subset of ATTRS that affect type identity,
1369 otherwise return the subset of ATTRS that don't affect type identity. */
1371 tree
1372 affects_type_identity_attributes (tree attrs, bool value)
1374 auto predicate = [value](const_tree, const attribute_spec *as) -> bool
1376 return bool (as && as->affects_type_identity) == value;
1378 return remove_attributes_matching (attrs, predicate);
1381 /* Remove attributes that affect type identity from ATTRS unless the
1382 same attributes occur in OK_ATTRS. */
1384 tree
1385 restrict_type_identity_attributes_to (tree attrs, tree ok_attrs)
1387 auto predicate = [ok_attrs](const_tree attr,
1388 const attribute_spec *as) -> bool
1390 if (!as || !as->affects_type_identity)
1391 return true;
1393 for (tree ok_attr = lookup_attribute (as->name, ok_attrs);
1394 ok_attr;
1395 ok_attr = lookup_attribute (as->name, TREE_CHAIN (ok_attr)))
1396 if (simple_cst_equal (TREE_VALUE (ok_attr), TREE_VALUE (attr)) == 1)
1397 return true;
1399 return false;
1401 return remove_attributes_matching (attrs, predicate);
1404 /* Return a type like TTYPE except that its TYPE_ATTRIBUTE
1405 is ATTRIBUTE.
1407 Record such modified types already made so we don't make duplicates. */
1409 tree
1410 build_type_attribute_variant (tree ttype, tree attribute)
1412 return build_type_attribute_qual_variant (ttype, attribute,
1413 TYPE_QUALS (ttype));
1416 /* A variant of lookup_attribute() that can be used with an identifier
1417 as the first argument, and where the identifier can be either
1418 'text' or '__text__'.
1420 Given an attribute ATTR_IDENTIFIER, and a list of attributes LIST,
1421 return a pointer to the attribute's list element if the attribute
1422 is part of the list, or NULL_TREE if not found. If the attribute
1423 appears more than once, this only returns the first occurrence; the
1424 TREE_CHAIN of the return value should be passed back in if further
1425 occurrences are wanted. ATTR_IDENTIFIER must be an identifier but
1426 can be in the form 'text' or '__text__'. */
1427 static tree
1428 lookup_ident_attribute (tree attr_identifier, tree list)
1430 gcc_checking_assert (TREE_CODE (attr_identifier) == IDENTIFIER_NODE);
1432 while (list)
1434 gcc_checking_assert (TREE_CODE (get_attribute_name (list))
1435 == IDENTIFIER_NODE);
1437 if (cmp_attrib_identifiers (attr_identifier,
1438 get_attribute_name (list)))
1439 /* Found it. */
1440 break;
1441 list = TREE_CHAIN (list);
1444 return list;
1447 /* Remove any instances of attribute ATTR_NAME in LIST and return the
1448 modified list. */
1450 tree
1451 remove_attribute (const char *attr_name, tree list)
1453 tree *p;
1454 gcc_checking_assert (attr_name[0] != '_');
1456 for (p = &list; *p;)
1458 tree l = *p;
1460 tree attr = get_attribute_name (l);
1461 if (is_attribute_p (attr_name, attr))
1462 *p = TREE_CHAIN (l);
1463 else
1464 p = &TREE_CHAIN (l);
1467 return list;
1470 /* Return an attribute list that is the union of a1 and a2. */
1472 tree
1473 merge_attributes (tree a1, tree a2)
1475 tree attributes;
1477 /* Either one unset? Take the set one. */
1479 if ((attributes = a1) == 0)
1480 attributes = a2;
1482 /* One that completely contains the other? Take it. */
1484 else if (a2 != 0 && ! attribute_list_contained (a1, a2))
1486 if (attribute_list_contained (a2, a1))
1487 attributes = a2;
1488 else
1490 /* Pick the longest list, and hang on the other list. */
1492 if (list_length (a1) < list_length (a2))
1493 attributes = a2, a2 = a1;
1495 for (; a2 != 0; a2 = TREE_CHAIN (a2))
1497 tree a;
1498 for (a = lookup_ident_attribute (get_attribute_name (a2),
1499 attributes);
1500 a != NULL_TREE && !attribute_value_equal (a, a2);
1501 a = lookup_ident_attribute (get_attribute_name (a2),
1502 TREE_CHAIN (a)))
1504 if (a == NULL_TREE)
1506 a1 = copy_node (a2);
1507 TREE_CHAIN (a1) = attributes;
1508 attributes = a1;
1513 return attributes;
1516 /* Given types T1 and T2, merge their attributes and return
1517 the result. */
1519 tree
1520 merge_type_attributes (tree t1, tree t2)
1522 return merge_attributes (TYPE_ATTRIBUTES (t1),
1523 TYPE_ATTRIBUTES (t2));
1526 /* Given decls OLDDECL and NEWDECL, merge their attributes and return
1527 the result. */
1529 tree
1530 merge_decl_attributes (tree olddecl, tree newdecl)
1532 return merge_attributes (DECL_ATTRIBUTES (olddecl),
1533 DECL_ATTRIBUTES (newdecl));
1536 /* Duplicate all attributes with name NAME in ATTR list to *ATTRS if
1537 they are missing there. */
1539 void
1540 duplicate_one_attribute (tree *attrs, tree attr, const char *name)
1542 attr = lookup_attribute (name, attr);
1543 if (!attr)
1544 return;
1545 tree a = lookup_attribute (name, *attrs);
1546 while (attr)
1548 tree a2;
1549 for (a2 = a; a2; a2 = lookup_attribute (name, TREE_CHAIN (a2)))
1550 if (attribute_value_equal (attr, a2))
1551 break;
1552 if (!a2)
1554 a2 = copy_node (attr);
1555 TREE_CHAIN (a2) = *attrs;
1556 *attrs = a2;
1558 attr = lookup_attribute (name, TREE_CHAIN (attr));
1562 /* Duplicate all attributes from user DECL to the corresponding
1563 builtin that should be propagated. */
1565 void
1566 copy_attributes_to_builtin (tree decl)
1568 tree b = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
1569 if (b)
1570 duplicate_one_attribute (&DECL_ATTRIBUTES (b),
1571 DECL_ATTRIBUTES (decl), "omp declare simd");
1574 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1576 /* Specialization of merge_decl_attributes for various Windows targets.
1578 This handles the following situation:
1580 __declspec (dllimport) int foo;
1581 int foo;
1583 The second instance of `foo' nullifies the dllimport. */
1585 tree
1586 merge_dllimport_decl_attributes (tree old, tree new_tree)
1588 tree a;
1589 int delete_dllimport_p = 1;
1591 /* What we need to do here is remove from `old' dllimport if it doesn't
1592 appear in `new'. dllimport behaves like extern: if a declaration is
1593 marked dllimport and a definition appears later, then the object
1594 is not dllimport'd. We also remove a `new' dllimport if the old list
1595 contains dllexport: dllexport always overrides dllimport, regardless
1596 of the order of declaration. */
1597 if (!VAR_OR_FUNCTION_DECL_P (new_tree))
1598 delete_dllimport_p = 0;
1599 else if (DECL_DLLIMPORT_P (new_tree)
1600 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (old)))
1602 DECL_DLLIMPORT_P (new_tree) = 0;
1603 warning (OPT_Wattributes, "%q+D already declared with dllexport "
1604 "attribute: dllimport ignored", new_tree);
1606 else if (DECL_DLLIMPORT_P (old) && !DECL_DLLIMPORT_P (new_tree))
1608 /* Warn about overriding a symbol that has already been used, e.g.:
1609 extern int __attribute__ ((dllimport)) foo;
1610 int* bar () {return &foo;}
1611 int foo;
1613 if (TREE_USED (old))
1615 warning (0, "%q+D redeclared without dllimport attribute "
1616 "after being referenced with dll linkage", new_tree);
1617 /* If we have used a variable's address with dllimport linkage,
1618 keep the old DECL_DLLIMPORT_P flag: the ADDR_EXPR using the
1619 decl may already have had TREE_CONSTANT computed.
1620 We still remove the attribute so that assembler code refers
1621 to '&foo rather than '_imp__foo'. */
1622 if (VAR_P (old) && TREE_ADDRESSABLE (old))
1623 DECL_DLLIMPORT_P (new_tree) = 1;
1626 /* Let an inline definition silently override the external reference,
1627 but otherwise warn about attribute inconsistency. */
1628 else if (VAR_P (new_tree) || !DECL_DECLARED_INLINE_P (new_tree))
1629 warning (OPT_Wattributes, "%q+D redeclared without dllimport "
1630 "attribute: previous dllimport ignored", new_tree);
1632 else
1633 delete_dllimport_p = 0;
1635 a = merge_attributes (DECL_ATTRIBUTES (old), DECL_ATTRIBUTES (new_tree));
1637 if (delete_dllimport_p)
1638 a = remove_attribute ("dllimport", a);
1640 return a;
1643 /* Handle a "dllimport" or "dllexport" attribute; arguments as in
1644 struct attribute_spec.handler. */
1646 tree
1647 handle_dll_attribute (tree * pnode, tree name, tree args, int flags,
1648 bool *no_add_attrs)
1650 tree node = *pnode;
1651 bool is_dllimport;
1653 /* These attributes may apply to structure and union types being created,
1654 but otherwise should pass to the declaration involved. */
1655 if (!DECL_P (node))
1657 if (flags & ((int) ATTR_FLAG_DECL_NEXT | (int) ATTR_FLAG_FUNCTION_NEXT
1658 | (int) ATTR_FLAG_ARRAY_NEXT))
1660 *no_add_attrs = true;
1661 return tree_cons (name, args, NULL_TREE);
1663 if (TREE_CODE (node) == RECORD_TYPE
1664 || TREE_CODE (node) == UNION_TYPE)
1666 node = TYPE_NAME (node);
1667 if (!node)
1668 return NULL_TREE;
1670 else
1672 warning (OPT_Wattributes, "%qE attribute ignored",
1673 name);
1674 *no_add_attrs = true;
1675 return NULL_TREE;
1679 if (!VAR_OR_FUNCTION_DECL_P (node) && TREE_CODE (node) != TYPE_DECL)
1681 *no_add_attrs = true;
1682 warning (OPT_Wattributes, "%qE attribute ignored",
1683 name);
1684 return NULL_TREE;
1687 if (TREE_CODE (node) == TYPE_DECL
1688 && TREE_CODE (TREE_TYPE (node)) != RECORD_TYPE
1689 && TREE_CODE (TREE_TYPE (node)) != UNION_TYPE)
1691 *no_add_attrs = true;
1692 warning (OPT_Wattributes, "%qE attribute ignored",
1693 name);
1694 return NULL_TREE;
1697 is_dllimport = is_attribute_p ("dllimport", name);
1699 /* Report error on dllimport ambiguities seen now before they cause
1700 any damage. */
1701 if (is_dllimport)
1703 /* Honor any target-specific overrides. */
1704 if (!targetm.valid_dllimport_attribute_p (node))
1705 *no_add_attrs = true;
1707 else if (TREE_CODE (node) == FUNCTION_DECL
1708 && DECL_DECLARED_INLINE_P (node))
1710 warning (OPT_Wattributes, "inline function %q+D declared as "
1711 "dllimport: attribute ignored", node);
1712 *no_add_attrs = true;
1714 /* Like MS, treat definition of dllimported variables and
1715 non-inlined functions on declaration as syntax errors. */
1716 else if (TREE_CODE (node) == FUNCTION_DECL && DECL_INITIAL (node))
1718 error ("function %q+D definition is marked dllimport", node);
1719 *no_add_attrs = true;
1722 else if (VAR_P (node))
1724 if (DECL_INITIAL (node))
1726 error ("variable %q+D definition is marked dllimport",
1727 node);
1728 *no_add_attrs = true;
1731 /* `extern' needn't be specified with dllimport.
1732 Specify `extern' now and hope for the best. Sigh. */
1733 DECL_EXTERNAL (node) = 1;
1734 /* Also, implicitly give dllimport'd variables declared within
1735 a function global scope, unless declared static. */
1736 if (current_function_decl != NULL_TREE && !TREE_STATIC (node))
1737 TREE_PUBLIC (node) = 1;
1738 /* Clear TREE_STATIC because DECL_EXTERNAL is set, unless
1739 it is a C++ static data member. */
1740 if (DECL_CONTEXT (node) == NULL_TREE
1741 || !RECORD_OR_UNION_TYPE_P (DECL_CONTEXT (node)))
1742 TREE_STATIC (node) = 0;
1745 if (*no_add_attrs == false)
1746 DECL_DLLIMPORT_P (node) = 1;
1748 else if (TREE_CODE (node) == FUNCTION_DECL
1749 && DECL_DECLARED_INLINE_P (node)
1750 && flag_keep_inline_dllexport)
1751 /* An exported function, even if inline, must be emitted. */
1752 DECL_EXTERNAL (node) = 0;
1754 /* Report error if symbol is not accessible at global scope. */
1755 if (!TREE_PUBLIC (node) && VAR_OR_FUNCTION_DECL_P (node))
1757 error ("external linkage required for symbol %q+D because of "
1758 "%qE attribute", node, name);
1759 *no_add_attrs = true;
1762 /* A dllexport'd entity must have default visibility so that other
1763 program units (shared libraries or the main executable) can see
1764 it. A dllimport'd entity must have default visibility so that
1765 the linker knows that undefined references within this program
1766 unit can be resolved by the dynamic linker. */
1767 if (!*no_add_attrs)
1769 if (DECL_VISIBILITY_SPECIFIED (node)
1770 && DECL_VISIBILITY (node) != VISIBILITY_DEFAULT)
1771 error ("%qE implies default visibility, but %qD has already "
1772 "been declared with a different visibility",
1773 name, node);
1774 DECL_VISIBILITY (node) = VISIBILITY_DEFAULT;
1775 DECL_VISIBILITY_SPECIFIED (node) = 1;
1778 return NULL_TREE;
1781 #endif /* TARGET_DLLIMPORT_DECL_ATTRIBUTES */
1783 /* Given two lists of attributes, return true if list l2 is
1784 equivalent to l1. */
1787 attribute_list_equal (const_tree l1, const_tree l2)
1789 if (l1 == l2)
1790 return 1;
1792 return attribute_list_contained (l1, l2)
1793 && attribute_list_contained (l2, l1);
1796 /* Given two lists of attributes, return true if list L2 is
1797 completely contained within L1. */
1798 /* ??? This would be faster if attribute names were stored in a canonicalized
1799 form. Otherwise, if L1 uses `foo' and L2 uses `__foo__', the long method
1800 must be used to show these elements are equivalent (which they are). */
1801 /* ??? It's not clear that attributes with arguments will always be handled
1802 correctly. */
1805 attribute_list_contained (const_tree l1, const_tree l2)
1807 const_tree t1, t2;
1809 /* First check the obvious, maybe the lists are identical. */
1810 if (l1 == l2)
1811 return 1;
1813 /* Maybe the lists are similar. */
1814 for (t1 = l1, t2 = l2;
1815 t1 != 0 && t2 != 0
1816 && get_attribute_name (t1) == get_attribute_name (t2)
1817 && TREE_VALUE (t1) == TREE_VALUE (t2);
1818 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1821 /* Maybe the lists are equal. */
1822 if (t1 == 0 && t2 == 0)
1823 return 1;
1825 for (; t2 != 0; t2 = TREE_CHAIN (t2))
1827 const_tree attr;
1828 /* This CONST_CAST is okay because lookup_attribute does not
1829 modify its argument and the return value is assigned to a
1830 const_tree. */
1831 for (attr = lookup_ident_attribute (get_attribute_name (t2),
1832 CONST_CAST_TREE (l1));
1833 attr != NULL_TREE && !attribute_value_equal (t2, attr);
1834 attr = lookup_ident_attribute (get_attribute_name (t2),
1835 TREE_CHAIN (attr)))
1838 if (attr == NULL_TREE)
1839 return 0;
1842 return 1;
1845 /* The backbone of lookup_attribute(). ATTR_LEN is the string length
1846 of ATTR_NAME, and LIST is not NULL_TREE.
1848 The function is called from lookup_attribute in order to optimize
1849 for size. */
1851 tree
1852 private_lookup_attribute (const char *attr_name, size_t attr_len, tree list)
1854 while (list)
1856 tree attr = get_attribute_name (list);
1857 size_t ident_len = IDENTIFIER_LENGTH (attr);
1858 if (cmp_attribs (attr_name, attr_len, IDENTIFIER_POINTER (attr),
1859 ident_len))
1860 break;
1861 list = TREE_CHAIN (list);
1864 return list;
1867 /* Return true if the function decl or type NODE has been declared
1868 with attribute ANAME among attributes ATTRS. */
1870 static bool
1871 has_attribute (tree node, tree attrs, const char *aname)
1873 if (!strcmp (aname, "const"))
1875 if (DECL_P (node) && TREE_READONLY (node))
1876 return true;
1878 else if (!strcmp (aname, "malloc"))
1880 if (DECL_P (node) && DECL_IS_MALLOC (node))
1881 return true;
1883 else if (!strcmp (aname, "noreturn"))
1885 if (DECL_P (node) && TREE_THIS_VOLATILE (node))
1886 return true;
1888 else if (!strcmp (aname, "nothrow"))
1890 if (TREE_NOTHROW (node))
1891 return true;
1893 else if (!strcmp (aname, "pure"))
1895 if (DECL_P (node) && DECL_PURE_P (node))
1896 return true;
1899 return lookup_attribute (aname, attrs);
1902 /* Return the number of mismatched function or type attributes between
1903 the "template" function declaration TMPL and DECL. The word "template"
1904 doesn't necessarily refer to a C++ template but rather a declaration
1905 whose attributes should be matched by those on DECL. For a non-zero
1906 return value set *ATTRSTR to a string representation of the list of
1907 mismatched attributes with quoted names.
1908 ATTRLIST is a list of additional attributes that SPEC should be
1909 taken to ultimately be declared with. */
1911 unsigned
1912 decls_mismatched_attributes (tree tmpl, tree decl, tree attrlist,
1913 const char* const blacklist[],
1914 pretty_printer *attrstr)
1916 if (TREE_CODE (tmpl) != FUNCTION_DECL)
1917 return 0;
1919 /* Avoid warning if either declaration or its type is deprecated. */
1920 if (TREE_DEPRECATED (tmpl)
1921 || TREE_DEPRECATED (decl))
1922 return 0;
1924 const tree tmpls[] = { tmpl, TREE_TYPE (tmpl) };
1925 const tree decls[] = { decl, TREE_TYPE (decl) };
1927 if (TREE_DEPRECATED (tmpls[1])
1928 || TREE_DEPRECATED (decls[1])
1929 || TREE_DEPRECATED (TREE_TYPE (tmpls[1]))
1930 || TREE_DEPRECATED (TREE_TYPE (decls[1])))
1931 return 0;
1933 tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpls[1]) };
1934 tree decl_attrs[] = { DECL_ATTRIBUTES (decl), TYPE_ATTRIBUTES (decls[1]) };
1936 if (!decl_attrs[0])
1937 decl_attrs[0] = attrlist;
1938 else if (!decl_attrs[1])
1939 decl_attrs[1] = attrlist;
1941 /* Avoid warning if the template has no attributes. */
1942 if (!tmpl_attrs[0] && !tmpl_attrs[1])
1943 return 0;
1945 /* Avoid warning if either declaration contains an attribute on
1946 the white list below. */
1947 const char* const whitelist[] = {
1948 "error", "warning"
1951 for (unsigned i = 0; i != 2; ++i)
1952 for (unsigned j = 0; j != sizeof whitelist / sizeof *whitelist; ++j)
1953 if (lookup_attribute (whitelist[j], tmpl_attrs[i])
1954 || lookup_attribute (whitelist[j], decl_attrs[i]))
1955 return 0;
1957 /* Put together a list of the black-listed attributes that the template
1958 is declared with and the declaration is not, in case it's not apparent
1959 from the most recent declaration of the template. */
1960 unsigned nattrs = 0;
1962 for (unsigned i = 0; blacklist[i]; ++i)
1964 /* Attribute leaf only applies to extern functions. Avoid mentioning
1965 it when it's missing from a static declaration. */
1966 if (!TREE_PUBLIC (decl)
1967 && !strcmp ("leaf", blacklist[i]))
1968 continue;
1970 for (unsigned j = 0; j != 2; ++j)
1972 if (!has_attribute (tmpls[j], tmpl_attrs[j], blacklist[i]))
1973 continue;
1975 bool found = false;
1976 unsigned kmax = 1 + !!decl_attrs[1];
1977 for (unsigned k = 0; k != kmax; ++k)
1979 if (has_attribute (decls[k], decl_attrs[k], blacklist[i]))
1981 found = true;
1982 break;
1986 if (!found)
1988 if (nattrs)
1989 pp_string (attrstr, ", ");
1990 pp_begin_quote (attrstr, pp_show_color (global_dc->printer));
1991 pp_string (attrstr, blacklist[i]);
1992 pp_end_quote (attrstr, pp_show_color (global_dc->printer));
1993 ++nattrs;
1996 break;
2000 return nattrs;
2003 /* Issue a warning for the declaration ALIAS for TARGET where ALIAS
2004 specifies either attributes that are incompatible with those of
2005 TARGET, or attributes that are missing and that declaring ALIAS
2006 with would benefit. */
2008 void
2009 maybe_diag_alias_attributes (tree alias, tree target)
2011 /* Do not expect attributes to match between aliases and ifunc
2012 resolvers. There is no obvious correspondence between them. */
2013 if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (alias)))
2014 return;
2016 const char* const blacklist[] = {
2017 "alloc_align", "alloc_size", "cold", "const", "hot", "leaf", "malloc",
2018 "nonnull", "noreturn", "nothrow", "pure", "returns_nonnull",
2019 "returns_twice", NULL
2022 pretty_printer attrnames;
2023 if (warn_attribute_alias > 1)
2025 /* With -Wattribute-alias=2 detect alias declarations that are more
2026 restrictive than their targets first. Those indicate potential
2027 codegen bugs. */
2028 if (unsigned n = decls_mismatched_attributes (alias, target, NULL_TREE,
2029 blacklist, &attrnames))
2031 auto_diagnostic_group d;
2032 if (warning_n (DECL_SOURCE_LOCATION (alias),
2033 OPT_Wattribute_alias_, n,
2034 "%qD specifies more restrictive attribute than "
2035 "its target %qD: %s",
2036 "%qD specifies more restrictive attributes than "
2037 "its target %qD: %s",
2038 alias, target, pp_formatted_text (&attrnames)))
2039 inform (DECL_SOURCE_LOCATION (target),
2040 "%qD target declared here", alias);
2041 return;
2045 /* Detect alias declarations that are less restrictive than their
2046 targets. Those suggest potential optimization opportunities
2047 (solved by adding the missing attribute(s) to the alias). */
2048 if (unsigned n = decls_mismatched_attributes (target, alias, NULL_TREE,
2049 blacklist, &attrnames))
2051 auto_diagnostic_group d;
2052 if (warning_n (DECL_SOURCE_LOCATION (alias),
2053 OPT_Wmissing_attributes, n,
2054 "%qD specifies less restrictive attribute than "
2055 "its target %qD: %s",
2056 "%qD specifies less restrictive attributes than "
2057 "its target %qD: %s",
2058 alias, target, pp_formatted_text (&attrnames)))
2059 inform (DECL_SOURCE_LOCATION (target),
2060 "%qD target declared here", alias);
2064 /* Initialize a mapping RWM for a call to a function declared with
2065 attribute access in ATTRS. Each attribute positional operand
2066 inserts one entry into the mapping with the operand number as
2067 the key. */
2069 void
2070 init_attr_rdwr_indices (rdwr_map *rwm, tree attrs)
2072 if (!attrs)
2073 return;
2075 for (tree access = attrs;
2076 (access = lookup_attribute ("access", access));
2077 access = TREE_CHAIN (access))
2079 /* The TREE_VALUE of an attribute is a TREE_LIST whose TREE_VALUE
2080 is the attribute argument's value. */
2081 tree mode = TREE_VALUE (access);
2082 if (!mode)
2083 return;
2085 /* The (optional) list of VLA bounds. */
2086 tree vblist = TREE_CHAIN (mode);
2087 mode = TREE_VALUE (mode);
2088 if (TREE_CODE (mode) != STRING_CST)
2089 continue;
2090 gcc_assert (TREE_CODE (mode) == STRING_CST);
2092 if (vblist)
2093 vblist = nreverse (copy_list (TREE_VALUE (vblist)));
2095 for (const char *m = TREE_STRING_POINTER (mode); *m; )
2097 attr_access acc = { };
2099 /* Skip the internal-only plus sign. */
2100 if (*m == '+')
2101 ++m;
2103 acc.str = m;
2104 acc.mode = acc.from_mode_char (*m);
2105 acc.sizarg = UINT_MAX;
2107 const char *end;
2108 acc.ptrarg = strtoul (++m, const_cast<char**>(&end), 10);
2109 m = end;
2111 if (*m == '[')
2113 /* Forms containing the square bracket are internal-only
2114 (not specified by an attribute declaration), and used
2115 for various forms of array and VLA parameters. */
2116 acc.internal_p = true;
2118 /* Search to the closing bracket and look at the preceding
2119 code: it determines the form of the most significant
2120 bound of the array. Others prior to it encode the form
2121 of interior VLA bounds. They're not of interest here. */
2122 end = strchr (m, ']');
2123 const char *p = end;
2124 gcc_assert (p);
2126 while (ISDIGIT (p[-1]))
2127 --p;
2129 if (ISDIGIT (*p))
2131 /* A digit denotes a constant bound (as in T[3]). */
2132 acc.static_p = p[-1] == 's';
2133 acc.minsize = strtoull (p, NULL, 10);
2135 else if (' ' == p[-1])
2137 /* A space denotes an ordinary array of unspecified bound
2138 (as in T[]). */
2139 acc.minsize = 0;
2141 else if ('*' == p[-1] || '$' == p[-1])
2143 /* An asterisk denotes a VLA. When the closing bracket
2144 is followed by a comma and a dollar sign its bound is
2145 on the list. Otherwise it's a VLA with an unspecified
2146 bound. */
2147 acc.static_p = p[-2] == 's';
2148 acc.minsize = HOST_WIDE_INT_M1U;
2151 m = end + 1;
2154 if (*m == ',')
2156 ++m;
2159 if (*m == '$')
2161 ++m;
2162 if (!acc.size && vblist)
2164 /* Extract the list of VLA bounds for the current
2165 parameter, store it in ACC.SIZE, and advance
2166 to the list of bounds for the next VLA parameter.
2168 acc.size = TREE_VALUE (vblist);
2169 vblist = TREE_CHAIN (vblist);
2173 if (ISDIGIT (*m))
2175 /* Extract the positional argument. It's absent
2176 for VLAs whose bound doesn't name a function
2177 parameter. */
2178 unsigned pos = strtoul (m, const_cast<char**>(&end), 10);
2179 if (acc.sizarg == UINT_MAX)
2180 acc.sizarg = pos;
2181 m = end;
2184 while (*m == '$');
2187 acc.end = m;
2189 bool existing;
2190 auto &ref = rwm->get_or_insert (acc.ptrarg, &existing);
2191 if (existing)
2193 /* Merge the new spec with the existing. */
2194 if (acc.minsize == HOST_WIDE_INT_M1U)
2195 ref.minsize = HOST_WIDE_INT_M1U;
2197 if (acc.sizarg != UINT_MAX)
2198 ref.sizarg = acc.sizarg;
2200 if (acc.mode)
2201 ref.mode = acc.mode;
2203 else
2204 ref = acc;
2206 /* Unconditionally add an entry for the required pointer
2207 operand of the attribute, and one for the optional size
2208 operand when it's specified. */
2209 if (acc.sizarg != UINT_MAX)
2210 rwm->put (acc.sizarg, acc);
2215 /* Return the access specification for a function parameter PARM
2216 or null if the current function has no such specification. */
2218 attr_access *
2219 get_parm_access (rdwr_map &rdwr_idx, tree parm,
2220 tree fndecl /* = current_function_decl */)
2222 tree fntype = TREE_TYPE (fndecl);
2223 init_attr_rdwr_indices (&rdwr_idx, TYPE_ATTRIBUTES (fntype));
2225 if (rdwr_idx.is_empty ())
2226 return NULL;
2228 unsigned argpos = 0;
2229 tree fnargs = DECL_ARGUMENTS (fndecl);
2230 for (tree arg = fnargs; arg; arg = TREE_CHAIN (arg), ++argpos)
2231 if (arg == parm)
2232 return rdwr_idx.get (argpos);
2234 return NULL;
2237 /* Return the internal representation as STRING_CST. Internal positional
2238 arguments are zero-based. */
2240 tree
2241 attr_access::to_internal_string () const
2243 return build_string (end - str, str);
2246 /* Return the human-readable representation of the external attribute
2247 specification (as it might appear in the source code) as STRING_CST.
2248 External positional arguments are one-based. */
2250 tree
2251 attr_access::to_external_string () const
2253 char buf[80];
2254 gcc_assert (mode != access_deferred);
2255 int len = snprintf (buf, sizeof buf, "access (%s, %u",
2256 mode_names[mode], ptrarg + 1);
2257 if (sizarg != UINT_MAX)
2258 len += snprintf (buf + len, sizeof buf - len, ", %u", sizarg + 1);
2259 strcpy (buf + len, ")");
2260 return build_string (len + 2, buf);
2263 /* Return the number of specified VLA bounds and set *nunspec to
2264 the number of unspecified ones (those designated by [*]). */
2266 unsigned
2267 attr_access::vla_bounds (unsigned *nunspec) const
2269 unsigned nbounds = 0;
2270 *nunspec = 0;
2271 /* STR points to the beginning of the specified string for the current
2272 argument that may be followed by the string for the next argument. */
2273 for (const char* p = strchr (str, ']'); p && *p != '['; --p)
2275 if (*p == '*')
2276 ++*nunspec;
2277 else if (*p == '$')
2278 ++nbounds;
2280 return nbounds;
2283 /* Reset front end-specific attribute access data from ATTRS.
2284 Called from the free_lang_data pass. */
2286 /* static */ void
2287 attr_access::free_lang_data (tree attrs)
2289 for (tree acs = attrs; (acs = lookup_attribute ("access", acs));
2290 acs = TREE_CHAIN (acs))
2292 tree vblist = TREE_VALUE (acs);
2293 vblist = TREE_CHAIN (vblist);
2294 if (!vblist)
2295 continue;
2297 for (vblist = TREE_VALUE (vblist); vblist; vblist = TREE_CHAIN (vblist))
2299 tree *pvbnd = &TREE_VALUE (vblist);
2300 if (!*pvbnd || DECL_P (*pvbnd))
2301 continue;
2303 /* VLA bounds that are expressions as opposed to DECLs are
2304 only used in the front end. Reset them to keep front end
2305 trees leaking into the middle end (see pr97172) and to
2306 free up memory. */
2307 *pvbnd = NULL_TREE;
2311 for (tree argspec = attrs; (argspec = lookup_attribute ("arg spec", argspec));
2312 argspec = TREE_CHAIN (argspec))
2314 /* Same as above. */
2315 tree *pvblist = &TREE_VALUE (argspec);
2316 *pvblist = NULL_TREE;
2320 /* Defined in attr_access. */
2321 constexpr char attr_access::mode_chars[];
2322 constexpr char attr_access::mode_names[][11];
2324 /* Format an array, including a VLA, pointed to by TYPE and used as
2325 a function parameter as a human-readable string. ACC describes
2326 an access to the parameter and is used to determine the outermost
2327 form of the array including its bound which is otherwise obviated
2328 by its decay to pointer. Return the formatted string. */
2330 std::string
2331 attr_access::array_as_string (tree type) const
2333 std::string typstr;
2335 if (type == error_mark_node)
2336 return std::string ();
2338 if (this->str)
2340 /* For array parameters (but not pointers) create a temporary array
2341 type that corresponds to the form of the parameter including its
2342 qualifiers even though they apply to the pointer, not the array
2343 type. */
2344 const bool vla_p = minsize == HOST_WIDE_INT_M1U;
2345 tree eltype = TREE_TYPE (type);
2346 tree index_type = NULL_TREE;
2348 if (minsize == HOST_WIDE_INT_M1U)
2350 /* Determine if this is a VLA (an array whose most significant
2351 bound is nonconstant and whose access string has "$]" in it)
2352 extract the bound expression from SIZE. */
2353 const char *p = end;
2354 for ( ; p != str && *p-- != ']'; );
2355 if (*p == '$')
2356 /* SIZE may have been cleared. Use it with care. */
2357 index_type = build_index_type (size ? TREE_VALUE (size) : size);
2359 else if (minsize)
2360 index_type = build_index_type (size_int (minsize - 1));
2362 tree arat = NULL_TREE;
2363 if (static_p || vla_p)
2365 tree flag = static_p ? integer_one_node : NULL_TREE;
2366 /* Hack: there's no language-independent way to encode
2367 the "static" specifier or the "*" notation in an array type.
2368 Add a "fake" attribute to have the pretty-printer add "static"
2369 or "*". The "[static N]" notation is only valid in the most
2370 significant bound but [*] can be used for any bound. Because
2371 [*] is represented the same as [0] this hack only works for
2372 the most significant bound like static and the others are
2373 rendered as [0]. */
2374 arat = build_tree_list (get_identifier ("array"), flag);
2377 const int quals = TYPE_QUALS (type);
2378 type = build_array_type (eltype, index_type);
2379 type = build_type_attribute_qual_variant (type, arat, quals);
2382 /* Format the type using the current pretty printer. The generic tree
2383 printer does a terrible job. */
2384 pretty_printer *pp = global_dc->printer->clone ();
2385 pp_printf (pp, "%qT", type);
2386 typstr = pp_formatted_text (pp);
2387 delete pp;
2389 return typstr;
2392 #if CHECKING_P
2394 namespace selftest
2397 /* Helper types to verify the consistency attribute exclusions. */
2399 typedef std::pair<const char *, const char *> excl_pair;
2401 struct excl_hash_traits: typed_noop_remove<excl_pair>
2403 typedef excl_pair value_type;
2404 typedef value_type compare_type;
2406 static hashval_t hash (const value_type &x)
2408 hashval_t h1 = htab_hash_string (x.first);
2409 hashval_t h2 = htab_hash_string (x.second);
2410 return h1 ^ h2;
2413 static bool equal (const value_type &x, const value_type &y)
2415 return !strcmp (x.first, y.first) && !strcmp (x.second, y.second);
2418 static void mark_deleted (value_type &x)
2420 x = value_type (NULL, NULL);
2423 static const bool empty_zero_p = false;
2425 static void mark_empty (value_type &x)
2427 x = value_type ("", "");
2430 static bool is_deleted (const value_type &x)
2432 return !x.first && !x.second;
2435 static bool is_empty (const value_type &x)
2437 return !*x.first && !*x.second;
2442 /* Self-test to verify that each attribute exclusion is symmetric,
2443 meaning that if attribute A is encoded as incompatible with
2444 attribute B then the opposite relationship is also encoded.
2445 This test also detects most cases of misspelled attribute names
2446 in exclusions. */
2448 static void
2449 test_attribute_exclusions ()
2451 /* Iterate over the array of attribute tables first (with TI0 as
2452 the index) and over the array of attribute_spec in each table
2453 (with SI0 as the index). */
2454 const size_t ntables = ARRAY_SIZE (attribute_tables);
2456 /* Set of pairs of mutually exclusive attributes. */
2457 typedef hash_set<excl_pair, false, excl_hash_traits> exclusion_set;
2458 exclusion_set excl_set;
2460 for (size_t ti0 = 0; ti0 != ntables; ++ti0)
2461 for (size_t s0 = 0; attribute_tables[ti0][s0].name; ++s0)
2463 const attribute_spec::exclusions *excl
2464 = attribute_tables[ti0][s0].exclude;
2466 /* Skip each attribute that doesn't define exclusions. */
2467 if (!excl)
2468 continue;
2470 const char *attr_name = attribute_tables[ti0][s0].name;
2472 /* Iterate over the set of exclusions for every attribute
2473 (with EI0 as the index) adding the exclusions defined
2474 for each to the set. */
2475 for (size_t ei0 = 0; excl[ei0].name; ++ei0)
2477 const char *excl_name = excl[ei0].name;
2479 if (!strcmp (attr_name, excl_name))
2480 continue;
2482 excl_set.add (excl_pair (attr_name, excl_name));
2486 /* Traverse the set of mutually exclusive pairs of attributes
2487 and verify that they are symmetric. */
2488 for (exclusion_set::iterator it = excl_set.begin ();
2489 it != excl_set.end ();
2490 ++it)
2492 if (!excl_set.contains (excl_pair ((*it).second, (*it).first)))
2494 /* An exclusion for an attribute has been found that
2495 doesn't have a corresponding exclusion in the opposite
2496 direction. */
2497 char desc[120];
2498 sprintf (desc, "'%s' attribute exclusion '%s' must be symmetric",
2499 (*it).first, (*it).second);
2500 fail (SELFTEST_LOCATION, desc);
2505 void
2506 attribute_c_tests ()
2508 test_attribute_exclusions ();
2511 } /* namespace selftest */
2513 #endif /* CHECKING_P */