c++: fix throwing cleanup with label
[official-gcc.git] / gcc / cp / constraint.cc
blob8cf0f2d097465aa6c0a49512da8cbcb789eae9de
1 /* Processing rules for constraints.
2 Copyright (C) 2013-2023 Free Software Foundation, Inc.
3 Contributed by Andrew Sutton (andrew.n.sutton@gmail.com)
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "timevar.h"
26 #include "hash-set.h"
27 #include "machmode.h"
28 #include "vec.h"
29 #include "double-int.h"
30 #include "input.h"
31 #include "alias.h"
32 #include "symtab.h"
33 #include "wide-int.h"
34 #include "inchash.h"
35 #include "tree.h"
36 #include "stringpool.h"
37 #include "attribs.h"
38 #include "intl.h"
39 #include "flags.h"
40 #include "cp-tree.h"
41 #include "c-family/c-common.h"
42 #include "c-family/c-objc.h"
43 #include "cp-objcp-common.h"
44 #include "tree-inline.h"
45 #include "decl.h"
46 #include "toplev.h"
47 #include "type-utils.h"
49 static tree satisfaction_value (tree t);
51 /* When we're parsing or substuting a constraint expression, we have slightly
52 different expression semantics. In particular, we don't want to reduce a
53 concept-id to a satisfaction value. */
55 processing_constraint_expression_sentinel::
56 processing_constraint_expression_sentinel ()
58 ++scope_chain->x_processing_constraint;
61 processing_constraint_expression_sentinel::
62 ~processing_constraint_expression_sentinel ()
64 --scope_chain->x_processing_constraint;
67 bool
68 processing_constraint_expression_p ()
70 return scope_chain->x_processing_constraint != 0;
73 /*---------------------------------------------------------------------------
74 Constraint expressions
75 ---------------------------------------------------------------------------*/
77 /* Information provided to substitution. */
79 struct subst_info
81 subst_info (tsubst_flags_t cmp, tree in)
82 : complain (cmp), in_decl (in)
83 { }
85 /* True if we should not diagnose errors. */
86 bool quiet() const
88 return complain == tf_none;
91 /* True if we should diagnose errors. */
92 bool noisy() const
94 return !quiet ();
97 tsubst_flags_t complain;
98 tree in_decl;
101 /* Provides additional context for satisfaction.
103 During satisfaction:
104 - The flag noisy() controls whether to diagnose ill-formed satisfaction,
105 such as the satisfaction value of an atom being non-bool or non-constant.
106 - The flag diagnose_unsatisfaction_p() controls whether to additionally
107 explain why a constraint is not satisfied.
108 - We enter satisfaction with noisy+unsat from diagnose_constraints.
109 - We enter satisfaction with noisy-unsat from the replay inside
110 constraint_satisfaction_value.
111 - We enter satisfaction quietly (both flags cleared) from
112 constraints_satisfied_p.
114 During evaluation of a requires-expression:
115 - The flag noisy() controls whether to diagnose ill-formed types and
116 expressions inside its requirements.
117 - The flag diagnose_unsatisfaction_p() controls whether to additionally
118 explain why the requires-expression evaluates to false.
119 - We enter tsubst_requires_expr with noisy+unsat from
120 diagnose_atomic_constraint and potentially from
121 satisfy_nondeclaration_constraints.
122 - We enter tsubst_requires_expr with noisy-unsat from
123 cp_parser_requires_expression when processing a requires-expression that
124 appears outside a template.
125 - We enter tsubst_requires_expr quietly (both flags cleared) when
126 substituting through a requires-expression as part of template
127 instantiation. */
129 struct sat_info : subst_info
131 sat_info (tsubst_flags_t cmp, tree in, bool diag_unsat = false)
132 : subst_info (cmp, in), diagnose_unsatisfaction (diag_unsat)
134 if (diagnose_unsatisfaction_p ())
135 gcc_checking_assert (noisy ());
138 /* True if we should diagnose the cause of satisfaction failure.
139 Implies noisy(). */
140 bool
141 diagnose_unsatisfaction_p () const
143 return diagnose_unsatisfaction;
146 bool diagnose_unsatisfaction;
149 static tree constraint_satisfaction_value (tree, tree, sat_info);
151 /* True if T is known to be some type other than bool. Note that this
152 is false for dependent types and errors. */
154 static inline bool
155 known_non_bool_p (tree t)
157 return (t && !WILDCARD_TYPE_P (t) && TREE_CODE (t) != BOOLEAN_TYPE);
160 static bool
161 check_constraint_atom (cp_expr expr)
163 if (known_non_bool_p (TREE_TYPE (expr)))
165 error_at (expr.get_location (),
166 "constraint expression does not have type %<bool%>");
167 return false;
170 /* Check that we're using function concepts correctly. */
171 if (concept_check_p (expr))
173 tree id = unpack_concept_check (expr);
174 tree tmpl = TREE_OPERAND (id, 0);
175 if (OVL_P (tmpl) && TREE_CODE (expr) == TEMPLATE_ID_EXPR)
177 error_at (EXPR_LOC_OR_LOC (expr, input_location),
178 "function concept must be called");
179 return false;
183 return true;
186 static bool
187 check_constraint_operands (location_t, cp_expr lhs, cp_expr rhs)
189 return check_constraint_atom (lhs) && check_constraint_atom (rhs);
192 /* Validate the semantic properties of the constraint expression. */
194 static cp_expr
195 finish_constraint_binary_op (location_t loc,
196 tree_code code,
197 cp_expr lhs,
198 cp_expr rhs)
200 gcc_assert (processing_constraint_expression_p ());
201 if (lhs == error_mark_node || rhs == error_mark_node)
202 return error_mark_node;
203 if (!check_constraint_operands (loc, lhs, rhs))
204 return error_mark_node;
205 cp_expr expr
206 = build_min_nt_loc (loc, code, lhs.get_value (), rhs.get_value ());
207 expr.set_range (lhs.get_start (), rhs.get_finish ());
208 return expr;
211 cp_expr
212 finish_constraint_or_expr (location_t loc, cp_expr lhs, cp_expr rhs)
214 return finish_constraint_binary_op (loc, TRUTH_ORIF_EXPR, lhs, rhs);
217 cp_expr
218 finish_constraint_and_expr (location_t loc, cp_expr lhs, cp_expr rhs)
220 return finish_constraint_binary_op (loc, TRUTH_ANDIF_EXPR, lhs, rhs);
223 cp_expr
224 finish_constraint_primary_expr (cp_expr expr)
226 if (expr == error_mark_node)
227 return error_mark_node;
228 if (!check_constraint_atom (expr))
229 return cp_expr (error_mark_node, expr.get_location ());
230 return expr;
233 /* Combine two constraint-expressions with a logical-and. */
235 tree
236 combine_constraint_expressions (tree lhs, tree rhs)
238 processing_constraint_expression_sentinel pce;
239 if (!lhs)
240 return rhs;
241 if (!rhs)
242 return lhs;
243 return finish_constraint_and_expr (input_location, lhs, rhs);
246 /* Extract the template-id from a concept check. For standard and variable
247 checks, this is simply T. For function concept checks, this is the
248 called function. */
250 tree
251 unpack_concept_check (tree t)
253 gcc_assert (concept_check_p (t));
255 if (TREE_CODE (t) == CALL_EXPR)
256 t = CALL_EXPR_FN (t);
258 gcc_assert (TREE_CODE (t) == TEMPLATE_ID_EXPR);
259 return t;
262 /* Extract the TEMPLATE_DECL from a concept check. */
264 tree
265 get_concept_check_template (tree t)
267 tree id = unpack_concept_check (t);
268 tree tmpl = TREE_OPERAND (id, 0);
269 if (OVL_P (tmpl))
270 tmpl = OVL_FIRST (tmpl);
271 return tmpl;
274 /*---------------------------------------------------------------------------
275 Resolution of qualified concept names
276 ---------------------------------------------------------------------------*/
278 /* This facility is used to resolve constraint checks from requirement
279 expressions. A constraint check is a call to a function template declared
280 with the keyword 'concept'.
282 The result of resolution is a pair (a TREE_LIST) whose value is the
283 matched declaration, and whose purpose contains the coerced template
284 arguments that can be substituted into the call. */
286 /* Given an overload set OVL, try to find a unique definition that can be
287 instantiated by the template arguments ARGS.
289 This function is not called for arbitrary call expressions. In particular,
290 the call expression must be written with explicit template arguments
291 and no function arguments. For example:
293 f<T, U>()
295 If a single match is found, this returns a TREE_LIST whose VALUE
296 is the constraint function (not the template), and its PURPOSE is
297 the complete set of arguments substituted into the parameter list. */
299 static tree
300 resolve_function_concept_overload (tree ovl, tree args)
302 int nerrs = 0;
303 tree cands = NULL_TREE;
304 for (lkp_iterator iter (ovl); iter; ++iter)
306 tree tmpl = *iter;
307 if (TREE_CODE (tmpl) != TEMPLATE_DECL)
308 continue;
310 /* Don't try to deduce checks for non-concepts. We often end up trying
311 to resolve constraints in functional casts as part of a
312 postfix-expression. We can save time and headaches by not
313 instantiating those declarations.
315 NOTE: This masks a potential error, caused by instantiating
316 non-deduced contexts using placeholder arguments. */
317 tree fn = DECL_TEMPLATE_RESULT (tmpl);
318 if (DECL_ARGUMENTS (fn))
319 continue;
320 if (!DECL_DECLARED_CONCEPT_P (fn))
321 continue;
323 /* Remember the candidate if we can deduce a substitution. */
324 ++processing_template_decl;
325 tree parms = TREE_VALUE (DECL_TEMPLATE_PARMS (tmpl));
326 if (tree subst = coerce_template_parms (parms, args, tmpl, tf_none))
328 if (subst == error_mark_node)
329 ++nerrs;
330 else
331 cands = tree_cons (subst, fn, cands);
333 --processing_template_decl;
336 if (!cands)
337 /* We either had no candidates or failed deductions. */
338 return nerrs ? error_mark_node : NULL_TREE;
339 else if (TREE_CHAIN (cands))
340 /* There are multiple candidates. */
341 return error_mark_node;
343 return cands;
346 /* Determine if the call expression CALL is a constraint check, and
347 return the concept declaration and arguments being checked. If CALL
348 does not denote a constraint check, return NULL. */
350 tree
351 resolve_function_concept_check (tree call)
353 gcc_assert (TREE_CODE (call) == CALL_EXPR);
355 /* A constraint check must be only a template-id expression.
356 If it's a call to a base-link, its function(s) should be a
357 template-id expression. If this is not a template-id, then
358 it cannot be a concept-check. */
359 tree target = CALL_EXPR_FN (call);
360 if (BASELINK_P (target))
361 target = BASELINK_FUNCTIONS (target);
362 if (TREE_CODE (target) != TEMPLATE_ID_EXPR)
363 return NULL_TREE;
365 /* Get the overload set and template arguments and try to
366 resolve the target. */
367 tree ovl = TREE_OPERAND (target, 0);
369 /* This is a function call of a variable concept... ill-formed. */
370 if (TREE_CODE (ovl) == TEMPLATE_DECL)
372 error_at (location_of (call),
373 "function call of variable concept %qE", call);
374 return error_mark_node;
377 tree args = TREE_OPERAND (target, 1);
378 return resolve_function_concept_overload (ovl, args);
381 /* Returns a pair containing the checked concept and its associated
382 prototype parameter. The result is a TREE_LIST whose TREE_VALUE
383 is the concept (non-template) and whose TREE_PURPOSE contains
384 the converted template arguments, including the deduced prototype
385 parameter (in position 0). */
387 tree
388 resolve_concept_check (tree check)
390 gcc_assert (concept_check_p (check));
391 tree id = unpack_concept_check (check);
392 tree tmpl = TREE_OPERAND (id, 0);
394 /* If this is an overloaded function concept, perform overload
395 resolution (this only happens when deducing prototype parameters
396 and template introductions). */
397 if (TREE_CODE (tmpl) == OVERLOAD)
399 if (OVL_CHAIN (tmpl))
400 return resolve_function_concept_check (check);
401 tmpl = OVL_FIRST (tmpl);
404 tree args = TREE_OPERAND (id, 1);
405 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
406 ++processing_template_decl;
407 tree result = coerce_template_parms (parms, args, tmpl, tf_none);
408 --processing_template_decl;
409 if (result == error_mark_node)
410 return error_mark_node;
411 return build_tree_list (result, DECL_TEMPLATE_RESULT (tmpl));
414 /* Given a call expression or template-id expression to a concept EXPR
415 possibly including a wildcard, deduce the concept being checked and
416 the prototype parameter. Returns true if the constraint and prototype
417 can be deduced and false otherwise. Note that the CHECK and PROTO
418 arguments are set to NULL_TREE if this returns false. */
420 bool
421 deduce_constrained_parameter (tree expr, tree& check, tree& proto)
423 tree info = resolve_concept_check (expr);
424 if (info && info != error_mark_node)
426 check = TREE_VALUE (info);
427 tree arg = TREE_VEC_ELT (TREE_PURPOSE (info), 0);
428 if (ARGUMENT_PACK_P (arg))
429 arg = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg), 0);
430 proto = TREE_TYPE (arg);
431 return true;
434 check = proto = NULL_TREE;
435 return false;
438 /* Given a call expression or template-id expression to a concept, EXPR,
439 deduce the concept being checked and return the template arguments.
440 Returns NULL_TREE if deduction fails. */
441 static tree
442 deduce_concept_introduction (tree check)
444 tree info = resolve_concept_check (check);
445 if (info && info != error_mark_node)
446 return TREE_PURPOSE (info);
447 return NULL_TREE;
450 /* Build a constrained placeholder type where SPEC is a type-constraint.
451 SPEC can be anything were concept_definition_p is true.
453 Returns a pair whose FIRST is the concept being checked and whose
454 SECOND is the prototype parameter. */
456 tree_pair
457 finish_type_constraints (tree spec, tree args, tsubst_flags_t complain)
459 gcc_assert (concept_definition_p (spec));
461 /* Build an initial concept check. */
462 tree check = build_type_constraint (spec, args, complain);
463 if (check == error_mark_node)
464 return std::make_pair (error_mark_node, NULL_TREE);
466 /* Extract the concept and prototype parameter from the check. */
467 tree con;
468 tree proto;
469 if (!deduce_constrained_parameter (check, con, proto))
470 return std::make_pair (error_mark_node, NULL_TREE);
472 return std::make_pair (con, proto);
475 /*---------------------------------------------------------------------------
476 Expansion of concept definitions
477 ---------------------------------------------------------------------------*/
479 /* Returns the expression of a function concept. */
481 static tree
482 get_returned_expression (tree fn)
484 /* Extract the body of the function minus the return expression. */
485 tree body = DECL_SAVED_TREE (fn);
486 if (!body)
487 return error_mark_node;
488 if (TREE_CODE (body) == BIND_EXPR)
489 body = BIND_EXPR_BODY (body);
490 if (TREE_CODE (body) != RETURN_EXPR)
491 return error_mark_node;
493 return TREE_OPERAND (body, 0);
496 /* Returns the initializer of a variable concept. */
498 static tree
499 get_variable_initializer (tree var)
501 tree init = DECL_INITIAL (var);
502 if (!init)
503 return error_mark_node;
504 if (BRACE_ENCLOSED_INITIALIZER_P (init)
505 && CONSTRUCTOR_NELTS (init) == 1)
506 init = CONSTRUCTOR_ELT (init, 0)->value;
507 return init;
510 /* Returns the definition of a variable or function concept. */
512 static tree
513 get_concept_definition (tree decl)
515 if (TREE_CODE (decl) == OVERLOAD)
516 decl = OVL_FIRST (decl);
518 if (TREE_CODE (decl) == TEMPLATE_DECL)
519 decl = DECL_TEMPLATE_RESULT (decl);
521 if (TREE_CODE (decl) == CONCEPT_DECL)
522 return DECL_INITIAL (decl);
523 if (VAR_P (decl))
524 return get_variable_initializer (decl);
525 if (TREE_CODE (decl) == FUNCTION_DECL)
526 return get_returned_expression (decl);
527 gcc_unreachable ();
530 /*---------------------------------------------------------------------------
531 Normalization of expressions
533 This set of functions will transform an expression into a constraint
534 in a sequence of steps.
535 ---------------------------------------------------------------------------*/
537 void
538 debug_parameter_mapping (tree map)
540 for (tree p = map; p; p = TREE_CHAIN (p))
542 tree parm = TREE_VALUE (p);
543 tree arg = TREE_PURPOSE (p);
544 if (TYPE_P (parm))
545 verbatim ("MAP %qD TO %qT", TEMPLATE_TYPE_DECL (parm), arg);
546 else
547 verbatim ("MAP %qD TO %qE", TEMPLATE_PARM_DECL (parm), arg);
548 // debug_tree (parm);
549 // debug_tree (arg);
553 void
554 debug_argument_list (tree args)
556 for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
558 tree arg = TREE_VEC_ELT (args, i);
559 if (TYPE_P (arg))
560 verbatim ("argument %qT", arg);
561 else
562 verbatim ("argument %qE", arg);
566 /* Associate each parameter in PARMS with its corresponding template
567 argument in ARGS. */
569 static tree
570 map_arguments (tree parms, tree args)
572 for (tree p = parms; p; p = TREE_CHAIN (p))
573 if (args)
575 int level;
576 int index;
577 template_parm_level_and_index (TREE_VALUE (p), &level, &index);
578 TREE_PURPOSE (p) = TMPL_ARG (args, level, index);
580 else
581 TREE_PURPOSE (p) = template_parm_to_arg (p);
583 return parms;
586 /* Build the parameter mapping for EXPR using ARGS, where CTX_PARMS
587 are the template parameters in scope for EXPR. */
589 static tree
590 build_parameter_mapping (tree expr, tree args, tree ctx_parms)
592 tree parms = find_template_parameters (expr, ctx_parms);
593 tree map = map_arguments (parms, args);
594 return map;
597 /* True if the parameter mappings of two atomic constraints formed
598 from the same expression are equivalent. */
600 static bool
601 parameter_mapping_equivalent_p (tree t1, tree t2)
603 tree map1 = ATOMIC_CONSTR_MAP (t1);
604 tree map2 = ATOMIC_CONSTR_MAP (t2);
605 while (map1 && map2)
607 gcc_checking_assert (TREE_VALUE (map1) == TREE_VALUE (map2));
608 tree arg1 = TREE_PURPOSE (map1);
609 tree arg2 = TREE_PURPOSE (map2);
610 if (!template_args_equal (arg1, arg2))
611 return false;
612 map1 = TREE_CHAIN (map1);
613 map2 = TREE_CHAIN (map2);
615 gcc_checking_assert (!map1 && !map2);
616 return true;
619 /* Provides additional context for normalization. */
621 struct norm_info : subst_info
623 explicit norm_info (tsubst_flags_t cmp)
624 : norm_info (NULL_TREE, cmp)
627 /* Construct a top-level context for DECL. */
629 norm_info (tree in_decl, tsubst_flags_t complain)
630 : subst_info (tf_warning_or_error | complain, in_decl)
632 if (in_decl)
634 initial_parms = DECL_TEMPLATE_PARMS (in_decl);
635 if (generate_diagnostics ())
636 context = build_tree_list (NULL_TREE, in_decl);
638 else
639 initial_parms = current_template_parms;
642 bool generate_diagnostics() const
644 return complain & tf_norm;
647 void update_context(tree expr, tree args)
649 if (generate_diagnostics ())
651 tree map = build_parameter_mapping (expr, args, ctx_parms ());
652 context = tree_cons (map, expr, context);
654 in_decl = get_concept_check_template (expr);
657 /* Returns the template parameters that are in scope for the current
658 normalization context. */
660 tree ctx_parms()
662 if (in_decl)
663 return DECL_TEMPLATE_PARMS (in_decl);
664 else
665 return initial_parms;
668 /* Provides information about the source of a constraint. This is a
669 TREE_LIST whose VALUE is either a concept check or a constrained
670 declaration. The PURPOSE, for concept checks is a parameter mapping
671 for that check. */
673 tree context = NULL_TREE;
675 /* The declaration whose constraints we're normalizing. The targets
676 of the parameter mapping of each atom will be in terms of the
677 template parameters of ORIG_DECL. */
679 tree initial_parms = NULL_TREE;
682 static tree normalize_expression (tree, tree, norm_info);
684 /* Transform a logical-or or logical-and expression into either
685 a conjunction or disjunction. */
687 static tree
688 normalize_logical_operation (tree t, tree args, tree_code c, norm_info info)
690 tree t0 = normalize_expression (TREE_OPERAND (t, 0), args, info);
691 tree t1 = normalize_expression (TREE_OPERAND (t, 1), args, info);
693 /* Build a new info object for the constraint. */
694 tree ci = info.generate_diagnostics()
695 ? build_tree_list (t, info.context)
696 : NULL_TREE;
698 return build2 (c, ci, t0, t1);
701 /* Data types and hash functions for caching the normal form of a concept-id.
702 This essentially memoizes calls to normalize_concept_check. */
704 struct GTY((for_user)) norm_entry
706 /* The CONCEPT_DECL of the concept-id. */
707 tree tmpl;
708 /* The arguments of the concept-id. */
709 tree args;
710 /* The normal form of the concept-id. */
711 tree norm;
714 struct norm_hasher : ggc_ptr_hash<norm_entry>
716 static hashval_t hash (norm_entry *e)
718 ++comparing_specializations;
719 hashval_t val = iterative_hash_template_arg (e->tmpl, 0);
720 val = iterative_hash_template_arg (e->args, val);
721 --comparing_specializations;
722 return val;
725 static bool equal (norm_entry *e1, norm_entry *e2)
727 ++comparing_specializations;
728 bool eq = e1->tmpl == e2->tmpl
729 && template_args_equal (e1->args, e2->args);
730 --comparing_specializations;
731 return eq;
735 static GTY((deletable)) hash_table<norm_hasher> *norm_cache;
737 /* Normalize the concept check CHECK where ARGS are the
738 arguments to be substituted into CHECK's arguments. */
740 static tree
741 normalize_concept_check (tree check, tree args, norm_info info)
743 tree id = unpack_concept_check (check);
744 tree tmpl = TREE_OPERAND (id, 0);
745 tree targs = TREE_OPERAND (id, 1);
747 /* A function concept is wrapped in an overload. */
748 if (TREE_CODE (tmpl) == OVERLOAD)
750 /* TODO: Can we diagnose this error during parsing? */
751 if (TREE_CODE (check) == TEMPLATE_ID_EXPR)
752 error_at (EXPR_LOC_OR_LOC (check, input_location),
753 "function concept must be called");
754 tmpl = OVL_FIRST (tmpl);
757 /* Substitute through the arguments of the concept check. */
758 if (args)
759 targs = tsubst_template_args (targs, args, info.complain, info.in_decl);
760 if (targs == error_mark_node)
761 return error_mark_node;
762 if (template_args_equal (targs, generic_targs_for (tmpl)))
763 /* Canonicalize generic arguments as NULL_TREE, as an optimization. */
764 targs = NULL_TREE;
766 /* Build the substitution for the concept definition. */
767 tree parms = TREE_VALUE (DECL_TEMPLATE_PARMS (tmpl));
768 if (targs && args)
769 /* As an optimization, coerce the arguments only if necessary
770 (i.e. if they were substituted). */
771 targs = coerce_template_parms (parms, targs, tmpl, tf_none);
772 if (targs == error_mark_node)
773 return error_mark_node;
775 if (!norm_cache)
776 norm_cache = hash_table<norm_hasher>::create_ggc (31);
777 norm_entry *entry = nullptr;
778 if (!info.generate_diagnostics ())
780 /* Cache the normal form of the substituted concept-id (when not
781 diagnosing). */
782 norm_entry elt = {tmpl, targs, NULL_TREE};
783 norm_entry **slot = norm_cache->find_slot (&elt, INSERT);
784 if (*slot)
785 return (*slot)->norm;
786 entry = ggc_alloc<norm_entry> ();
787 *entry = elt;
788 *slot = entry;
791 tree def = get_concept_definition (DECL_TEMPLATE_RESULT (tmpl));
792 info.update_context (check, args);
793 tree norm = normalize_expression (def, targs, info);
794 if (entry)
795 entry->norm = norm;
796 return norm;
799 /* Used by normalize_atom to cache ATOMIC_CONSTRs. */
801 static GTY((deletable)) hash_table<atom_hasher> *atom_cache;
803 /* The normal form of an atom depends on the expression. The normal
804 form of a function call to a function concept is a check constraint
805 for that concept. The normal form of a reference to a variable
806 concept is a check constraint for that concept. Otherwise, the
807 constraint is a predicate constraint. */
809 static tree
810 normalize_atom (tree t, tree args, norm_info info)
812 /* Concept checks are not atomic. */
813 if (concept_check_p (t))
814 return normalize_concept_check (t, args, info);
816 /* Build the parameter mapping for the atom. */
817 tree map = build_parameter_mapping (t, args, info.ctx_parms ());
819 /* Build a new info object for the atom. */
820 tree ci = build_tree_list (t, info.context);
822 tree atom = build1 (ATOMIC_CONSTR, ci, map);
824 /* Remember whether the expression of this atomic constraint belongs to
825 a concept definition by inspecting in_decl, which should always be set
826 in this case either by norm_info::update_context (when recursing into a
827 concept-id during normalization) or by normalize_concept_definition
828 (when starting out with a concept-id). */
829 if (info.in_decl && concept_definition_p (info.in_decl))
830 ATOMIC_CONSTR_EXPR_FROM_CONCEPT_P (atom) = true;
832 if (!info.generate_diagnostics ())
834 /* Cache the ATOMIC_CONSTRs that we return, so that sat_hasher::equal
835 later can cheaply compare two atoms using just pointer equality. */
836 if (!atom_cache)
837 atom_cache = hash_table<atom_hasher>::create_ggc (31);
838 tree *slot = atom_cache->find_slot (atom, INSERT);
839 if (*slot)
840 return *slot;
842 /* Find all template parameters used in the targets of the parameter
843 mapping, and store a list of them in the TREE_TYPE of the mapping.
844 This list will be used by sat_hasher to determine the subset of
845 supplied template arguments that the satisfaction value of the atom
846 depends on. */
847 if (map)
849 tree targets = make_tree_vec (list_length (map));
850 int i = 0;
851 for (tree node = map; node; node = TREE_CHAIN (node))
853 tree target = TREE_PURPOSE (node);
854 TREE_VEC_ELT (targets, i++) = target;
856 tree target_parms = find_template_parameters (targets,
857 info.initial_parms);
858 TREE_TYPE (map) = target_parms;
861 *slot = atom;
863 return atom;
866 /* Returns the normal form of an expression. */
868 static tree
869 normalize_expression (tree t, tree args, norm_info info)
871 if (!t)
872 return NULL_TREE;
874 if (t == error_mark_node)
875 return error_mark_node;
877 switch (TREE_CODE (t))
879 case TRUTH_ANDIF_EXPR:
880 return normalize_logical_operation (t, args, CONJ_CONSTR, info);
881 case TRUTH_ORIF_EXPR:
882 return normalize_logical_operation (t, args, DISJ_CONSTR, info);
883 default:
884 return normalize_atom (t, args, info);
888 /* Cache of the normalized form of constraints. Marked as deletable because it
889 can all be recalculated. */
890 static GTY((deletable)) hash_map<tree,tree> *normalized_map;
892 static tree
893 get_normalized_constraints (tree t, norm_info info)
895 auto_timevar time (TV_CONSTRAINT_NORM);
896 return normalize_expression (t, NULL_TREE, info);
899 /* Returns the normalized constraints from a constraint-info object
900 or NULL_TREE if the constraints are null. IN_DECL provides the
901 declaration to which the constraints belong. */
903 static tree
904 get_normalized_constraints_from_info (tree ci, tree in_decl, bool diag = false)
906 if (ci == NULL_TREE)
907 return NULL_TREE;
909 /* Substitution errors during normalization are fatal. */
910 ++processing_template_decl;
911 norm_info info (in_decl, diag ? tf_norm : tf_none);
912 tree t = get_normalized_constraints (CI_ASSOCIATED_CONSTRAINTS (ci), info);
913 --processing_template_decl;
915 return t;
918 /* Returns the normalized constraints for the declaration D. */
920 static tree
921 get_normalized_constraints_from_decl (tree d, bool diag = false)
923 tree tmpl;
924 tree decl;
926 /* For inherited constructors, consider the original declaration;
927 it has the correct template information attached. */
928 d = strip_inheriting_ctors (d);
930 if (regenerated_lambda_fn_p (d))
932 /* If this lambda was regenerated, DECL_TEMPLATE_PARMS doesn't contain
933 all in-scope template parameters, but the lambda from which it was
934 ultimately regenerated does, so use that instead. */
935 tree lambda = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (d));
936 lambda = most_general_lambda (lambda);
937 d = lambda_function (lambda);
940 if (TREE_CODE (d) == TEMPLATE_DECL)
942 tmpl = d;
943 decl = DECL_TEMPLATE_RESULT (tmpl);
945 else
947 if (tree ti = DECL_TEMPLATE_INFO (d))
948 tmpl = TI_TEMPLATE (ti);
949 else
950 tmpl = NULL_TREE;
951 decl = d;
954 /* Get the most general template for the declaration, and compute
955 arguments from that. This ensures that the arguments used for
956 normalization are always template parameters and not arguments
957 used for outer specializations. For example:
959 template<typename T>
960 struct S {
961 template<typename U> requires C<T, U> void f(U);
964 S<int>::f(0);
966 When we normalize the requirements for S<int>::f, we want the
967 arguments to be {T, U}, not {int, U}. One reason for this is that
968 accepting the latter causes the template parameter level of U
969 to be reduced in a way that makes it overly difficult substitute
970 concrete arguments (i.e., eventually {int, int} during satisfaction. */
971 if (tmpl)
973 if (DECL_LANG_SPECIFIC(tmpl) && !DECL_TEMPLATE_SPECIALIZATION (tmpl))
974 tmpl = most_general_template (tmpl);
977 d = tmpl ? tmpl : decl;
979 /* If we're not diagnosing errors, use cached constraints, if any. */
980 if (!diag)
981 if (tree *p = hash_map_safe_get (normalized_map, d))
982 return *p;
984 tree norm = NULL_TREE;
985 if (tree ci = get_constraints (d))
987 push_access_scope_guard pas (decl);
988 norm = get_normalized_constraints_from_info (ci, tmpl, diag);
991 if (!diag)
992 hash_map_safe_put<hm_ggc> (normalized_map, d, norm);
994 return norm;
997 /* Returns the normal form of TMPL's definition. */
999 static tree
1000 normalize_concept_definition (tree tmpl, bool diag)
1002 if (!norm_cache)
1003 norm_cache = hash_table<norm_hasher>::create_ggc (31);
1004 norm_entry entry = {tmpl, NULL_TREE, NULL_TREE};
1006 if (!diag)
1007 if (norm_entry *found = norm_cache->find (&entry))
1008 return found->norm;
1010 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1011 tree def = get_concept_definition (DECL_TEMPLATE_RESULT (tmpl));
1012 ++processing_template_decl;
1013 norm_info info (tmpl, diag ? tf_norm : tf_none);
1014 tree norm = get_normalized_constraints (def, info);
1015 --processing_template_decl;
1017 if (!diag)
1019 norm_entry **slot = norm_cache->find_slot (&entry, INSERT);
1020 entry.norm = norm;
1021 *slot = ggc_alloc<norm_entry> ();
1022 **slot = entry;
1025 return norm;
1028 /* Normalize an EXPR as a constraint. */
1030 static tree
1031 normalize_constraint_expression (tree expr, norm_info info)
1033 if (!expr || expr == error_mark_node)
1034 return expr;
1036 if (!info.generate_diagnostics ())
1037 if (tree *p = hash_map_safe_get (normalized_map, expr))
1038 return *p;
1040 ++processing_template_decl;
1041 tree norm = get_normalized_constraints (expr, info);
1042 --processing_template_decl;
1044 if (!info.generate_diagnostics ())
1045 hash_map_safe_put<hm_ggc> (normalized_map, expr, norm);
1047 return norm;
1050 /* 17.4.1.2p2. Two constraints are identical if they are formed
1051 from the same expression and the targets of the parameter mapping
1052 are equivalent. */
1054 bool
1055 atomic_constraints_identical_p (tree t1, tree t2)
1057 gcc_assert (TREE_CODE (t1) == ATOMIC_CONSTR);
1058 gcc_assert (TREE_CODE (t2) == ATOMIC_CONSTR);
1060 if (ATOMIC_CONSTR_EXPR (t1) != ATOMIC_CONSTR_EXPR (t2))
1061 return false;
1063 if (!parameter_mapping_equivalent_p (t1, t2))
1064 return false;
1066 return true;
1069 /* True if T1 and T2 are equivalent, meaning they have the same syntactic
1070 structure and all corresponding constraints are identical. */
1072 bool
1073 constraints_equivalent_p (tree t1, tree t2)
1075 gcc_assert (CONSTR_P (t1));
1076 gcc_assert (CONSTR_P (t2));
1078 if (TREE_CODE (t1) != TREE_CODE (t2))
1079 return false;
1081 switch (TREE_CODE (t1))
1083 case CONJ_CONSTR:
1084 case DISJ_CONSTR:
1085 if (!constraints_equivalent_p (TREE_OPERAND (t1, 0), TREE_OPERAND (t2, 0)))
1086 return false;
1087 if (!constraints_equivalent_p (TREE_OPERAND (t1, 1), TREE_OPERAND (t2, 1)))
1088 return false;
1089 break;
1090 case ATOMIC_CONSTR:
1091 if (!atomic_constraints_identical_p(t1, t2))
1092 return false;
1093 break;
1094 default:
1095 gcc_unreachable ();
1097 return true;
1100 /* Compute the hash value for T. */
1102 hashval_t
1103 hash_atomic_constraint (tree t)
1105 gcc_assert (TREE_CODE (t) == ATOMIC_CONSTR);
1107 /* Hash the identity of the expression. */
1108 hashval_t val = htab_hash_pointer (ATOMIC_CONSTR_EXPR (t));
1110 /* Hash the targets of the parameter map. */
1111 tree p = ATOMIC_CONSTR_MAP (t);
1112 while (p)
1114 val = iterative_hash_template_arg (TREE_PURPOSE (p), val);
1115 p = TREE_CHAIN (p);
1118 return val;
1121 namespace inchash
1124 static void
1125 add_constraint (tree t, hash& h)
1127 h.add_int(TREE_CODE (t));
1128 switch (TREE_CODE (t))
1130 case CONJ_CONSTR:
1131 case DISJ_CONSTR:
1132 add_constraint (TREE_OPERAND (t, 0), h);
1133 add_constraint (TREE_OPERAND (t, 1), h);
1134 break;
1135 case ATOMIC_CONSTR:
1136 h.merge_hash (hash_atomic_constraint (t));
1137 break;
1138 default:
1139 gcc_unreachable ();
1145 /* Computes a hash code for the constraint T. */
1147 hashval_t
1148 iterative_hash_constraint (tree t, hashval_t val)
1150 gcc_assert (CONSTR_P (t));
1151 inchash::hash h (val);
1152 inchash::add_constraint (t, h);
1153 return h.end ();
1156 // -------------------------------------------------------------------------- //
1157 // Constraint Semantic Processing
1159 // The following functions are called by the parser and substitution rules
1160 // to create and evaluate constraint-related nodes.
1162 // The constraints associated with the current template parameters.
1163 tree
1164 current_template_constraints (void)
1166 if (!current_template_parms)
1167 return NULL_TREE;
1168 tree tmpl_constr = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
1169 return build_constraints (tmpl_constr, NULL_TREE);
1172 /* If the recently parsed TYPE declares or defines a template or
1173 template specialization, get its corresponding constraints from the
1174 current template parameters and bind them to TYPE's declaration. */
1176 tree
1177 associate_classtype_constraints (tree type)
1179 if (!type || type == error_mark_node || !CLASS_TYPE_P (type))
1180 return type;
1182 /* An explicit class template specialization has no template parameters. */
1183 if (!current_template_parms)
1184 return type;
1186 if (CLASSTYPE_IS_TEMPLATE (type) || CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1188 tree decl = TYPE_STUB_DECL (type);
1189 tree ci = current_template_constraints ();
1191 /* An implicitly instantiated member template declaration already
1192 has associated constraints. If it is defined outside of its
1193 class, then we need match these constraints against those of
1194 original declaration. */
1195 if (tree orig_ci = get_constraints (decl))
1197 if (int extra_levels = (TMPL_PARMS_DEPTH (current_template_parms)
1198 - TMPL_ARGS_DEPTH (TYPE_TI_ARGS (type))))
1200 /* If there is a discrepancy between the current template depth
1201 and the template depth of the original declaration, then we
1202 must be redeclaring a class template as part of a friend
1203 declaration within another class template. Before matching
1204 constraints, we need to reduce the template parameter level
1205 within the current constraints via substitution. */
1206 tree outer_gtargs = template_parms_to_args (current_template_parms);
1207 TREE_VEC_LENGTH (outer_gtargs) = extra_levels;
1208 ci = tsubst_constraint_info (ci, outer_gtargs, tf_none, NULL_TREE);
1210 if (!equivalent_constraints (ci, orig_ci))
1212 error ("%qT does not match original declaration", type);
1213 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1214 location_t loc = DECL_SOURCE_LOCATION (tmpl);
1215 inform (loc, "original template declaration here");
1216 /* Fall through, so that we define the type anyway. */
1218 return type;
1220 set_constraints (decl, ci);
1222 return type;
1225 /* Create an empty constraint info block. */
1227 static inline tree_constraint_info*
1228 build_constraint_info ()
1230 return (tree_constraint_info *)make_node (CONSTRAINT_INFO);
1233 /* Build a constraint-info object that contains the associated constraints
1234 of a declaration. This also includes the declaration's template
1235 requirements (TREQS) and any trailing requirements for a function
1236 declarator (DREQS). Note that both TREQS and DREQS must be constraints.
1238 If the declaration has neither template nor declaration requirements
1239 this returns NULL_TREE, indicating an unconstrained declaration. */
1241 tree
1242 build_constraints (tree tr, tree dr)
1244 if (!tr && !dr)
1245 return NULL_TREE;
1247 tree_constraint_info* ci = build_constraint_info ();
1248 ci->template_reqs = tr;
1249 ci->declarator_reqs = dr;
1250 ci->associated_constr = combine_constraint_expressions (tr, dr);
1252 return (tree)ci;
1255 /* Add constraint RHS to the end of CONSTRAINT_INFO ci. */
1257 tree
1258 append_constraint (tree ci, tree rhs)
1260 tree tr = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
1261 tree dr = ci ? CI_DECLARATOR_REQS (ci) : NULL_TREE;
1262 dr = combine_constraint_expressions (dr, rhs);
1263 if (ci)
1265 CI_DECLARATOR_REQS (ci) = dr;
1266 tree ac = combine_constraint_expressions (tr, dr);
1267 CI_ASSOCIATED_CONSTRAINTS (ci) = ac;
1269 else
1270 ci = build_constraints (tr, dr);
1271 return ci;
1274 /* A mapping from declarations to constraint information. */
1276 static GTY ((cache)) decl_tree_cache_map *decl_constraints;
1278 /* Returns the template constraints of declaration T. If T is not
1279 constrained, return NULL_TREE. Note that T must be non-null. */
1281 tree
1282 get_constraints (const_tree t)
1284 if (!flag_concepts)
1285 return NULL_TREE;
1286 if (!decl_constraints)
1287 return NULL_TREE;
1289 gcc_assert (DECL_P (t));
1290 if (TREE_CODE (t) == TEMPLATE_DECL)
1291 t = DECL_TEMPLATE_RESULT (t);
1292 tree* found = decl_constraints->get (CONST_CAST_TREE (t));
1293 if (found)
1294 return *found;
1295 else
1296 return NULL_TREE;
1299 /* Associate the given constraint information CI with the declaration
1300 T. If T is a template, then the constraints are associated with
1301 its underlying declaration. Don't build associations if CI is
1302 NULL_TREE. */
1304 void
1305 set_constraints (tree t, tree ci)
1307 if (!ci)
1308 return;
1309 gcc_assert (t && flag_concepts);
1310 if (TREE_CODE (t) == TEMPLATE_DECL)
1311 t = DECL_TEMPLATE_RESULT (t);
1312 bool found = hash_map_safe_put<hm_ggc> (decl_constraints, t, ci);
1313 gcc_assert (!found);
1316 /* Remove the associated constraints of the declaration T. */
1318 void
1319 remove_constraints (tree t)
1321 gcc_checking_assert (DECL_P (t));
1322 if (TREE_CODE (t) == TEMPLATE_DECL)
1323 t = DECL_TEMPLATE_RESULT (t);
1325 if (decl_constraints)
1326 decl_constraints->remove (t);
1329 /* If DECL is a friend, substitute into REQS to produce requirements suitable
1330 for declaration matching. */
1332 tree
1333 maybe_substitute_reqs_for (tree reqs, const_tree decl)
1335 if (reqs == NULL_TREE)
1336 return NULL_TREE;
1338 decl = STRIP_TEMPLATE (decl);
1339 if (DECL_UNIQUE_FRIEND_P (decl) && DECL_TEMPLATE_INFO (decl))
1341 tree tmpl = DECL_TI_TEMPLATE (decl);
1342 tree outer_args = outer_template_args (tmpl);
1343 processing_template_decl_sentinel s;
1344 if (PRIMARY_TEMPLATE_P (tmpl)
1345 || uses_template_parms (outer_args))
1346 ++processing_template_decl;
1347 reqs = tsubst_constraint (reqs, outer_args,
1348 tf_warning_or_error, NULL_TREE);
1350 return reqs;
1353 /* Returns the trailing requires clause of the declarator of
1354 a template declaration T or NULL_TREE if none. */
1356 tree
1357 get_trailing_function_requirements (tree t)
1359 tree ci = get_constraints (t);
1360 if (!ci)
1361 return NULL_TREE;
1362 return CI_DECLARATOR_REQS (ci);
1365 /* Construct a sequence of template arguments by prepending
1366 ARG to REST. Either ARG or REST may be null. */
1367 static tree
1368 build_concept_check_arguments (tree arg, tree rest)
1370 gcc_assert (rest ? TREE_CODE (rest) == TREE_VEC : true);
1371 tree args;
1372 if (arg)
1374 int n = rest ? TREE_VEC_LENGTH (rest) : 0;
1375 args = make_tree_vec (n + 1);
1376 TREE_VEC_ELT (args, 0) = arg;
1377 if (rest)
1378 for (int i = 0; i < n; ++i)
1379 TREE_VEC_ELT (args, i + 1) = TREE_VEC_ELT (rest, i);
1380 int def = rest ? GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (rest) : 0;
1381 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args, def + 1);
1383 else
1385 args = rest;
1387 return args;
1390 /* Builds an id-expression of the form `C<Args...>()` where C is a function
1391 concept. */
1393 static tree
1394 build_function_check (tree tmpl, tree args, tsubst_flags_t /*complain*/)
1396 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
1398 /* If we just got a template, wrap it in an overload so it looks like any
1399 other template-id. */
1400 tmpl = ovl_make (tmpl);
1401 TREE_TYPE (tmpl) = boolean_type_node;
1404 /* Perform function concept resolution now so we always have a single
1405 function of the overload set (even if we started with only one; the
1406 resolution function converts template arguments). Note that we still
1407 wrap this in an overload set so we don't upset other parts of the
1408 compiler that expect template-ids referring to function concepts
1409 to have an overload set. */
1410 tree info = resolve_function_concept_overload (tmpl, args);
1411 if (info == error_mark_node)
1412 return error_mark_node;
1413 if (!info)
1415 error ("no matching concepts for %qE", tmpl);
1416 return error_mark_node;
1418 args = TREE_PURPOSE (info);
1419 tmpl = DECL_TI_TEMPLATE (TREE_VALUE (info));
1421 /* Rebuild the singleton overload set; mark the type bool. */
1422 tmpl = ovl_make (tmpl, NULL_TREE);
1423 TREE_TYPE (tmpl) = boolean_type_node;
1425 /* Build the id-expression around the overload set. */
1426 tree id = build2 (TEMPLATE_ID_EXPR, boolean_type_node, tmpl, args);
1428 /* Finally, build the call expression around the overload. */
1429 ++processing_template_decl;
1430 vec<tree, va_gc> *fargs = make_tree_vector ();
1431 tree call = build_min_nt_call_vec (id, fargs);
1432 TREE_TYPE (call) = boolean_type_node;
1433 release_tree_vector (fargs);
1434 --processing_template_decl;
1436 return call;
1439 /* Builds an id-expression of the form `C<Args...>` where C is a variable
1440 concept. */
1442 static tree
1443 build_variable_check (tree tmpl, tree args, tsubst_flags_t complain)
1445 gcc_assert (variable_concept_p (tmpl));
1446 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1447 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
1448 args = coerce_template_parms (parms, args, tmpl, complain);
1449 if (args == error_mark_node)
1450 return error_mark_node;
1451 return build2 (TEMPLATE_ID_EXPR, boolean_type_node, tmpl, args);
1454 /* Builds an id-expression of the form `C<Args...>` where C is a standard
1455 concept. */
1457 static tree
1458 build_standard_check (tree tmpl, tree args, tsubst_flags_t complain)
1460 gcc_assert (standard_concept_p (tmpl));
1461 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1462 if (TREE_DEPRECATED (DECL_TEMPLATE_RESULT (tmpl)))
1463 warn_deprecated_use (DECL_TEMPLATE_RESULT (tmpl), NULL_TREE);
1464 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
1465 args = coerce_template_parms (parms, args, tmpl, complain);
1466 if (args == error_mark_node)
1467 return error_mark_node;
1468 return build2 (TEMPLATE_ID_EXPR, boolean_type_node, tmpl, args);
1471 /* Construct an expression that checks TARGET using ARGS. */
1473 tree
1474 build_concept_check (tree target, tree args, tsubst_flags_t complain)
1476 return build_concept_check (target, NULL_TREE, args, complain);
1479 /* Construct an expression that checks the concept given by DECL. If
1480 concept_definition_p (DECL) is false, this returns null. */
1482 tree
1483 build_concept_check (tree decl, tree arg, tree rest, tsubst_flags_t complain)
1485 tree args = build_concept_check_arguments (arg, rest);
1487 if (standard_concept_p (decl))
1488 return build_standard_check (decl, args, complain);
1489 if (variable_concept_p (decl))
1490 return build_variable_check (decl, args, complain);
1491 if (function_concept_p (decl))
1492 return build_function_check (decl, args, complain);
1494 return error_mark_node;
1497 /* Build a template-id that can participate in a concept check. */
1499 static tree
1500 build_concept_id (tree decl, tree args)
1502 tree check = build_concept_check (decl, args, tf_warning_or_error);
1503 if (check == error_mark_node)
1504 return error_mark_node;
1505 return unpack_concept_check (check);
1508 /* Build a template-id that can participate in a concept check, preserving
1509 the source location of the original template-id. */
1511 tree
1512 build_concept_id (tree expr)
1514 gcc_assert (TREE_CODE (expr) == TEMPLATE_ID_EXPR);
1515 tree id = build_concept_id (TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
1516 protected_set_expr_location (id, cp_expr_location (expr));
1517 return id;
1520 /* Build as template-id with a placeholder that can be used as a
1521 type constraint.
1523 Note that this will diagnose errors if the initial concept check
1524 cannot be built. */
1526 tree
1527 build_type_constraint (tree decl, tree args, tsubst_flags_t complain)
1529 tree wildcard = build_nt (WILDCARD_DECL);
1530 ++processing_template_decl;
1531 tree check = build_concept_check (decl, wildcard, args, complain);
1532 --processing_template_decl;
1533 if (check == error_mark_node)
1534 return error_mark_node;
1535 return unpack_concept_check (check);
1538 /* Returns a TYPE_DECL that contains sufficient information to
1539 build a template parameter of the same kind as PROTO and
1540 constrained by the concept declaration CNC. Note that PROTO
1541 is the first template parameter of CNC.
1543 If specified, ARGS provides additional arguments to the
1544 constraint check. */
1545 tree
1546 build_constrained_parameter (tree cnc, tree proto, tree args)
1548 tree name = DECL_NAME (cnc);
1549 tree type = TREE_TYPE (proto);
1550 tree decl = build_decl (input_location, TYPE_DECL, name, type);
1551 CONSTRAINED_PARM_PROTOTYPE (decl) = proto;
1552 CONSTRAINED_PARM_CONCEPT (decl) = cnc;
1553 CONSTRAINED_PARM_EXTRA_ARGS (decl) = args;
1554 return decl;
1557 /* Create a constraint expression for the given DECL that evaluates the
1558 requirements specified by CONSTR, a TYPE_DECL that contains all the
1559 information necessary to build the requirements (see finish_concept_name
1560 for the layout of that TYPE_DECL).
1562 Note that the constraints are neither reduced nor decomposed. That is
1563 done only after the requires clause has been parsed (or not). */
1565 tree
1566 finish_shorthand_constraint (tree decl, tree constr)
1568 /* No requirements means no constraints. */
1569 if (!constr)
1570 return NULL_TREE;
1572 if (error_operand_p (constr))
1573 return NULL_TREE;
1575 tree proto = CONSTRAINED_PARM_PROTOTYPE (constr);
1576 tree con = CONSTRAINED_PARM_CONCEPT (constr);
1577 tree args = CONSTRAINED_PARM_EXTRA_ARGS (constr);
1579 /* The TS lets use shorthand to constrain a pack of arguments, but the
1580 standard does not.
1582 For the TS, consider:
1584 template<C... Ts> struct s;
1586 If C is variadic (and because Ts is a pack), we associate the
1587 constraint C<Ts...>. In all other cases, we associate
1588 the constraint (C<Ts> && ...).
1590 The standard behavior cannot be overridden by -fconcepts-ts. */
1591 bool variadic_concept_p = template_parameter_pack_p (proto);
1592 bool declared_pack_p = template_parameter_pack_p (decl);
1593 bool apply_to_each_p = (cxx_dialect >= cxx20) ? true : !variadic_concept_p;
1595 /* Get the argument and overload used for the requirement
1596 and adjust it if we're going to expand later. */
1597 tree arg = template_parm_to_arg (decl);
1598 if (apply_to_each_p && declared_pack_p)
1599 arg = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg), 0));
1601 /* Build the concept constraint-expression. */
1602 tree tmpl = DECL_TI_TEMPLATE (con);
1603 tree check = tmpl;
1604 if (TREE_CODE (con) == FUNCTION_DECL)
1605 check = ovl_make (tmpl);
1606 check = build_concept_check (check, arg, args, tf_warning_or_error);
1608 /* Make the check a fold-expression if needed. */
1609 if (apply_to_each_p && declared_pack_p)
1610 check = finish_left_unary_fold_expr (check, TRUTH_ANDIF_EXPR);
1612 return check;
1615 /* Returns a conjunction of shorthand requirements for the template
1616 parameter list PARMS. Note that the requirements are stored in
1617 the TYPE of each tree node. */
1619 tree
1620 get_shorthand_constraints (tree parms)
1622 tree result = NULL_TREE;
1623 parms = INNERMOST_TEMPLATE_PARMS (parms);
1624 for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
1626 tree parm = TREE_VEC_ELT (parms, i);
1627 tree constr = TEMPLATE_PARM_CONSTRAINTS (parm);
1628 result = combine_constraint_expressions (result, constr);
1630 return result;
1633 /* Get the deduced wildcard from a DEDUCED placeholder. If the deduced
1634 wildcard is a pack, return the first argument of that pack. */
1636 static tree
1637 get_deduced_wildcard (tree wildcard)
1639 if (ARGUMENT_PACK_P (wildcard))
1640 wildcard = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (wildcard), 0);
1641 gcc_assert (TREE_CODE (wildcard) == WILDCARD_DECL);
1642 return wildcard;
1645 /* Returns the prototype parameter for the nth deduced wildcard. */
1647 static tree
1648 get_introduction_prototype (tree wildcards, int index)
1650 return TREE_TYPE (get_deduced_wildcard (TREE_VEC_ELT (wildcards, index)));
1653 /* Introduce a type template parameter. */
1655 static tree
1656 introduce_type_template_parameter (tree wildcard, bool& non_type_p)
1658 non_type_p = false;
1659 return finish_template_type_parm (class_type_node, DECL_NAME (wildcard));
1662 /* Introduce a template template parameter. */
1664 static tree
1665 introduce_template_template_parameter (tree wildcard, bool& non_type_p)
1667 non_type_p = false;
1668 begin_template_parm_list ();
1669 current_template_parms = DECL_TEMPLATE_PARMS (TREE_TYPE (wildcard));
1670 end_template_parm_list ();
1671 return finish_template_template_parm (class_type_node, DECL_NAME (wildcard));
1674 /* Introduce a template non-type parameter. */
1676 static tree
1677 introduce_nontype_template_parameter (tree wildcard, bool& non_type_p)
1679 non_type_p = true;
1680 tree parm = copy_decl (TREE_TYPE (wildcard));
1681 DECL_NAME (parm) = DECL_NAME (wildcard);
1682 return parm;
1685 /* Introduce a single template parameter. */
1687 static tree
1688 build_introduced_template_parameter (tree wildcard, bool& non_type_p)
1690 tree proto = TREE_TYPE (wildcard);
1692 tree parm;
1693 if (TREE_CODE (proto) == TYPE_DECL)
1694 parm = introduce_type_template_parameter (wildcard, non_type_p);
1695 else if (TREE_CODE (proto) == TEMPLATE_DECL)
1696 parm = introduce_template_template_parameter (wildcard, non_type_p);
1697 else
1698 parm = introduce_nontype_template_parameter (wildcard, non_type_p);
1700 /* Wrap in a TREE_LIST for process_template_parm. Note that introduced
1701 parameters do not retain the defaults from the source parameter. */
1702 return build_tree_list (NULL_TREE, parm);
1705 /* Introduce a single template parameter. */
1707 static tree
1708 introduce_template_parameter (tree parms, tree wildcard)
1710 gcc_assert (!ARGUMENT_PACK_P (wildcard));
1711 tree proto = TREE_TYPE (wildcard);
1712 location_t loc = DECL_SOURCE_LOCATION (wildcard);
1714 /* Diagnose the case where we have C{...Args}. */
1715 if (WILDCARD_PACK_P (wildcard))
1717 tree id = DECL_NAME (wildcard);
1718 error_at (loc, "%qE cannot be introduced with an ellipsis %<...%>", id);
1719 inform (DECL_SOURCE_LOCATION (proto), "prototype declared here");
1722 bool non_type_p;
1723 tree parm = build_introduced_template_parameter (wildcard, non_type_p);
1724 return process_template_parm (parms, loc, parm, non_type_p, false);
1727 /* Introduce a template parameter pack. */
1729 static tree
1730 introduce_template_parameter_pack (tree parms, tree wildcard)
1732 bool non_type_p;
1733 tree parm = build_introduced_template_parameter (wildcard, non_type_p);
1734 location_t loc = DECL_SOURCE_LOCATION (wildcard);
1735 return process_template_parm (parms, loc, parm, non_type_p, true);
1738 /* Introduce the nth template parameter. */
1740 static tree
1741 introduce_template_parameter (tree parms, tree wildcards, int& index)
1743 tree deduced = TREE_VEC_ELT (wildcards, index++);
1744 return introduce_template_parameter (parms, deduced);
1747 /* Introduce either a template parameter pack or a list of template
1748 parameters. */
1750 static tree
1751 introduce_template_parameters (tree parms, tree wildcards, int& index)
1753 /* If the prototype was a parameter, we better have deduced an
1754 argument pack, and that argument must be the last deduced value
1755 in the wildcard vector. */
1756 tree deduced = TREE_VEC_ELT (wildcards, index++);
1757 gcc_assert (ARGUMENT_PACK_P (deduced));
1758 gcc_assert (index == TREE_VEC_LENGTH (wildcards));
1760 /* Introduce each element in the pack. */
1761 tree args = ARGUMENT_PACK_ARGS (deduced);
1762 for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
1764 tree arg = TREE_VEC_ELT (args, i);
1765 if (WILDCARD_PACK_P (arg))
1766 parms = introduce_template_parameter_pack (parms, arg);
1767 else
1768 parms = introduce_template_parameter (parms, arg);
1771 return parms;
1774 /* Builds the template parameter list PARMS by chaining introduced
1775 parameters from the WILDCARD vector. INDEX is the position of
1776 the current parameter. */
1778 static tree
1779 process_introduction_parms (tree parms, tree wildcards, int& index)
1781 tree proto = get_introduction_prototype (wildcards, index);
1782 if (template_parameter_pack_p (proto))
1783 return introduce_template_parameters (parms, wildcards, index);
1784 else
1785 return introduce_template_parameter (parms, wildcards, index);
1788 /* Ensure that all template parameters have been introduced for the concept
1789 named in CHECK. If not, emit a diagnostic.
1791 Note that implicitly introducing a parameter with a default argument
1792 creates a case where a parameter is declared, but unnamed, making
1793 it unusable in the definition. */
1795 static bool
1796 check_introduction_list (tree intros, tree check)
1798 check = unpack_concept_check (check);
1799 tree tmpl = TREE_OPERAND (check, 0);
1800 if (OVL_P (tmpl))
1801 tmpl = OVL_FIRST (tmpl);
1803 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
1804 if (TREE_VEC_LENGTH (intros) < TREE_VEC_LENGTH (parms))
1806 error_at (input_location, "all template parameters of %qD must "
1807 "be introduced", tmpl);
1808 return false;
1811 return true;
1814 /* Associates a constraint check to the current template based on the
1815 introduction parameters. INTRO_LIST must be a TREE_VEC of WILDCARD_DECLs
1816 containing a chained PARM_DECL which contains the identifier as well as
1817 the source location. TMPL_DECL is the decl for the concept being used.
1818 If we take a concept, C, this will form a check in the form of
1819 C<INTRO_LIST> filling in any extra arguments needed by the defaults
1820 deduced.
1822 Returns NULL_TREE if no concept could be matched and error_mark_node if
1823 an error occurred when matching. */
1825 tree
1826 finish_template_introduction (tree tmpl_decl,
1827 tree intro_list,
1828 location_t intro_loc)
1830 /* Build a concept check to deduce the actual parameters. */
1831 tree expr = build_concept_check (tmpl_decl, intro_list, tf_none);
1832 if (expr == error_mark_node)
1834 error_at (intro_loc, "cannot deduce template parameters from "
1835 "introduction list");
1836 return error_mark_node;
1839 if (!check_introduction_list (intro_list, expr))
1840 return error_mark_node;
1842 tree parms = deduce_concept_introduction (expr);
1843 if (!parms)
1844 return NULL_TREE;
1846 /* Build template parameter scope for introduction. */
1847 tree parm_list = NULL_TREE;
1848 begin_template_parm_list ();
1849 int nargs = MIN (TREE_VEC_LENGTH (parms), TREE_VEC_LENGTH (intro_list));
1850 for (int n = 0; n < nargs; )
1851 parm_list = process_introduction_parms (parm_list, parms, n);
1852 parm_list = end_template_parm_list (parm_list);
1854 /* Update the number of arguments to reflect the number of deduced
1855 template parameter introductions. */
1856 nargs = TREE_VEC_LENGTH (parm_list);
1858 /* Determine if any errors occurred during matching. */
1859 for (int i = 0; i < TREE_VEC_LENGTH (parm_list); ++i)
1860 if (TREE_VALUE (TREE_VEC_ELT (parm_list, i)) == error_mark_node)
1862 end_template_decl ();
1863 return error_mark_node;
1866 /* Build a concept check for our constraint. */
1867 tree check_args = make_tree_vec (nargs);
1868 int n = 0;
1869 for (; n < TREE_VEC_LENGTH (parm_list); ++n)
1871 tree parm = TREE_VEC_ELT (parm_list, n);
1872 TREE_VEC_ELT (check_args, n) = template_parm_to_arg (parm);
1874 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (check_args, n);
1876 /* If the template expects more parameters we should be able
1877 to use the defaults from our deduced concept. */
1878 for (; n < TREE_VEC_LENGTH (parms); ++n)
1879 TREE_VEC_ELT (check_args, n) = TREE_VEC_ELT (parms, n);
1881 /* Associate the constraint. */
1882 tree check = build_concept_check (tmpl_decl,
1883 check_args,
1884 tf_warning_or_error);
1885 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = check;
1887 return parm_list;
1891 /* Given the concept check T from a constrained-type-specifier, extract
1892 its TMPL and ARGS. FIXME why do we need two different forms of
1893 constrained-type-specifier? */
1895 void
1896 placeholder_extract_concept_and_args (tree t, tree &tmpl, tree &args)
1898 if (concept_check_p (t))
1900 t = unpack_concept_check (t);
1901 tmpl = TREE_OPERAND (t, 0);
1902 if (TREE_CODE (tmpl) == OVERLOAD)
1903 tmpl = OVL_FIRST (tmpl);
1904 args = TREE_OPERAND (t, 1);
1905 return;
1908 if (TREE_CODE (t) == TYPE_DECL)
1910 /* A constrained parameter. Build a constraint check
1911 based on the prototype parameter and then extract the
1912 arguments from that. */
1913 tree proto = CONSTRAINED_PARM_PROTOTYPE (t);
1914 tree check = finish_shorthand_constraint (proto, t);
1915 placeholder_extract_concept_and_args (check, tmpl, args);
1916 return;
1920 /* Returns true iff the placeholders C1 and C2 are equivalent. C1
1921 and C2 can be either TEMPLATE_TYPE_PARM or template-ids. */
1923 bool
1924 equivalent_placeholder_constraints (tree c1, tree c2)
1926 if (c1 && TREE_CODE (c1) == TEMPLATE_TYPE_PARM)
1927 /* A constrained auto. */
1928 c1 = PLACEHOLDER_TYPE_CONSTRAINTS (c1);
1929 if (c2 && TREE_CODE (c2) == TEMPLATE_TYPE_PARM)
1930 c2 = PLACEHOLDER_TYPE_CONSTRAINTS (c2);
1932 if (c1 == c2)
1933 return true;
1934 if (!c1 || !c2)
1935 return false;
1936 if (c1 == error_mark_node || c2 == error_mark_node)
1937 /* We get here during satisfaction; when a deduction constraint
1938 fails, substitution can produce an error_mark_node for the
1939 placeholder constraints. */
1940 return false;
1942 tree t1, t2, a1, a2;
1943 placeholder_extract_concept_and_args (c1, t1, a1);
1944 placeholder_extract_concept_and_args (c2, t2, a2);
1946 if (t1 != t2)
1947 return false;
1949 int len1 = TREE_VEC_LENGTH (a1);
1950 int len2 = TREE_VEC_LENGTH (a2);
1951 if (len1 != len2)
1952 return false;
1954 /* Skip the first argument so we don't infinitely recurse.
1955 Also, they may differ in template parameter index. */
1956 for (int i = 1; i < len1; ++i)
1958 tree t1 = TREE_VEC_ELT (a1, i);
1959 tree t2 = TREE_VEC_ELT (a2, i);
1960 if (!template_args_equal (t1, t2))
1961 return false;
1963 return true;
1966 /* Return a hash value for the placeholder ATOMIC_CONSTR C. */
1968 hashval_t
1969 hash_placeholder_constraint (tree c)
1971 tree t, a;
1972 placeholder_extract_concept_and_args (c, t, a);
1974 /* Like hash_tmpl_and_args, but skip the first argument. */
1975 hashval_t val = iterative_hash_object (DECL_UID (t), 0);
1977 for (int i = TREE_VEC_LENGTH (a)-1; i > 0; --i)
1978 val = iterative_hash_template_arg (TREE_VEC_ELT (a, i), val);
1980 return val;
1983 /* Substitute through the expression of a simple requirement or
1984 compound requirement. */
1986 static tree
1987 tsubst_valid_expression_requirement (tree t, tree args, sat_info info)
1989 tree r = tsubst_expr (t, args, tf_none, info.in_decl);
1990 if (convert_to_void (r, ICV_STATEMENT, tf_none) != error_mark_node)
1991 return r;
1993 if (info.diagnose_unsatisfaction_p ())
1995 location_t loc = cp_expr_loc_or_input_loc (t);
1996 if (diagnosing_failed_constraint::replay_errors_p ())
1998 inform (loc, "the required expression %qE is invalid, because", t);
1999 if (r == error_mark_node)
2000 tsubst_expr (t, args, info.complain, info.in_decl);
2001 else
2002 convert_to_void (r, ICV_STATEMENT, info.complain);
2004 else
2005 inform (loc, "the required expression %qE is invalid", t);
2007 else if (info.noisy ())
2009 r = tsubst_expr (t, args, info.complain, info.in_decl);
2010 convert_to_void (r, ICV_STATEMENT, info.complain);
2013 return error_mark_node;
2017 /* Substitute through the simple requirement. */
2019 static tree
2020 tsubst_simple_requirement (tree t, tree args, sat_info info)
2022 tree t0 = TREE_OPERAND (t, 0);
2023 tree expr = tsubst_valid_expression_requirement (t0, args, info);
2024 if (expr == error_mark_node)
2025 return error_mark_node;
2026 return boolean_true_node;
2029 /* Subroutine of tsubst_type_requirement that performs the actual substitution
2030 and diagnosing. Also used by tsubst_compound_requirement. */
2032 static tree
2033 tsubst_type_requirement_1 (tree t, tree args, sat_info info, location_t loc)
2035 tree r = tsubst (t, args, tf_none, info.in_decl);
2036 if (r != error_mark_node)
2037 return r;
2039 if (info.diagnose_unsatisfaction_p ())
2041 if (diagnosing_failed_constraint::replay_errors_p ())
2043 /* Replay the substitution error. */
2044 inform (loc, "the required type %qT is invalid, because", t);
2045 tsubst (t, args, info.complain, info.in_decl);
2047 else
2048 inform (loc, "the required type %qT is invalid", t);
2050 else if (info.noisy ())
2051 tsubst (t, args, info.complain, info.in_decl);
2053 return error_mark_node;
2057 /* Substitute through the type requirement. */
2059 static tree
2060 tsubst_type_requirement (tree t, tree args, sat_info info)
2062 tree t0 = TREE_OPERAND (t, 0);
2063 tree type = tsubst_type_requirement_1 (t0, args, info, EXPR_LOCATION (t));
2064 if (type == error_mark_node)
2065 return error_mark_node;
2066 return boolean_true_node;
2069 /* True if TYPE can be deduced from EXPR. */
2071 static bool
2072 type_deducible_p (tree expr, tree type, tree placeholder, tree args,
2073 subst_info info)
2075 /* Make sure deduction is performed against ( EXPR ), so that
2076 references are preserved in the result. */
2077 expr = force_paren_expr_uneval (expr);
2079 tree deduced_type = do_auto_deduction (type, expr, placeholder,
2080 info.complain, adc_requirement,
2081 /*outer_targs=*/args);
2083 return deduced_type != error_mark_node;
2086 /* True if EXPR can not be converted to TYPE. */
2088 static bool
2089 expression_convertible_p (tree expr, tree type, subst_info info)
2091 tree conv =
2092 perform_direct_initialization_if_possible (type, expr, false,
2093 info.complain);
2094 if (conv == error_mark_node)
2095 return false;
2096 if (conv == NULL_TREE)
2098 if (info.complain & tf_error)
2100 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
2101 error_at (loc, "cannot convert %qE to %qT", expr, type);
2103 return false;
2105 return true;
2109 /* Substitute through the compound requirement. */
2111 static tree
2112 tsubst_compound_requirement (tree t, tree args, sat_info info)
2114 tree t0 = TREE_OPERAND (t, 0);
2115 tree t1 = TREE_OPERAND (t, 1);
2116 tree expr = tsubst_valid_expression_requirement (t0, args, info);
2117 if (expr == error_mark_node)
2118 return error_mark_node;
2120 location_t loc = cp_expr_loc_or_input_loc (expr);
2122 /* Check the noexcept condition. */
2123 bool noexcept_p = COMPOUND_REQ_NOEXCEPT_P (t);
2124 if (noexcept_p && !expr_noexcept_p (expr, tf_none))
2126 if (info.diagnose_unsatisfaction_p ())
2127 inform (loc, "%qE is not %<noexcept%>", expr);
2128 else
2129 return error_mark_node;
2132 /* Substitute through the type expression, if any. */
2133 tree type = tsubst_type_requirement_1 (t1, args, info, EXPR_LOCATION (t));
2134 if (type == error_mark_node)
2135 return error_mark_node;
2137 subst_info quiet (tf_none, info.in_decl);
2139 /* Check expression against the result type. */
2140 if (type)
2142 if (tree placeholder = type_uses_auto (type))
2144 if (!type_deducible_p (expr, type, placeholder, args, quiet))
2146 if (info.diagnose_unsatisfaction_p ())
2148 if (diagnosing_failed_constraint::replay_errors_p ())
2150 inform (loc,
2151 "%qE does not satisfy return-type-requirement, "
2152 "because", t0);
2153 /* Further explain the reason for the error. */
2154 type_deducible_p (expr, type, placeholder, args, info);
2156 else
2157 inform (loc,
2158 "%qE does not satisfy return-type-requirement", t0);
2160 return error_mark_node;
2163 else if (!expression_convertible_p (expr, type, quiet))
2165 if (info.diagnose_unsatisfaction_p ())
2167 if (diagnosing_failed_constraint::replay_errors_p ())
2169 inform (loc, "cannot convert %qE to %qT because", t0, type);
2170 /* Further explain the reason for the error. */
2171 expression_convertible_p (expr, type, info);
2173 else
2174 inform (loc, "cannot convert %qE to %qT", t0, type);
2176 return error_mark_node;
2180 return boolean_true_node;
2183 /* Substitute through the nested requirement. */
2185 static tree
2186 tsubst_nested_requirement (tree t, tree args, sat_info info)
2188 sat_info quiet (tf_none, info.in_decl);
2189 tree result = constraint_satisfaction_value (t, args, quiet);
2190 if (result == boolean_true_node)
2191 return boolean_true_node;
2193 if (result == boolean_false_node
2194 && info.diagnose_unsatisfaction_p ())
2196 tree expr = TREE_OPERAND (t, 0);
2197 location_t loc = cp_expr_location (t);
2198 if (diagnosing_failed_constraint::replay_errors_p ())
2200 /* Replay the substitution error. */
2201 inform (loc, "nested requirement %qE is not satisfied, because", expr);
2202 constraint_satisfaction_value (t, args, info);
2204 else
2205 inform (loc, "nested requirement %qE is not satisfied", expr);
2208 return error_mark_node;
2211 /* Substitute ARGS into the requirement T. */
2213 static tree
2214 tsubst_requirement (tree t, tree args, sat_info info)
2216 iloc_sentinel loc_s (cp_expr_location (t));
2217 switch (TREE_CODE (t))
2219 case SIMPLE_REQ:
2220 return tsubst_simple_requirement (t, args, info);
2221 case TYPE_REQ:
2222 return tsubst_type_requirement (t, args, info);
2223 case COMPOUND_REQ:
2224 return tsubst_compound_requirement (t, args, info);
2225 case NESTED_REQ:
2226 return tsubst_nested_requirement (t, args, info);
2227 default:
2228 break;
2230 gcc_unreachable ();
2233 static tree
2234 declare_constraint_vars (tree parms, tree vars)
2236 tree s = vars;
2237 for (tree t = parms; t; t = DECL_CHAIN (t))
2239 if (DECL_PACK_P (t))
2241 tree pack = extract_fnparm_pack (t, &s);
2242 register_local_specialization (pack, t);
2244 else
2246 register_local_specialization (s, t);
2247 s = DECL_CHAIN (s);
2250 return vars;
2253 /* Substitute through as if checking function parameter types. This
2254 will diagnose common parameter type errors. Returns error_mark_node
2255 if an error occurred. */
2257 static tree
2258 check_constraint_variables (tree t, tree args, subst_info info)
2260 tree types = NULL_TREE;
2261 tree p = t;
2262 while (p && !VOID_TYPE_P (p))
2264 types = tree_cons (NULL_TREE, TREE_TYPE (p), types);
2265 p = TREE_CHAIN (p);
2267 types = chainon (nreverse (types), void_list_node);
2268 return tsubst_function_parms (types, args, info.complain, info.in_decl);
2271 /* A subroutine of tsubst_parameterized_constraint. Substitute ARGS
2272 into the parameter list T, producing a sequence of constraint
2273 variables, declared in the current scope.
2275 Note that the caller must establish a local specialization stack
2276 prior to calling this function since this substitution will
2277 declare the substituted parameters. */
2279 static tree
2280 tsubst_constraint_variables (tree t, tree args, subst_info info)
2282 /* Perform a trial substitution to check for type errors. */
2283 tree parms = check_constraint_variables (t, args, info);
2284 if (parms == error_mark_node)
2285 return error_mark_node;
2287 /* Clear cp_unevaluated_operand across tsubst so that we get a proper chain
2288 of PARM_DECLs. */
2289 int saved_unevaluated_operand = cp_unevaluated_operand;
2290 cp_unevaluated_operand = 0;
2291 tree vars = tsubst (t, args, info.complain, info.in_decl);
2292 cp_unevaluated_operand = saved_unevaluated_operand;
2293 if (vars == error_mark_node)
2294 return error_mark_node;
2295 return declare_constraint_vars (t, vars);
2298 /* Substitute ARGS into the requires-expression T. [8.4.7]p6. The
2299 substitution of template arguments into a requires-expression
2300 may result in the formation of invalid types or expressions
2301 in its requirements ... In such cases, the expression evaluates
2302 to false; it does not cause the program to be ill-formed.
2304 When substituting through a REQUIRES_EXPR as part of template
2305 instantiation, we call this routine with info.quiet() true.
2307 When evaluating a REQUIRES_EXPR that appears outside a template in
2308 cp_parser_requires_expression, we call this routine with
2309 info.noisy() true.
2311 Finally, when diagnosing unsatisfaction from diagnose_atomic_constraint
2312 and when diagnosing a false REQUIRES_EXPR via diagnose_constraints,
2313 we call this routine with info.diagnose_unsatisfaction_p() true. */
2315 static tree
2316 tsubst_requires_expr (tree t, tree args, sat_info info)
2318 local_specialization_stack stack (lss_copy);
2320 /* We need to check access during the substitution. */
2321 deferring_access_check_sentinel acs (dk_no_deferred);
2323 /* A requires-expression is an unevaluated context. */
2324 cp_unevaluated u;
2326 args = add_extra_args (REQUIRES_EXPR_EXTRA_ARGS (t), args,
2327 info.complain, info.in_decl);
2328 if (processing_template_decl)
2330 /* We're partially instantiating a generic lambda. Substituting into
2331 this requires-expression now may cause its requirements to get
2332 checked out of order, so instead just remember the template
2333 arguments and wait until we can substitute them all at once. */
2334 t = copy_node (t);
2335 REQUIRES_EXPR_EXTRA_ARGS (t) = build_extra_args (t, args, info.complain);
2336 return t;
2339 if (tree parms = REQUIRES_EXPR_PARMS (t))
2341 parms = tsubst_constraint_variables (parms, args, info);
2342 if (parms == error_mark_node)
2343 return boolean_false_node;
2346 tree result = boolean_true_node;
2347 for (tree reqs = REQUIRES_EXPR_REQS (t); reqs; reqs = TREE_CHAIN (reqs))
2349 tree req = TREE_VALUE (reqs);
2350 if (tsubst_requirement (req, args, info) == error_mark_node)
2352 result = boolean_false_node;
2353 if (info.diagnose_unsatisfaction_p ())
2354 /* Keep going so that we diagnose all failed requirements. */;
2355 else
2356 break;
2359 return result;
2362 /* Public wrapper for the above. */
2364 tree
2365 tsubst_requires_expr (tree t, tree args,
2366 tsubst_flags_t complain, tree in_decl)
2368 sat_info info (complain, in_decl);
2369 return tsubst_requires_expr (t, args, info);
2372 /* Substitute ARGS into the constraint information CI, producing a new
2373 constraint record. */
2375 tree
2376 tsubst_constraint_info (tree t, tree args,
2377 tsubst_flags_t complain, tree in_decl)
2379 if (!t || t == error_mark_node || !check_constraint_info (t))
2380 return NULL_TREE;
2382 tree tr = tsubst_constraint (CI_TEMPLATE_REQS (t), args, complain, in_decl);
2383 tree dr = tsubst_constraint (CI_DECLARATOR_REQS (t), args, complain, in_decl);
2384 return build_constraints (tr, dr);
2387 /* Substitute through a parameter mapping, in order to get the actual
2388 arguments used to instantiate an atomic constraint. This may fail
2389 if the substitution into arguments produces something ill-formed. */
2391 static tree
2392 tsubst_parameter_mapping (tree map, tree args, subst_info info)
2394 if (!map)
2395 return NULL_TREE;
2397 tsubst_flags_t complain = info.complain;
2398 tree in_decl = info.in_decl;
2400 tree result = NULL_TREE;
2401 for (tree p = map; p; p = TREE_CHAIN (p))
2403 if (p == error_mark_node)
2404 return error_mark_node;
2405 tree parm = TREE_VALUE (p);
2406 tree arg = TREE_PURPOSE (p);
2407 tree new_arg;
2408 if (ARGUMENT_PACK_P (arg))
2409 new_arg = tsubst_argument_pack (arg, args, complain, in_decl);
2410 else
2412 new_arg = tsubst_template_arg (arg, args, complain, in_decl);
2413 if (TYPE_P (new_arg))
2414 new_arg = canonicalize_type_argument (new_arg, complain);
2416 if (TREE_CODE (new_arg) == TYPE_ARGUMENT_PACK)
2418 tree pack_args = ARGUMENT_PACK_ARGS (new_arg);
2419 for (tree& pack_arg : tree_vec_range (pack_args))
2420 if (TYPE_P (pack_arg))
2421 pack_arg = canonicalize_type_argument (pack_arg, complain);
2423 if (new_arg == error_mark_node)
2424 return error_mark_node;
2426 result = tree_cons (new_arg, parm, result);
2428 return nreverse (result);
2431 tree
2432 tsubst_parameter_mapping (tree map, tree args, tsubst_flags_t complain, tree in_decl)
2434 return tsubst_parameter_mapping (map, args, subst_info (complain, in_decl));
2437 /*---------------------------------------------------------------------------
2438 Constraint satisfaction
2439 ---------------------------------------------------------------------------*/
2441 /* True if we are currently satisfying a constraint. */
2443 static bool satisfying_constraint;
2445 /* A vector of incomplete types (and of declarations with undeduced return type),
2446 appended to by note_failed_type_completion_for_satisfaction. The
2447 satisfaction caches use this in order to keep track of "potentially unstable"
2448 satisfaction results.
2450 Since references to entries in this vector are stored only in the
2451 GC-deletable sat_cache, it's safe to make this deletable as well. */
2453 static GTY((deletable)) vec<tree, va_gc> *failed_type_completions;
2455 /* Called whenever a type completion (or return type deduction) failure occurs
2456 that definitely affects the meaning of the program, by e.g. inducing
2457 substitution failure. */
2459 void
2460 note_failed_type_completion_for_satisfaction (tree t)
2462 if (satisfying_constraint)
2464 gcc_checking_assert ((TYPE_P (t) && !COMPLETE_TYPE_P (t))
2465 || (DECL_P (t) && undeduced_auto_decl (t)));
2466 vec_safe_push (failed_type_completions, t);
2470 /* Returns true if the range [BEGIN, END) of elements within the
2471 failed_type_completions vector contains a complete type (or a
2472 declaration with a non-placeholder return type). */
2474 static bool
2475 some_type_complete_p (int begin, int end)
2477 for (int i = begin; i < end; i++)
2479 tree t = (*failed_type_completions)[i];
2480 if (TYPE_P (t) && COMPLETE_TYPE_P (t))
2481 return true;
2482 if (DECL_P (t) && !undeduced_auto_decl (t))
2483 return true;
2485 return false;
2488 /* Hash functions and data types for satisfaction cache entries. */
2490 struct GTY((for_user)) sat_entry
2492 /* The relevant ATOMIC_CONSTR. */
2493 tree atom;
2495 /* The relevant template arguments. */
2496 tree args;
2498 /* The result of satisfaction of ATOM+ARGS.
2499 This is either boolean_true_node, boolean_false_node or error_mark_node,
2500 where error_mark_node indicates ill-formed satisfaction.
2501 It's set to NULL_TREE while computing satisfaction of ATOM+ARGS for
2502 the first time. */
2503 tree result;
2505 /* The value of input_location when satisfaction of ATOM+ARGS was first
2506 performed. */
2507 location_t location;
2509 /* The range of elements appended to the failed_type_completions vector
2510 during computation of this satisfaction result, encoded as a begin/end
2511 pair of offsets. */
2512 int ftc_begin, ftc_end;
2514 /* True if we want to diagnose the above instability when it's detected.
2515 We don't always want to do so, in order to avoid emitting duplicate
2516 diagnostics in some cases. */
2517 bool diagnose_instability;
2519 /* True if we're in the middle of computing this satisfaction result.
2520 Used during both quiet and noisy satisfaction to detect self-recursive
2521 satisfaction. */
2522 bool evaluating;
2525 struct sat_hasher : ggc_ptr_hash<sat_entry>
2527 static hashval_t hash (sat_entry *e)
2529 auto cso = make_temp_override (comparing_specializations);
2530 ++comparing_specializations;
2532 if (ATOMIC_CONSTR_MAP_INSTANTIATED_P (e->atom))
2534 /* Atoms with instantiated mappings are built during satisfaction.
2535 They live only inside the sat_cache, and we build one to query
2536 the cache with each time we instantiate a mapping. */
2537 gcc_assert (!e->args);
2538 return hash_atomic_constraint (e->atom);
2541 /* Atoms with uninstantiated mappings are built during normalization.
2542 Since normalize_atom caches the atoms it returns, we can assume
2543 pointer-based identity for fast hashing and comparison. Even if this
2544 assumption is violated, that's okay, we'll just get a cache miss. */
2545 hashval_t value = htab_hash_pointer (e->atom);
2547 if (tree map = ATOMIC_CONSTR_MAP (e->atom))
2548 /* Only the parameters that are used in the targets of the mapping
2549 affect the satisfaction value of the atom. So we consider only
2550 the arguments for these parameters, and ignore the rest. */
2551 for (tree target_parms = TREE_TYPE (map);
2552 target_parms;
2553 target_parms = TREE_CHAIN (target_parms))
2555 int level, index;
2556 tree parm = TREE_VALUE (target_parms);
2557 template_parm_level_and_index (parm, &level, &index);
2558 tree arg = TMPL_ARG (e->args, level, index);
2559 value = iterative_hash_template_arg (arg, value);
2561 return value;
2564 static bool equal (sat_entry *e1, sat_entry *e2)
2566 auto cso = make_temp_override (comparing_specializations);
2567 ++comparing_specializations;
2569 if (ATOMIC_CONSTR_MAP_INSTANTIATED_P (e1->atom)
2570 != ATOMIC_CONSTR_MAP_INSTANTIATED_P (e2->atom))
2571 return false;
2573 /* See sat_hasher::hash. */
2574 if (ATOMIC_CONSTR_MAP_INSTANTIATED_P (e1->atom))
2576 gcc_assert (!e1->args && !e2->args);
2577 return atomic_constraints_identical_p (e1->atom, e2->atom);
2580 if (e1->atom != e2->atom)
2581 return false;
2583 if (tree map = ATOMIC_CONSTR_MAP (e1->atom))
2584 for (tree target_parms = TREE_TYPE (map);
2585 target_parms;
2586 target_parms = TREE_CHAIN (target_parms))
2588 int level, index;
2589 tree parm = TREE_VALUE (target_parms);
2590 template_parm_level_and_index (parm, &level, &index);
2591 tree arg1 = TMPL_ARG (e1->args, level, index);
2592 tree arg2 = TMPL_ARG (e2->args, level, index);
2593 if (!template_args_equal (arg1, arg2))
2594 return false;
2596 return true;
2600 /* Cache the result of satisfy_atom. */
2601 static GTY((deletable)) hash_table<sat_hasher> *sat_cache;
2603 /* Cache the result of satisfy_declaration_constraints. */
2604 static GTY((deletable)) hash_map<tree, tree> *decl_satisfied_cache;
2606 /* A tool used by satisfy_atom to help manage satisfaction caching and to
2607 diagnose "unstable" satisfaction values. We insert into the cache only
2608 when performing satisfaction quietly. */
2610 struct satisfaction_cache
2612 satisfaction_cache (tree, tree, sat_info);
2613 tree get ();
2614 tree save (tree);
2616 sat_entry *entry;
2617 sat_info info;
2618 int ftc_begin;
2621 /* Constructor for the satisfaction_cache class. We're performing satisfaction
2622 of ATOM+ARGS according to INFO. */
2624 satisfaction_cache
2625 ::satisfaction_cache (tree atom, tree args, sat_info info)
2626 : entry(nullptr), info(info), ftc_begin(-1)
2628 if (!sat_cache)
2629 sat_cache = hash_table<sat_hasher>::create_ggc (31);
2631 /* When noisy, we query the satisfaction cache in order to diagnose
2632 "unstable" satisfaction values. */
2633 if (info.noisy ())
2635 /* When noisy, constraints have been re-normalized, and that breaks the
2636 pointer-based identity assumption of sat_cache (for atoms with
2637 uninstantiated mappings). So undo this re-normalization by looking in
2638 the atom_cache for the corresponding atom that was used during quiet
2639 satisfaction. */
2640 if (!ATOMIC_CONSTR_MAP_INSTANTIATED_P (atom))
2642 if (tree found = atom_cache->find (atom))
2643 atom = found;
2644 else
2645 /* The lookup should always succeed, but if it fails then let's
2646 just leave 'entry' empty, effectively disabling the cache. */
2647 return;
2651 /* Look up or create the corresponding satisfaction entry. */
2652 sat_entry elt;
2653 elt.atom = atom;
2654 elt.args = args;
2655 sat_entry **slot = sat_cache->find_slot (&elt, INSERT);
2656 if (*slot)
2657 entry = *slot;
2658 else if (info.quiet ())
2660 entry = ggc_alloc<sat_entry> ();
2661 entry->atom = atom;
2662 entry->args = args;
2663 entry->result = NULL_TREE;
2664 entry->location = input_location;
2665 entry->ftc_begin = entry->ftc_end = -1;
2666 entry->diagnose_instability = false;
2667 if (ATOMIC_CONSTR_MAP_INSTANTIATED_P (atom))
2668 /* We always want to diagnose instability of an atom with an
2669 instantiated parameter mapping. For atoms with an uninstantiated
2670 mapping, we set this flag (in satisfy_atom) only if substitution
2671 into its mapping previously failed. */
2672 entry->diagnose_instability = true;
2673 entry->evaluating = false;
2674 *slot = entry;
2676 else
2678 /* We're evaluating this atom for the first time, and doing so noisily.
2679 This shouldn't happen outside of error recovery situations involving
2680 unstable satisfaction. Let's just leave 'entry' empty, effectively
2681 disabling the cache, and remove the empty slot. */
2682 gcc_checking_assert (seen_error ());
2683 /* Appease hash_table::check_complete_insertion. */
2684 *slot = ggc_alloc<sat_entry> ();
2685 sat_cache->clear_slot (slot);
2689 /* Returns the cached satisfaction result if we have one and we're not
2690 recomputing the satisfaction result from scratch. Otherwise returns
2691 NULL_TREE. */
2693 tree
2694 satisfaction_cache::get ()
2696 if (!entry)
2697 return NULL_TREE;
2699 if (entry->evaluating)
2701 /* If we get here, it means satisfaction is self-recursive. */
2702 gcc_checking_assert (!entry->result || seen_error ());
2703 if (info.noisy ())
2704 error_at (EXPR_LOCATION (ATOMIC_CONSTR_EXPR (entry->atom)),
2705 "satisfaction of atomic constraint %qE depends on itself",
2706 entry->atom);
2707 return error_mark_node;
2710 /* This satisfaction result is "potentially unstable" if a type for which
2711 type completion failed during its earlier computation is now complete. */
2712 bool maybe_unstable = some_type_complete_p (entry->ftc_begin,
2713 entry->ftc_end);
2715 if (info.noisy () || maybe_unstable || !entry->result)
2717 /* We're computing the satisfaction result from scratch. */
2718 entry->evaluating = true;
2719 ftc_begin = vec_safe_length (failed_type_completions);
2720 return NULL_TREE;
2722 else
2723 return entry->result;
2726 /* RESULT is the computed satisfaction result. If RESULT differs from the
2727 previously cached result, this routine issues an appropriate error.
2728 Otherwise, when evaluating quietly, updates the cache appropriately. */
2730 tree
2731 satisfaction_cache::save (tree result)
2733 if (!entry)
2734 return result;
2736 gcc_checking_assert (entry->evaluating);
2737 entry->evaluating = false;
2739 if (entry->result && result != entry->result)
2741 if (info.quiet ())
2742 /* Return error_mark_node to force satisfaction to get replayed
2743 noisily. */
2744 return error_mark_node;
2745 else
2747 if (entry->diagnose_instability)
2749 auto_diagnostic_group d;
2750 error_at (EXPR_LOCATION (ATOMIC_CONSTR_EXPR (entry->atom)),
2751 "satisfaction value of atomic constraint %qE changed "
2752 "from %qE to %qE", entry->atom, entry->result, result);
2753 inform (entry->location,
2754 "satisfaction value first evaluated to %qE from here",
2755 entry->result);
2757 /* For sake of error recovery, allow this latest satisfaction result
2758 to prevail. */
2759 entry->result = result;
2760 return result;
2764 if (info.quiet ())
2766 entry->result = result;
2767 /* Store into this entry the list of relevant failed type completions
2768 that occurred during (re)computation of the satisfaction result. */
2769 gcc_checking_assert (ftc_begin != -1);
2770 entry->ftc_begin = ftc_begin;
2771 entry->ftc_end = vec_safe_length (failed_type_completions);
2774 return result;
2777 /* Substitute ARGS into constraint-expression T during instantiation of
2778 a member of a class template. */
2780 tree
2781 tsubst_constraint (tree t, tree args, tsubst_flags_t complain, tree in_decl)
2783 /* We also don't want to evaluate concept-checks when substituting the
2784 constraint-expressions of a declaration. */
2785 processing_constraint_expression_sentinel s;
2786 cp_unevaluated u;
2787 tree expr = tsubst_expr (t, args, complain, in_decl);
2788 return expr;
2791 static tree satisfy_constraint_r (tree, tree, sat_info info);
2793 /* Compute the satisfaction of a conjunction. */
2795 static tree
2796 satisfy_conjunction (tree t, tree args, sat_info info)
2798 tree lhs = satisfy_constraint_r (TREE_OPERAND (t, 0), args, info);
2799 if (lhs == error_mark_node || lhs == boolean_false_node)
2800 return lhs;
2801 return satisfy_constraint_r (TREE_OPERAND (t, 1), args, info);
2804 /* The current depth at which we're replaying an error during recursive
2805 diagnosis of a constraint satisfaction failure. */
2807 static int current_constraint_diagnosis_depth;
2809 /* Whether CURRENT_CONSTRAINT_DIAGNOSIS_DEPTH has ever exceeded
2810 CONCEPTS_DIAGNOSTICS_MAX_DEPTH during recursive diagnosis of a constraint
2811 satisfaction error. */
2813 static bool concepts_diagnostics_max_depth_exceeded_p;
2815 /* Recursive subroutine of collect_operands_of_disjunction. T is a normalized
2816 subexpression of a constraint (composed of CONJ_CONSTRs and DISJ_CONSTRs)
2817 and E is the corresponding unnormalized subexpression (composed of
2818 TRUTH_ANDIF_EXPRs and TRUTH_ORIF_EXPRs). */
2820 static void
2821 collect_operands_of_disjunction_r (tree t, tree e,
2822 auto_vec<tree_pair> *operands)
2824 if (TREE_CODE (e) == TRUTH_ORIF_EXPR)
2826 collect_operands_of_disjunction_r (TREE_OPERAND (t, 0),
2827 TREE_OPERAND (e, 0), operands);
2828 collect_operands_of_disjunction_r (TREE_OPERAND (t, 1),
2829 TREE_OPERAND (e, 1), operands);
2831 else
2833 tree_pair p = std::make_pair (t, e);
2834 operands->safe_push (p);
2838 /* Recursively collect the normalized and unnormalized operands of the
2839 disjunction T and append them to OPERANDS in order. */
2841 static void
2842 collect_operands_of_disjunction (tree t, auto_vec<tree_pair> *operands)
2844 collect_operands_of_disjunction_r (t, CONSTR_EXPR (t), operands);
2847 /* Compute the satisfaction of a disjunction. */
2849 static tree
2850 satisfy_disjunction (tree t, tree args, sat_info info)
2852 /* Evaluate each operand with unsatisfaction diagnostics disabled. */
2853 sat_info sub = info;
2854 sub.diagnose_unsatisfaction = false;
2856 tree lhs = satisfy_constraint_r (TREE_OPERAND (t, 0), args, sub);
2857 if (lhs == boolean_true_node || lhs == error_mark_node)
2858 return lhs;
2860 tree rhs = satisfy_constraint_r (TREE_OPERAND (t, 1), args, sub);
2861 if (rhs == boolean_true_node || rhs == error_mark_node)
2862 return rhs;
2864 /* Both branches evaluated to false. Explain the satisfaction failure in
2865 each branch. */
2866 if (info.diagnose_unsatisfaction_p ())
2868 diagnosing_failed_constraint failure (t, args, info.noisy ());
2869 cp_expr disj_expr = CONSTR_EXPR (t);
2870 inform (disj_expr.get_location (),
2871 "no operand of the disjunction is satisfied");
2872 if (diagnosing_failed_constraint::replay_errors_p ())
2874 /* Replay the error in each branch of the disjunction. */
2875 auto_vec<tree_pair> operands;
2876 collect_operands_of_disjunction (t, &operands);
2877 for (unsigned i = 0; i < operands.length (); i++)
2879 tree norm_op = operands[i].first;
2880 tree op = operands[i].second;
2881 location_t loc = make_location (cp_expr_location (op),
2882 disj_expr.get_start (),
2883 disj_expr.get_finish ());
2884 inform (loc, "the operand %qE is unsatisfied because", op);
2885 satisfy_constraint_r (norm_op, args, info);
2890 return boolean_false_node;
2893 /* Ensures that T is a truth value and not (accidentally, as sometimes
2894 happens) an integer value. */
2896 tree
2897 satisfaction_value (tree t)
2899 if (t == error_mark_node || t == boolean_true_node || t == boolean_false_node)
2900 return t;
2902 gcc_assert (TREE_CODE (t) == INTEGER_CST
2903 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (t),
2904 boolean_type_node));
2905 if (integer_zerop (t))
2906 return boolean_false_node;
2907 else
2908 return boolean_true_node;
2911 /* Build a new template argument vector corresponding to the parameter
2912 mapping of the atomic constraint T, using arguments from ARGS. */
2914 static tree
2915 get_mapped_args (tree t, tree args)
2917 tree map = ATOMIC_CONSTR_MAP (t);
2919 /* No map, no arguments. */
2920 if (!map)
2921 return NULL_TREE;
2923 /* Determine the depth of the resulting argument vector. */
2924 int depth;
2925 if (ATOMIC_CONSTR_EXPR_FROM_CONCEPT_P (t))
2926 /* The expression of this atomic constraint comes from a concept definition,
2927 whose template depth is always one, so the resulting argument vector
2928 will also have depth one. */
2929 depth = 1;
2930 else
2931 /* Otherwise, the expression of this atomic constraint comes from
2932 the context of the constrained entity, whose template depth is that
2933 of ARGS. */
2934 depth = TMPL_ARGS_DEPTH (args);
2936 /* Place each argument at its corresponding position in the argument
2937 list. Note that the list will be sparse (not all arguments supplied),
2938 but instantiation is guaranteed to only use the parameters in the
2939 mapping, so null arguments would never be used. */
2940 auto_vec< vec<tree> > lists (depth);
2941 lists.quick_grow_cleared (depth);
2942 for (tree p = map; p; p = TREE_CHAIN (p))
2944 int level;
2945 int index;
2946 template_parm_level_and_index (TREE_VALUE (p), &level, &index);
2948 /* Insert the argument into its corresponding position. */
2949 vec<tree> &list = lists[level - 1];
2950 if (index >= (int)list.length ())
2951 list.safe_grow_cleared (index + 1, /*exact=*/false);
2952 list[index] = TREE_PURPOSE (p);
2955 /* Build the new argument list. */
2956 args = make_tree_vec (lists.length ());
2957 for (unsigned i = 0; i != lists.length (); ++i)
2959 vec<tree> &list = lists[i];
2960 tree level = make_tree_vec (list.length ());
2961 for (unsigned j = 0; j < list.length(); ++j)
2962 TREE_VEC_ELT (level, j) = list[j];
2963 SET_TMPL_ARGS_LEVEL (args, i + 1, level);
2964 list.release ();
2966 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args, 0);
2968 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
2969 && TMPL_ARGS_DEPTH (args) == 1)
2971 /* Get rid of the redundant outer TREE_VEC. */
2972 tree level = TMPL_ARGS_LEVEL (args, 1);
2973 ggc_free (args);
2974 args = level;
2977 return args;
2980 static void diagnose_atomic_constraint (tree, tree, tree, sat_info);
2982 /* Compute the satisfaction of an atomic constraint. */
2984 static tree
2985 satisfy_atom (tree t, tree args, sat_info info)
2987 /* In case there is a diagnostic, we want to establish the context
2988 prior to printing errors. If no errors occur, this context is
2989 removed before returning. */
2990 diagnosing_failed_constraint failure (t, args, info.noisy ());
2992 satisfaction_cache cache (t, args, info);
2993 if (tree r = cache.get ())
2994 return r;
2996 /* Perform substitution quietly. */
2997 subst_info quiet (tf_none, NULL_TREE);
2999 /* Instantiate the parameter mapping. */
3000 tree map = tsubst_parameter_mapping (ATOMIC_CONSTR_MAP (t), args, quiet);
3001 if (map == error_mark_node)
3003 /* If instantiation of the parameter mapping fails, the constraint is
3004 not satisfied. Replay the substitution. */
3005 if (info.diagnose_unsatisfaction_p ())
3006 tsubst_parameter_mapping (ATOMIC_CONSTR_MAP (t), args, info);
3007 if (info.quiet ())
3008 /* Since instantiation of the parameter mapping failed, we
3009 want to diagnose potential instability of this satisfaction
3010 result. */
3011 cache.entry->diagnose_instability = true;
3012 return cache.save (boolean_false_node);
3015 /* Now build a new atom using the instantiated mapping. We use
3016 this atom as a second key to the satisfaction cache, and we
3017 also pass it to diagnose_atomic_constraint so that diagnostics
3018 which refer to the atom display the instantiated mapping. */
3019 t = copy_node (t);
3020 ATOMIC_CONSTR_MAP (t) = map;
3021 gcc_assert (!ATOMIC_CONSTR_MAP_INSTANTIATED_P (t));
3022 ATOMIC_CONSTR_MAP_INSTANTIATED_P (t) = true;
3023 satisfaction_cache inst_cache (t, /*args=*/NULL_TREE, info);
3024 if (tree r = inst_cache.get ())
3026 cache.entry->location = inst_cache.entry->location;
3027 return cache.save (r);
3030 /* Rebuild the argument vector from the parameter mapping. */
3031 args = get_mapped_args (t, args);
3033 /* Apply the parameter mapping (i.e., just substitute). */
3034 tree expr = ATOMIC_CONSTR_EXPR (t);
3035 tree result = tsubst_expr (expr, args, quiet.complain, quiet.in_decl);
3036 if (result == error_mark_node)
3038 /* If substitution results in an invalid type or expression, the constraint
3039 is not satisfied. Replay the substitution. */
3040 if (info.diagnose_unsatisfaction_p ())
3041 tsubst_expr (expr, args, info.complain, info.in_decl);
3042 return cache.save (inst_cache.save (boolean_false_node));
3045 /* [17.4.1.2] ... lvalue-to-rvalue conversion is performed as necessary,
3046 and EXPR shall be a constant expression of type bool. */
3047 result = force_rvalue (result, info.complain);
3048 if (result == error_mark_node)
3049 return cache.save (inst_cache.save (error_mark_node));
3050 if (!same_type_p (TREE_TYPE (result), boolean_type_node))
3052 if (info.noisy ())
3053 diagnose_atomic_constraint (t, args, result, info);
3054 return cache.save (inst_cache.save (error_mark_node));
3057 /* Compute the value of the constraint. */
3058 if (info.noisy ())
3060 iloc_sentinel ils (EXPR_LOCATION (result));
3061 result = cxx_constant_value (result);
3063 else
3065 result = maybe_constant_value (result, NULL_TREE, mce_true);
3066 if (!TREE_CONSTANT (result))
3067 result = error_mark_node;
3069 result = satisfaction_value (result);
3070 if (result == boolean_false_node && info.diagnose_unsatisfaction_p ())
3071 diagnose_atomic_constraint (t, args, result, info);
3073 return cache.save (inst_cache.save (result));
3076 /* Determine if the normalized constraint T is satisfied.
3077 Returns boolean_true_node if the expression/constraint is
3078 satisfied, boolean_false_node if not, and error_mark_node
3079 if the there was an error evaluating the constraint.
3081 The parameter mapping of atomic constraints is simply the
3082 set of template arguments that will be substituted into
3083 the expression, regardless of template parameters appearing
3084 withing. Whether a template argument is used in the atomic
3085 constraint only matters for subsumption. */
3087 static tree
3088 satisfy_constraint_r (tree t, tree args, sat_info info)
3090 if (t == error_mark_node)
3091 return error_mark_node;
3093 switch (TREE_CODE (t))
3095 case CONJ_CONSTR:
3096 return satisfy_conjunction (t, args, info);
3097 case DISJ_CONSTR:
3098 return satisfy_disjunction (t, args, info);
3099 case ATOMIC_CONSTR:
3100 return satisfy_atom (t, args, info);
3101 default:
3102 gcc_unreachable ();
3106 /* Check that the normalized constraint T is satisfied for ARGS. */
3108 static tree
3109 satisfy_normalized_constraints (tree t, tree args, sat_info info)
3111 auto_timevar time (TV_CONSTRAINT_SAT);
3113 auto ovr = make_temp_override (satisfying_constraint, true);
3115 /* Turn off template processing. Constraint satisfaction only applies
3116 to non-dependent terms, so we want to ensure full checking here. */
3117 processing_template_decl_sentinel proc (true);
3119 /* We need to check access during satisfaction. */
3120 deferring_access_check_sentinel acs (dk_no_deferred);
3122 /* Constraints are unevaluated operands. */
3123 cp_unevaluated u;
3125 return satisfy_constraint_r (t, args, info);
3128 /* Return the normal form of the constraints on the placeholder 'auto'
3129 type T. */
3131 static tree
3132 normalize_placeholder_type_constraints (tree t, bool diag)
3134 gcc_assert (is_auto (t));
3135 tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t);
3136 if (!ci)
3137 return NULL_TREE;
3139 tree constr = TREE_VALUE (ci);
3140 /* The TREE_PURPOSE contains the set of template parameters that were in
3141 scope for this placeholder type; use them as the initial template
3142 parameters for normalization. */
3143 tree initial_parms = TREE_PURPOSE (ci);
3145 /* The 'auto' itself is used as the first argument in its own constraints,
3146 and its level is one greater than its template depth. So in order to
3147 capture all used template parameters, we need to add an extra level of
3148 template parameters to the context; a dummy level suffices. */
3149 initial_parms
3150 = tree_cons (size_int (initial_parms
3151 ? TMPL_PARMS_DEPTH (initial_parms) + 1 : 1),
3152 make_tree_vec (0), initial_parms);
3154 norm_info info (diag ? tf_norm : tf_none);
3155 info.initial_parms = initial_parms;
3156 return normalize_constraint_expression (constr, info);
3159 /* Evaluate the constraints of T using ARGS, returning a satisfaction value.
3160 Here, T can be a concept-id, nested-requirement, placeholder 'auto', or
3161 requires-expression. */
3163 static tree
3164 satisfy_nondeclaration_constraints (tree t, tree args, sat_info info)
3166 if (t == error_mark_node)
3167 return error_mark_node;
3169 /* Handle REQUIRES_EXPR directly, bypassing satisfaction. */
3170 if (TREE_CODE (t) == REQUIRES_EXPR)
3172 auto ovr = make_temp_override (current_constraint_diagnosis_depth);
3173 if (info.noisy ())
3174 ++current_constraint_diagnosis_depth;
3175 return tsubst_requires_expr (t, args, info);
3178 /* Get the normalized constraints. */
3179 tree norm;
3180 if (concept_check_p (t))
3182 gcc_assert (!args);
3183 tree id = unpack_concept_check (t);
3184 args = TREE_OPERAND (id, 1);
3185 tree tmpl = get_concept_check_template (id);
3186 norm = normalize_concept_definition (tmpl, info.noisy ());
3188 else if (TREE_CODE (t) == NESTED_REQ)
3190 norm_info ninfo (info.noisy () ? tf_norm : tf_none);
3191 /* The TREE_TYPE contains the set of template parameters that were in
3192 scope for this nested requirement; use them as the initial template
3193 parameters for normalization. */
3194 ninfo.initial_parms = TREE_TYPE (t);
3195 norm = normalize_constraint_expression (TREE_OPERAND (t, 0), ninfo);
3197 else if (is_auto (t))
3199 norm = normalize_placeholder_type_constraints (t, info.noisy ());
3200 if (!norm)
3201 return boolean_true_node;
3203 else
3204 gcc_unreachable ();
3206 /* Perform satisfaction. */
3207 return satisfy_normalized_constraints (norm, args, info);
3210 /* Evaluate the associated constraints of the template specialization T
3211 according to INFO, returning a satisfaction value. */
3213 static tree
3214 satisfy_declaration_constraints (tree t, sat_info info)
3216 gcc_assert (DECL_P (t) && TREE_CODE (t) != TEMPLATE_DECL);
3217 const tree saved_t = t;
3219 /* For inherited constructors, consider the original declaration;
3220 it has the correct template information attached. */
3221 t = strip_inheriting_ctors (t);
3222 tree inh_ctor_targs = NULL_TREE;
3223 if (t != saved_t)
3224 if (tree ti = DECL_TEMPLATE_INFO (saved_t))
3225 /* The inherited constructor points to an instantiation of a constructor
3226 template; remember its template arguments. */
3227 inh_ctor_targs = TI_ARGS (ti);
3229 /* Update the declaration for diagnostics. */
3230 info.in_decl = t;
3232 if (info.quiet ())
3233 if (tree *result = hash_map_safe_get (decl_satisfied_cache, saved_t))
3234 return *result;
3236 tree args = NULL_TREE;
3237 if (tree ti = DECL_TEMPLATE_INFO (t))
3239 /* The initial parameter mapping is the complete set of
3240 template arguments substituted into the declaration. */
3241 args = TI_ARGS (ti);
3242 if (inh_ctor_targs)
3243 args = add_outermost_template_args (args, inh_ctor_targs);
3246 if (regenerated_lambda_fn_p (t))
3248 /* The TI_ARGS of a regenerated lambda contains only the innermost
3249 set of template arguments. Augment this with the outer template
3250 arguments that were used to regenerate the lambda. */
3251 gcc_assert (!args || TMPL_ARGS_DEPTH (args) == 1);
3252 tree regen_args = lambda_regenerating_args (t);
3253 if (args)
3254 args = add_to_template_args (regen_args, args);
3255 else
3256 args = regen_args;
3259 /* If the innermost arguments are dependent, or if the outer arguments
3260 are dependent and are needed by the constraints, we can't check
3261 satisfaction yet so pretend they're satisfied for now. */
3262 if (uses_template_parms (args)
3263 && ((DECL_TEMPLATE_INFO (t)
3264 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t))
3265 && (TMPL_ARGS_DEPTH (args) == 1
3266 || uses_template_parms (INNERMOST_TEMPLATE_ARGS (args))))
3267 || uses_outer_template_parms_in_constraints (t)))
3268 return boolean_true_node;
3270 /* Get the normalized constraints. */
3271 tree norm = get_normalized_constraints_from_decl (t, info.noisy ());
3273 unsigned ftc_count = vec_safe_length (failed_type_completions);
3275 tree result = boolean_true_node;
3276 if (norm)
3278 if (!push_tinst_level (t))
3279 return result;
3280 push_to_top_level ();
3281 push_access_scope (t);
3282 result = satisfy_normalized_constraints (norm, args, info);
3283 pop_access_scope (t);
3284 pop_from_top_level ();
3285 pop_tinst_level ();
3288 /* True if this satisfaction is (heuristically) potentially unstable, i.e.
3289 if its result may depend on where in the program it was performed. */
3290 bool maybe_unstable_satisfaction = false;
3291 if (ftc_count != vec_safe_length (failed_type_completions))
3292 /* Type completion failure occurred during satisfaction. The satisfaction
3293 result may (or may not) materially depend on the completeness of a type,
3294 so we consider it potentially unstable. */
3295 maybe_unstable_satisfaction = true;
3297 if (maybe_unstable_satisfaction)
3298 /* Don't cache potentially unstable satisfaction, to allow satisfy_atom
3299 to check the stability the next time around. */;
3300 else if (info.quiet ())
3301 hash_map_safe_put<hm_ggc> (decl_satisfied_cache, saved_t, result);
3303 return result;
3306 /* Evaluate the associated constraints of the template T using ARGS as the
3307 innermost set of template arguments and according to INFO, returning a
3308 satisfaction value. */
3310 static tree
3311 satisfy_declaration_constraints (tree t, tree args, sat_info info)
3313 /* Update the declaration for diagnostics. */
3314 info.in_decl = t;
3316 gcc_assert (TREE_CODE (t) == TEMPLATE_DECL);
3318 if (regenerated_lambda_fn_p (t))
3320 /* As in the two-parameter version of this function. */
3321 gcc_assert (TMPL_ARGS_DEPTH (args) == 1);
3322 tree lambda = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
3323 tree outer_args = TI_ARGS (LAMBDA_EXPR_REGEN_INFO (lambda));
3324 args = add_to_template_args (outer_args, args);
3326 else
3327 args = add_outermost_template_args (t, args);
3329 /* If the innermost arguments are dependent, or if the outer arguments
3330 are dependent and are needed by the constraints, we can't check
3331 satisfaction yet so pretend they're satisfied for now. */
3332 if (uses_template_parms (args)
3333 && (TMPL_ARGS_DEPTH (args) == 1
3334 || uses_template_parms (INNERMOST_TEMPLATE_ARGS (args))
3335 || uses_outer_template_parms_in_constraints (t)))
3336 return boolean_true_node;
3338 tree result = boolean_true_node;
3339 if (tree norm = get_normalized_constraints_from_decl (t, info.noisy ()))
3341 if (!push_tinst_level (t, args))
3342 return result;
3343 tree pattern = DECL_TEMPLATE_RESULT (t);
3344 push_to_top_level ();
3345 push_access_scope (pattern);
3346 result = satisfy_normalized_constraints (norm, args, info);
3347 pop_access_scope (pattern);
3348 pop_from_top_level ();
3349 pop_tinst_level ();
3352 return result;
3355 /* A wrapper around satisfy_declaration_constraints and
3356 satisfy_nondeclaration_constraints which additionally replays
3357 quiet ill-formed satisfaction noisily, so that ill-formed
3358 satisfaction always gets diagnosed. */
3360 static tree
3361 constraint_satisfaction_value (tree t, tree args, sat_info info)
3363 tree r;
3364 if (DECL_P (t))
3366 if (args)
3367 r = satisfy_declaration_constraints (t, args, info);
3368 else
3369 r = satisfy_declaration_constraints (t, info);
3371 else
3372 r = satisfy_nondeclaration_constraints (t, args, info);
3373 if (r == error_mark_node && info.quiet ()
3374 && !(DECL_P (t) && warning_suppressed_p (t)))
3376 /* Replay the error noisily. */
3377 sat_info noisy (tf_warning_or_error, info.in_decl);
3378 constraint_satisfaction_value (t, args, noisy);
3379 if (DECL_P (t) && !args)
3380 /* Avoid giving these errors again. */
3381 suppress_warning (t);
3383 return r;
3386 /* True iff the result of satisfying T using ARGS is BOOLEAN_TRUE_NODE
3387 and false otherwise, even in the case of errors.
3389 Here, T can be:
3390 - a template declaration
3391 - a template specialization (in which case ARGS must be empty)
3392 - a concept-id (in which case ARGS must be empty)
3393 - a nested-requirement
3394 - a placeholder 'auto'
3395 - a requires-expression. */
3397 bool
3398 constraints_satisfied_p (tree t, tree args/*= NULL_TREE */)
3400 if (!flag_concepts)
3401 return true;
3403 sat_info quiet (tf_none, NULL_TREE);
3404 return constraint_satisfaction_value (t, args, quiet) == boolean_true_node;
3407 /* Evaluate a concept check of the form C<ARGS>. This is only used for the
3408 evaluation of template-ids as id-expressions. */
3410 tree
3411 evaluate_concept_check (tree check)
3413 if (check == error_mark_node)
3414 return error_mark_node;
3416 gcc_assert (concept_check_p (check));
3418 /* Check for satisfaction without diagnostics. */
3419 sat_info quiet (tf_none, NULL_TREE);
3420 return constraint_satisfaction_value (check, /*args=*/NULL_TREE, quiet);
3423 /* Evaluate the requires-expression T, returning either boolean_true_node
3424 or boolean_false_node. This is used during folding and constexpr
3425 evaluation. */
3427 tree
3428 evaluate_requires_expr (tree t)
3430 gcc_assert (TREE_CODE (t) == REQUIRES_EXPR);
3431 sat_info quiet (tf_none, NULL_TREE);
3432 return constraint_satisfaction_value (t, /*args=*/NULL_TREE, quiet);
3435 /*---------------------------------------------------------------------------
3436 Semantic analysis of requires-expressions
3437 ---------------------------------------------------------------------------*/
3439 /* Finish a requires expression for the given PARMS (possibly
3440 null) and the non-empty sequence of requirements. */
3442 tree
3443 finish_requires_expr (location_t loc, tree parms, tree reqs)
3445 /* Build the node. */
3446 tree r = build_min (REQUIRES_EXPR, boolean_type_node, parms, reqs, NULL_TREE);
3447 TREE_SIDE_EFFECTS (r) = false;
3448 TREE_CONSTANT (r) = true;
3449 SET_EXPR_LOCATION (r, loc);
3450 return r;
3453 /* Construct a requirement for the validity of EXPR. */
3455 tree
3456 finish_simple_requirement (location_t loc, tree expr)
3458 tree r = build_nt (SIMPLE_REQ, expr);
3459 SET_EXPR_LOCATION (r, loc);
3460 return r;
3463 /* Construct a requirement for the validity of TYPE. */
3465 tree
3466 finish_type_requirement (location_t loc, tree type)
3468 tree r = build_nt (TYPE_REQ, type);
3469 SET_EXPR_LOCATION (r, loc);
3470 return r;
3473 /* Construct a requirement for the validity of EXPR, along with
3474 its properties. if TYPE is non-null, then it specifies either
3475 an implicit conversion or argument deduction constraint,
3476 depending on whether any placeholders occur in the type name.
3477 NOEXCEPT_P is true iff the noexcept keyword was specified. */
3479 tree
3480 finish_compound_requirement (location_t loc, tree expr, tree type, bool noexcept_p)
3482 tree req = build_nt (COMPOUND_REQ, expr, type);
3483 SET_EXPR_LOCATION (req, loc);
3484 COMPOUND_REQ_NOEXCEPT_P (req) = noexcept_p;
3485 return req;
3488 /* Finish a nested requirement. */
3490 tree
3491 finish_nested_requirement (location_t loc, tree expr)
3493 /* Build the requirement, saving the set of in-scope template
3494 parameters as its type. */
3495 tree r = build1 (NESTED_REQ, current_template_parms, expr);
3496 SET_EXPR_LOCATION (r, loc);
3497 return r;
3500 /* Check that FN satisfies the structural requirements of a
3501 function concept definition. */
3502 tree
3503 check_function_concept (tree fn)
3505 /* Check that the function is comprised of only a return statement. */
3506 tree body = DECL_SAVED_TREE (fn);
3507 if (TREE_CODE (body) == BIND_EXPR)
3508 body = BIND_EXPR_BODY (body);
3510 /* Sometimes a function call results in the creation of clean up
3511 points. Allow these to be preserved in the body of the
3512 constraint, as we might actually need them for some constexpr
3513 evaluations. */
3514 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
3515 body = TREE_OPERAND (body, 0);
3517 /* Check that the definition is written correctly. */
3518 if (TREE_CODE (body) != RETURN_EXPR)
3520 location_t loc = DECL_SOURCE_LOCATION (fn);
3521 if (TREE_CODE (body) == STATEMENT_LIST && !STATEMENT_LIST_HEAD (body))
3523 if (seen_error ())
3524 /* The definition was probably erroneous, not empty. */;
3525 else
3526 error_at (loc, "definition of concept %qD is empty", fn);
3528 else
3529 error_at (loc, "definition of concept %qD has multiple statements", fn);
3532 return NULL_TREE;
3535 /*---------------------------------------------------------------------------
3536 Equivalence of constraints
3537 ---------------------------------------------------------------------------*/
3539 /* Returns true when A and B are equivalent constraints. */
3540 bool
3541 equivalent_constraints (tree a, tree b)
3543 gcc_assert (!a || TREE_CODE (a) == CONSTRAINT_INFO);
3544 gcc_assert (!b || TREE_CODE (b) == CONSTRAINT_INFO);
3545 return cp_tree_equal (a, b);
3548 /* Returns true if the template declarations A and B have equivalent
3549 constraints. This is the case when A's constraints subsume B's and
3550 when B's also constrain A's. */
3551 bool
3552 equivalently_constrained (tree d1, tree d2)
3554 gcc_assert (TREE_CODE (d1) == TREE_CODE (d2));
3555 return equivalent_constraints (get_constraints (d1), get_constraints (d2));
3558 /*---------------------------------------------------------------------------
3559 Partial ordering of constraints
3560 ---------------------------------------------------------------------------*/
3562 /* Returns true when the constraints in CI strictly subsume
3563 the associated constraints of TMPL. */
3565 bool
3566 strictly_subsumes (tree ci, tree tmpl)
3568 tree n1 = get_normalized_constraints_from_info (ci, NULL_TREE);
3569 tree n2 = get_normalized_constraints_from_decl (tmpl);
3571 return subsumes (n1, n2) && !subsumes (n2, n1);
3574 /* Returns true when the constraints in CI subsume the
3575 associated constraints of TMPL. */
3577 bool
3578 weakly_subsumes (tree ci, tree tmpl)
3580 tree n1 = get_normalized_constraints_from_info (ci, NULL_TREE);
3581 tree n2 = get_normalized_constraints_from_decl (tmpl);
3583 return subsumes (n1, n2);
3586 /* Determines which of the declarations, A or B, is more constrained.
3587 That is, which declaration's constraints subsume but are not subsumed
3588 by the other's?
3590 Returns 1 if D1 is more constrained than D2, -1 if D2 is more constrained
3591 than D1, and 0 otherwise. */
3594 more_constrained (tree d1, tree d2)
3596 tree n1 = get_normalized_constraints_from_decl (d1);
3597 tree n2 = get_normalized_constraints_from_decl (d2);
3599 int winner = 0;
3600 if (subsumes (n1, n2))
3601 ++winner;
3602 if (subsumes (n2, n1))
3603 --winner;
3604 return winner;
3607 /* Return whether D1 is at least as constrained as D2. */
3609 bool
3610 at_least_as_constrained (tree d1, tree d2)
3612 tree n1 = get_normalized_constraints_from_decl (d1);
3613 tree n2 = get_normalized_constraints_from_decl (d2);
3615 return subsumes (n1, n2);
3618 /*---------------------------------------------------------------------------
3619 Constraint diagnostics
3620 ---------------------------------------------------------------------------*/
3622 /* Returns the best location to diagnose a constraint error. */
3624 static location_t
3625 get_constraint_error_location (tree t)
3627 if (location_t loc = cp_expr_location (t))
3628 return loc;
3630 /* If we have a specific location give it. */
3631 tree expr = CONSTR_EXPR (t);
3632 if (location_t loc = cp_expr_location (expr))
3633 return loc;
3635 /* If the constraint is normalized from a requires-clause, give
3636 the location as that of the constrained declaration. */
3637 tree cxt = CONSTR_CONTEXT (t);
3638 tree src = cxt ? TREE_VALUE (cxt) : NULL_TREE;
3639 if (!src)
3640 /* TODO: This only happens for constrained non-template declarations. */
3642 else if (DECL_P (src))
3643 return DECL_SOURCE_LOCATION (src);
3644 /* Otherwise, give the location as the defining concept. */
3645 else if (concept_check_p (src))
3647 tree id = unpack_concept_check (src);
3648 tree tmpl = TREE_OPERAND (id, 0);
3649 if (OVL_P (tmpl))
3650 tmpl = OVL_FIRST (tmpl);
3651 return DECL_SOURCE_LOCATION (tmpl);
3654 return input_location;
3657 /* Emit a diagnostic for a failed trait. */
3659 static void
3660 diagnose_trait_expr (tree expr, tree args)
3662 location_t loc = cp_expr_location (expr);
3664 /* Build a "fake" version of the instantiated trait, so we can
3665 get the instantiated types from result. */
3666 ++processing_template_decl;
3667 expr = tsubst_expr (expr, args, tf_none, NULL_TREE);
3668 --processing_template_decl;
3670 tree t1 = TRAIT_EXPR_TYPE1 (expr);
3671 tree t2 = TRAIT_EXPR_TYPE2 (expr);
3672 if (t2 && TREE_CODE (t2) == TREE_VEC)
3674 /* Convert the TREE_VEC of arguments into a TREE_LIST, since we can't
3675 directly print a TREE_VEC but we can a TREE_LIST via the E format
3676 specifier. */
3677 tree list = NULL_TREE;
3678 for (tree t : tree_vec_range (t2))
3679 list = tree_cons (NULL_TREE, t, list);
3680 t2 = nreverse (list);
3682 switch (TRAIT_EXPR_KIND (expr))
3684 case CPTK_HAS_NOTHROW_ASSIGN:
3685 inform (loc, " %qT is not nothrow copy assignable", t1);
3686 break;
3687 case CPTK_HAS_NOTHROW_CONSTRUCTOR:
3688 inform (loc, " %qT is not nothrow default constructible", t1);
3689 break;
3690 case CPTK_HAS_NOTHROW_COPY:
3691 inform (loc, " %qT is not nothrow copy constructible", t1);
3692 break;
3693 case CPTK_HAS_TRIVIAL_ASSIGN:
3694 inform (loc, " %qT is not trivially copy assignable", t1);
3695 break;
3696 case CPTK_HAS_TRIVIAL_CONSTRUCTOR:
3697 inform (loc, " %qT is not trivially default constructible", t1);
3698 break;
3699 case CPTK_HAS_TRIVIAL_COPY:
3700 inform (loc, " %qT is not trivially copy constructible", t1);
3701 break;
3702 case CPTK_HAS_TRIVIAL_DESTRUCTOR:
3703 inform (loc, " %qT is not trivially destructible", t1);
3704 break;
3705 case CPTK_HAS_VIRTUAL_DESTRUCTOR:
3706 inform (loc, " %qT does not have a virtual destructor", t1);
3707 break;
3708 case CPTK_IS_ABSTRACT:
3709 inform (loc, " %qT is not an abstract class", t1);
3710 break;
3711 case CPTK_IS_BASE_OF:
3712 inform (loc, " %qT is not a base of %qT", t1, t2);
3713 break;
3714 case CPTK_IS_CLASS:
3715 inform (loc, " %qT is not a class", t1);
3716 break;
3717 case CPTK_IS_EMPTY:
3718 inform (loc, " %qT is not an empty class", t1);
3719 break;
3720 case CPTK_IS_ENUM:
3721 inform (loc, " %qT is not an enum", t1);
3722 break;
3723 case CPTK_IS_FINAL:
3724 inform (loc, " %qT is not a final class", t1);
3725 break;
3726 case CPTK_IS_LAYOUT_COMPATIBLE:
3727 inform (loc, " %qT is not layout compatible with %qT", t1, t2);
3728 break;
3729 case CPTK_IS_LITERAL_TYPE:
3730 inform (loc, " %qT is not a literal type", t1);
3731 break;
3732 case CPTK_IS_POINTER_INTERCONVERTIBLE_BASE_OF:
3733 inform (loc, " %qT is not pointer-interconvertible base of %qT",
3734 t1, t2);
3735 break;
3736 case CPTK_IS_POD:
3737 inform (loc, " %qT is not a POD type", t1);
3738 break;
3739 case CPTK_IS_POLYMORPHIC:
3740 inform (loc, " %qT is not a polymorphic type", t1);
3741 break;
3742 case CPTK_IS_SAME:
3743 inform (loc, " %qT is not the same as %qT", t1, t2);
3744 break;
3745 case CPTK_IS_STD_LAYOUT:
3746 inform (loc, " %qT is not an standard layout type", t1);
3747 break;
3748 case CPTK_IS_TRIVIAL:
3749 inform (loc, " %qT is not a trivial type", t1);
3750 break;
3751 case CPTK_IS_UNION:
3752 inform (loc, " %qT is not a union", t1);
3753 break;
3754 case CPTK_IS_AGGREGATE:
3755 inform (loc, " %qT is not an aggregate", t1);
3756 break;
3757 case CPTK_IS_TRIVIALLY_COPYABLE:
3758 inform (loc, " %qT is not trivially copyable", t1);
3759 break;
3760 case CPTK_IS_ASSIGNABLE:
3761 inform (loc, " %qT is not assignable from %qT", t1, t2);
3762 break;
3763 case CPTK_IS_TRIVIALLY_ASSIGNABLE:
3764 inform (loc, " %qT is not trivially assignable from %qT", t1, t2);
3765 break;
3766 case CPTK_IS_NOTHROW_ASSIGNABLE:
3767 inform (loc, " %qT is not nothrow assignable from %qT", t1, t2);
3768 break;
3769 case CPTK_IS_CONSTRUCTIBLE:
3770 if (!t2)
3771 inform (loc, " %qT is not default constructible", t1);
3772 else
3773 inform (loc, " %qT is not constructible from %qE", t1, t2);
3774 break;
3775 case CPTK_IS_TRIVIALLY_CONSTRUCTIBLE:
3776 if (!t2)
3777 inform (loc, " %qT is not trivially default constructible", t1);
3778 else
3779 inform (loc, " %qT is not trivially constructible from %qE", t1, t2);
3780 break;
3781 case CPTK_IS_NOTHROW_CONSTRUCTIBLE:
3782 if (!t2)
3783 inform (loc, " %qT is not nothrow default constructible", t1);
3784 else
3785 inform (loc, " %qT is not nothrow constructible from %qE", t1, t2);
3786 break;
3787 case CPTK_HAS_UNIQUE_OBJ_REPRESENTATIONS:
3788 inform (loc, " %qT does not have unique object representations", t1);
3789 break;
3790 case CPTK_IS_CONVERTIBLE:
3791 inform (loc, " %qT is not convertible from %qE", t2, t1);
3792 break;
3793 case CPTK_IS_NOTHROW_CONVERTIBLE:
3794 inform (loc, " %qT is not nothrow convertible from %qE", t2, t1);
3795 break;
3796 case CPTK_REF_CONSTRUCTS_FROM_TEMPORARY:
3797 inform (loc, " %qT is not a reference that binds to a temporary "
3798 "object of type %qT (direct-initialization)", t1, t2);
3799 break;
3800 case CPTK_REF_CONVERTS_FROM_TEMPORARY:
3801 inform (loc, " %qT is not a reference that binds to a temporary "
3802 "object of type %qT (copy-initialization)", t1, t2);
3803 break;
3804 case CPTK_IS_DEDUCIBLE:
3805 inform (loc, " %qD is not deducible from %qT", t1, t2);
3806 break;
3807 #define DEFTRAIT_TYPE(CODE, NAME, ARITY) \
3808 case CPTK_##CODE:
3809 #include "cp-trait.def"
3810 #undef DEFTRAIT_TYPE
3811 /* Type-yielding traits aren't expressions. */
3812 gcc_unreachable ();
3813 /* We deliberately omit the default case so that when adding a new
3814 trait we'll get reminded (by way of a warning) to handle it here. */
3818 /* Diagnose a substitution failure in the atomic constraint T using ARGS. */
3820 static void
3821 diagnose_atomic_constraint (tree t, tree args, tree result, sat_info info)
3823 /* If the constraint is already ill-formed, we've previously diagnosed
3824 the reason. We should still say why the constraints aren't satisfied. */
3825 if (t == error_mark_node)
3827 location_t loc;
3828 if (info.in_decl)
3829 loc = DECL_SOURCE_LOCATION (info.in_decl);
3830 else
3831 loc = input_location;
3832 inform (loc, "invalid constraints");
3833 return;
3836 location_t loc = get_constraint_error_location (t);
3837 iloc_sentinel loc_s (loc);
3839 /* Generate better diagnostics for certain kinds of expressions. */
3840 tree expr = ATOMIC_CONSTR_EXPR (t);
3841 STRIP_ANY_LOCATION_WRAPPER (expr);
3842 switch (TREE_CODE (expr))
3844 case TRAIT_EXPR:
3845 diagnose_trait_expr (expr, args);
3846 break;
3847 case REQUIRES_EXPR:
3848 gcc_checking_assert (info.diagnose_unsatisfaction_p ());
3849 /* Clear in_decl before replaying the substitution to avoid emitting
3850 seemingly unhelpful "in declaration ..." notes that follow some
3851 substitution failure error messages. */
3852 info.in_decl = NULL_TREE;
3853 tsubst_requires_expr (expr, args, info);
3854 break;
3855 default:
3856 if (!same_type_p (TREE_TYPE (result), boolean_type_node))
3857 error_at (loc, "constraint %qE has type %qT, not %<bool%>",
3858 t, TREE_TYPE (result));
3859 else
3860 inform (loc, "the expression %qE evaluated to %<false%>", t);
3864 GTY(()) tree current_failed_constraint;
3866 diagnosing_failed_constraint::
3867 diagnosing_failed_constraint (tree t, tree args, bool diag)
3868 : diagnosing_error (diag)
3870 if (diagnosing_error)
3872 current_failed_constraint
3873 = tree_cons (args, t, current_failed_constraint);
3874 ++current_constraint_diagnosis_depth;
3878 diagnosing_failed_constraint::
3879 ~diagnosing_failed_constraint ()
3881 if (diagnosing_error)
3883 --current_constraint_diagnosis_depth;
3884 if (current_failed_constraint)
3885 current_failed_constraint = TREE_CHAIN (current_failed_constraint);
3890 /* Whether we are allowed to replay an error that underlies a constraint failure
3891 at the current diagnosis depth. */
3893 bool
3894 diagnosing_failed_constraint::replay_errors_p ()
3896 if (current_constraint_diagnosis_depth >= concepts_diagnostics_max_depth)
3898 concepts_diagnostics_max_depth_exceeded_p = true;
3899 return false;
3901 else
3902 return true;
3905 /* Emit diagnostics detailing the failure ARGS to satisfy the constraints
3906 of T. Here, T and ARGS are as in constraints_satisfied_p. */
3908 void
3909 diagnose_constraints (location_t loc, tree t, tree args)
3911 inform (loc, "constraints not satisfied");
3913 if (concepts_diagnostics_max_depth == 0)
3914 return;
3916 /* Replay satisfaction, but diagnose unsatisfaction. */
3917 sat_info noisy (tf_warning_or_error, NULL_TREE, /*diag_unsat=*/true);
3918 constraint_satisfaction_value (t, args, noisy);
3920 static bool suggested_p;
3921 if (concepts_diagnostics_max_depth_exceeded_p
3922 && current_constraint_diagnosis_depth == 0
3923 && !suggested_p)
3925 inform (UNKNOWN_LOCATION,
3926 "set %qs to at least %d for more detail",
3927 "-fconcepts-diagnostics-depth=",
3928 concepts_diagnostics_max_depth + 1);
3929 suggested_p = true;
3933 #include "gt-cp-constraint.h"