clang 19.0.0git
SemaConcept.cpp
Go to the documentation of this file.
1//===-- SemaConcept.cpp - Semantic Analysis for Constraints and Concepts --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ constraints and concepts.
10//
11//===----------------------------------------------------------------------===//
12
14#include "TreeTransform.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/DeclCXX.h"
22#include "clang/Sema/Overload.h"
24#include "clang/Sema/Sema.h"
27#include "clang/Sema/Template.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/PointerUnion.h"
31#include "llvm/ADT/StringExtras.h"
32#include <optional>
33
34using namespace clang;
35using namespace sema;
36
37namespace {
38class LogicalBinOp {
41 const Expr *LHS = nullptr;
42 const Expr *RHS = nullptr;
43
44public:
45 LogicalBinOp(const Expr *E) {
46 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
47 Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
48 LHS = BO->getLHS();
49 RHS = BO->getRHS();
50 Loc = BO->getExprLoc();
51 } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
52 // If OO is not || or && it might not have exactly 2 arguments.
53 if (OO->getNumArgs() == 2) {
54 Op = OO->getOperator();
55 LHS = OO->getArg(0);
56 RHS = OO->getArg(1);
57 Loc = OO->getOperatorLoc();
58 }
59 }
60 }
61
62 bool isAnd() const { return Op == OO_AmpAmp; }
63 bool isOr() const { return Op == OO_PipePipe; }
64 explicit operator bool() const { return isAnd() || isOr(); }
65
66 const Expr *getLHS() const { return LHS; }
67 const Expr *getRHS() const { return RHS; }
68
69 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
70 return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
71 }
72
73 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
74 ExprResult RHS) const {
75 assert((isAnd() || isOr()) && "Not the right kind of op?");
76 assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
77
78 if (!LHS.isUsable() || !RHS.isUsable())
79 return ExprEmpty();
80
81 // We should just be able to 'normalize' these to the builtin Binary
82 // Operator, since that is how they are evaluated in constriant checks.
83 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
85 SemaRef.Context.BoolTy, VK_PRValue,
87 }
88};
89}
90
91bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
92 Token NextToken, bool *PossibleNonPrimary,
93 bool IsTrailingRequiresClause) {
94 // C++2a [temp.constr.atomic]p1
95 // ..E shall be a constant expression of type bool.
96
97 ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
98
99 if (LogicalBinOp BO = ConstraintExpression) {
100 return CheckConstraintExpression(BO.getLHS(), NextToken,
101 PossibleNonPrimary) &&
102 CheckConstraintExpression(BO.getRHS(), NextToken,
103 PossibleNonPrimary);
104 } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
105 return CheckConstraintExpression(C->getSubExpr(), NextToken,
106 PossibleNonPrimary);
107
108 QualType Type = ConstraintExpression->getType();
109
110 auto CheckForNonPrimary = [&] {
111 if (!PossibleNonPrimary)
112 return;
113
114 *PossibleNonPrimary =
115 // We have the following case:
116 // template<typename> requires func(0) struct S { };
117 // The user probably isn't aware of the parentheses required around
118 // the function call, and we're only going to parse 'func' as the
119 // primary-expression, and complain that it is of non-bool type.
120 //
121 // However, if we're in a lambda, this might also be:
122 // []<typename> requires var () {};
123 // Which also looks like a function call due to the lambda parentheses,
124 // but unlike the first case, isn't an error, so this check is skipped.
125 (NextToken.is(tok::l_paren) &&
126 (IsTrailingRequiresClause ||
127 (Type->isDependentType() &&
128 isa<UnresolvedLookupExpr>(ConstraintExpression) &&
129 !dyn_cast_if_present<LambdaScopeInfo>(getCurFunction())) ||
130 Type->isFunctionType() ||
131 Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
132 // We have the following case:
133 // template<typename T> requires size_<T> == 0 struct S { };
134 // The user probably isn't aware of the parentheses required around
135 // the binary operator, and we're only going to parse 'func' as the
136 // first operand, and complain that it is of non-bool type.
137 getBinOpPrecedence(NextToken.getKind(),
138 /*GreaterThanIsOperator=*/true,
140 };
141
142 // An atomic constraint!
143 if (ConstraintExpression->isTypeDependent()) {
144 CheckForNonPrimary();
145 return true;
146 }
147
149 Diag(ConstraintExpression->getExprLoc(),
150 diag::err_non_bool_atomic_constraint) << Type
151 << ConstraintExpression->getSourceRange();
152 CheckForNonPrimary();
153 return false;
154 }
155
156 if (PossibleNonPrimary)
157 *PossibleNonPrimary = false;
158 return true;
159}
160
161namespace {
162struct SatisfactionStackRAII {
163 Sema &SemaRef;
164 bool Inserted = false;
165 SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND,
166 const llvm::FoldingSetNodeID &FSNID)
167 : SemaRef(SemaRef) {
168 if (ND) {
169 SemaRef.PushSatisfactionStackEntry(ND, FSNID);
170 Inserted = true;
171 }
172 }
173 ~SatisfactionStackRAII() {
174 if (Inserted)
176 }
177};
178} // namespace
179
180template <typename AtomicEvaluator>
181static ExprResult
182calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
183 ConstraintSatisfaction &Satisfaction,
184 AtomicEvaluator &&Evaluator) {
185 ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
186
187 if (LogicalBinOp BO = ConstraintExpr) {
188 size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
190 S, BO.getLHS(), Satisfaction, Evaluator);
191
192 if (LHSRes.isInvalid())
193 return ExprError();
194
195 bool IsLHSSatisfied = Satisfaction.IsSatisfied;
196
197 if (BO.isOr() && IsLHSSatisfied)
198 // [temp.constr.op] p3
199 // A disjunction is a constraint taking two operands. To determine if
200 // a disjunction is satisfied, the satisfaction of the first operand
201 // is checked. If that is satisfied, the disjunction is satisfied.
202 // Otherwise, the disjunction is satisfied if and only if the second
203 // operand is satisfied.
204 // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
205 return LHSRes;
206
207 if (BO.isAnd() && !IsLHSSatisfied)
208 // [temp.constr.op] p2
209 // A conjunction is a constraint taking two operands. To determine if
210 // a conjunction is satisfied, the satisfaction of the first operand
211 // is checked. If that is not satisfied, the conjunction is not
212 // satisfied. Otherwise, the conjunction is satisfied if and only if
213 // the second operand is satisfied.
214 // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
215 return LHSRes;
216
218 S, BO.getRHS(), Satisfaction, std::forward<AtomicEvaluator>(Evaluator));
219 if (RHSRes.isInvalid())
220 return ExprError();
221
222 bool IsRHSSatisfied = Satisfaction.IsSatisfied;
223 // Current implementation adds diagnostic information about the falsity
224 // of each false atomic constraint expression when it evaluates them.
225 // When the evaluation results to `false || true`, the information
226 // generated during the evaluation of left-hand side is meaningless
227 // because the whole expression evaluates to true.
228 // The following code removes the irrelevant diagnostic information.
229 // FIXME: We should probably delay the addition of diagnostic information
230 // until we know the entire expression is false.
231 if (BO.isOr() && IsRHSSatisfied) {
232 auto EffectiveDetailEnd = Satisfaction.Details.begin();
233 std::advance(EffectiveDetailEnd, EffectiveDetailEndIndex);
234 Satisfaction.Details.erase(EffectiveDetailEnd,
235 Satisfaction.Details.end());
236 }
237
238 return BO.recreateBinOp(S, LHSRes, RHSRes);
239 }
240
241 if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpr)) {
242 // These aren't evaluated, so we don't care about cleanups, so we can just
243 // evaluate these as if the cleanups didn't exist.
245 S, C->getSubExpr(), Satisfaction,
246 std::forward<AtomicEvaluator>(Evaluator));
247 }
248
249 // An atomic constraint expression
250 ExprResult SubstitutedAtomicExpr = Evaluator(ConstraintExpr);
251
252 if (SubstitutedAtomicExpr.isInvalid())
253 return ExprError();
254
255 if (!SubstitutedAtomicExpr.isUsable())
256 // Evaluator has decided satisfaction without yielding an expression.
257 return ExprEmpty();
258
259 // We don't have the ability to evaluate this, since it contains a
260 // RecoveryExpr, so we want to fail overload resolution. Otherwise,
261 // we'd potentially pick up a different overload, and cause confusing
262 // diagnostics. SO, add a failure detail that will cause us to make this
263 // overload set not viable.
264 if (SubstitutedAtomicExpr.get()->containsErrors()) {
265 Satisfaction.IsSatisfied = false;
266 Satisfaction.ContainsErrors = true;
267
268 PartialDiagnostic Msg = S.PDiag(diag::note_constraint_references_error);
269 SmallString<128> DiagString;
270 DiagString = ": ";
271 Msg.EmitToString(S.getDiagnostics(), DiagString);
272 unsigned MessageSize = DiagString.size();
273 char *Mem = new (S.Context) char[MessageSize];
274 memcpy(Mem, DiagString.c_str(), MessageSize);
275 Satisfaction.Details.emplace_back(
276 ConstraintExpr,
278 SubstitutedAtomicExpr.get()->getBeginLoc(),
279 StringRef(Mem, MessageSize)});
280 return SubstitutedAtomicExpr;
281 }
282
283 EnterExpressionEvaluationContext ConstantEvaluated(
286 Expr::EvalResult EvalResult;
287 EvalResult.Diag = &EvaluationDiags;
288 if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
289 S.Context) ||
290 !EvaluationDiags.empty()) {
291 // C++2a [temp.constr.atomic]p1
292 // ...E shall be a constant expression of type bool.
293 S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
294 diag::err_non_constant_constraint_expression)
295 << SubstitutedAtomicExpr.get()->getSourceRange();
296 for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
297 S.Diag(PDiag.first, PDiag.second);
298 return ExprError();
299 }
300
301 assert(EvalResult.Val.isInt() &&
302 "evaluating bool expression didn't produce int");
303 Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
304 if (!Satisfaction.IsSatisfied)
305 Satisfaction.Details.emplace_back(ConstraintExpr,
306 SubstitutedAtomicExpr.get());
307
308 return SubstitutedAtomicExpr;
309}
310
311static bool
312DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID,
313 const NamedDecl *Templ, const Expr *E,
314 const MultiLevelTemplateArgumentList &MLTAL) {
315 E->Profile(ID, S.Context, /*Canonical=*/true);
316 for (const auto &List : MLTAL)
317 for (const auto &TemplateArg : List.Args)
318 TemplateArg.Profile(ID, S.Context);
319
320 // Note that we have to do this with our own collection, because there are
321 // times where a constraint-expression check can cause us to need to evaluate
322 // other constriants that are unrelated, such as when evaluating a recovery
323 // expression, or when trying to determine the constexpr-ness of special
324 // members. Otherwise we could just use the
325 // Sema::InstantiatingTemplate::isAlreadyBeingInstantiated function.
326 if (S.SatisfactionStackContains(Templ, ID)) {
327 S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self)
328 << const_cast<Expr *>(E) << E->getSourceRange();
329 return true;
330 }
331
332 return false;
333}
334
336 Sema &S, const NamedDecl *Template, SourceLocation TemplateNameLoc,
337 const MultiLevelTemplateArgumentList &MLTAL, const Expr *ConstraintExpr,
338 ConstraintSatisfaction &Satisfaction) {
340 S, ConstraintExpr, Satisfaction, [&](const Expr *AtomicExpr) {
341 EnterExpressionEvaluationContext ConstantEvaluated(
344
345 // Atomic constraint - substitute arguments and check satisfaction.
346 ExprResult SubstitutedExpression;
347 {
348 TemplateDeductionInfo Info(TemplateNameLoc);
351 const_cast<NamedDecl *>(Template), Info,
353 if (Inst.isInvalid())
354 return ExprError();
355
356 llvm::FoldingSetNodeID ID;
357 if (Template &&
358 DiagRecursiveConstraintEval(S, ID, Template, AtomicExpr, MLTAL)) {
359 Satisfaction.IsSatisfied = false;
360 Satisfaction.ContainsErrors = true;
361 return ExprEmpty();
362 }
363
364 SatisfactionStackRAII StackRAII(S, Template, ID);
365
366 // We do not want error diagnostics escaping here.
367 Sema::SFINAETrap Trap(S);
368 SubstitutedExpression =
369 S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
370
371 if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
372 // C++2a [temp.constr.atomic]p1
373 // ...If substitution results in an invalid type or expression, the
374 // constraint is not satisfied.
375 if (!Trap.hasErrorOccurred())
376 // A non-SFINAE error has occurred as a result of this
377 // substitution.
378 return ExprError();
379
382 Info.takeSFINAEDiagnostic(SubstDiag);
383 // FIXME: Concepts: This is an unfortunate consequence of there
384 // being no serialization code for PartialDiagnostics and the fact
385 // that serializing them would likely take a lot more storage than
386 // just storing them as strings. We would still like, in the
387 // future, to serialize the proper PartialDiagnostic as serializing
388 // it as a string defeats the purpose of the diagnostic mechanism.
389 SmallString<128> DiagString;
390 DiagString = ": ";
391 SubstDiag.second.EmitToString(S.getDiagnostics(), DiagString);
392 unsigned MessageSize = DiagString.size();
393 char *Mem = new (S.Context) char[MessageSize];
394 memcpy(Mem, DiagString.c_str(), MessageSize);
395 Satisfaction.Details.emplace_back(
398 SubstDiag.first, StringRef(Mem, MessageSize)});
399 Satisfaction.IsSatisfied = false;
400 return ExprEmpty();
401 }
402 }
403
404 if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
405 return ExprError();
406
407 // [temp.constr.atomic]p3: To determine if an atomic constraint is
408 // satisfied, the parameter mapping and template arguments are first
409 // substituted into its expression. If substitution results in an
410 // invalid type or expression, the constraint is not satisfied.
411 // Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
412 // and E shall be a constant expression of type bool.
413 //
414 // Perform the L to R Value conversion if necessary. We do so for all
415 // non-PRValue categories, else we fail to extend the lifetime of
416 // temporaries, and that fails the constant expression check.
417 if (!SubstitutedExpression.get()->isPRValue())
418 SubstitutedExpression = ImplicitCastExpr::Create(
419 S.Context, SubstitutedExpression.get()->getType(),
420 CK_LValueToRValue, SubstitutedExpression.get(),
421 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
422
423 return SubstitutedExpression;
424 });
425}
426
428 Sema &S, const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
430 const MultiLevelTemplateArgumentList &TemplateArgsLists,
431 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
432 if (ConstraintExprs.empty()) {
433 Satisfaction.IsSatisfied = true;
434 return false;
435 }
436
437 if (TemplateArgsLists.isAnyArgInstantiationDependent()) {
438 // No need to check satisfaction for dependent constraint expressions.
439 Satisfaction.IsSatisfied = true;
440 return false;
441 }
442
443 ArrayRef<TemplateArgument> TemplateArgs =
444 TemplateArgsLists.getNumSubstitutedLevels() > 0
445 ? TemplateArgsLists.getOutermost()
447 Sema::InstantiatingTemplate Inst(S, TemplateIDRange.getBegin(),
449 const_cast<NamedDecl *>(Template), TemplateArgs, TemplateIDRange);
450 if (Inst.isInvalid())
451 return true;
452
453 for (const Expr *ConstraintExpr : ConstraintExprs) {
455 S, Template, TemplateIDRange.getBegin(), TemplateArgsLists,
456 ConstraintExpr, Satisfaction);
457 if (Res.isInvalid())
458 return true;
459
460 Converted.push_back(Res.get());
461 if (!Satisfaction.IsSatisfied) {
462 // Backfill the 'converted' list with nulls so we can keep the Converted
463 // and unconverted lists in sync.
464 Converted.append(ConstraintExprs.size() - Converted.size(), nullptr);
465 // [temp.constr.op] p2
466 // [...] To determine if a conjunction is satisfied, the satisfaction
467 // of the first operand is checked. If that is not satisfied, the
468 // conjunction is not satisfied. [...]
469 return false;
470 }
471 }
472 return false;
473}
474
476 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
477 llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
478 const MultiLevelTemplateArgumentList &TemplateArgsLists,
479 SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction) {
480 if (ConstraintExprs.empty()) {
481 OutSatisfaction.IsSatisfied = true;
482 return false;
483 }
484 if (!Template) {
485 return ::CheckConstraintSatisfaction(
486 *this, nullptr, ConstraintExprs, ConvertedConstraints,
487 TemplateArgsLists, TemplateIDRange, OutSatisfaction);
488 }
489
490 // A list of the template argument list flattened in a predictible manner for
491 // the purposes of caching. The ConstraintSatisfaction type is in AST so it
492 // has no access to the MultiLevelTemplateArgumentList, so this has to happen
493 // here.
495 for (auto List : TemplateArgsLists)
496 FlattenedArgs.insert(FlattenedArgs.end(), List.Args.begin(),
497 List.Args.end());
498
499 llvm::FoldingSetNodeID ID;
500 ConstraintSatisfaction::Profile(ID, Context, Template, FlattenedArgs);
501 void *InsertPos;
502 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
503 OutSatisfaction = *Cached;
504 return false;
505 }
506
507 auto Satisfaction =
508 std::make_unique<ConstraintSatisfaction>(Template, FlattenedArgs);
509 if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,
510 ConvertedConstraints, TemplateArgsLists,
511 TemplateIDRange, *Satisfaction)) {
512 OutSatisfaction = *Satisfaction;
513 return true;
514 }
515
516 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
517 // The evaluation of this constraint resulted in us trying to re-evaluate it
518 // recursively. This isn't really possible, except we try to form a
519 // RecoveryExpr as a part of the evaluation. If this is the case, just
520 // return the 'cached' version (which will have the same result), and save
521 // ourselves the extra-insert. If it ever becomes possible to legitimately
522 // recursively check a constraint, we should skip checking the 'inner' one
523 // above, and replace the cached version with this one, as it would be more
524 // specific.
525 OutSatisfaction = *Cached;
526 return false;
527 }
528
529 // Else we can simply add this satisfaction to the list.
530 OutSatisfaction = *Satisfaction;
531 // We cannot use InsertPos here because CheckConstraintSatisfaction might have
532 // invalidated it.
533 // Note that entries of SatisfactionCache are deleted in Sema's destructor.
534 SatisfactionCache.InsertNode(Satisfaction.release());
535 return false;
536}
537
538bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr,
539 ConstraintSatisfaction &Satisfaction) {
541 *this, ConstraintExpr, Satisfaction,
542 [this](const Expr *AtomicExpr) -> ExprResult {
543 // We only do this to immitate lvalue-to-rvalue conversion.
545 const_cast<Expr *>(AtomicExpr));
546 })
547 .isInvalid();
548}
549
550bool Sema::addInstantiatedCapturesToScope(
551 FunctionDecl *Function, const FunctionDecl *PatternDecl,
553 const MultiLevelTemplateArgumentList &TemplateArgs) {
554 const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
555 const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
556
557 unsigned Instantiated = 0;
558
559 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
560 unsigned Index) {
561 ValueDecl *CapturedVar = LambdaClass->getCapture(Index)->getCapturedVar();
562 if (CapturedVar->isInitCapture())
563 Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
564 };
565
566 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
567 if (!CapturePattern.capturesVariable()) {
568 Instantiated++;
569 continue;
570 }
571 const ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
572 if (!CapturedPattern->isParameterPack()) {
573 AddSingleCapture(CapturedPattern, Instantiated++);
574 } else {
575 Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
576 std::optional<unsigned> NumArgumentsInExpansion =
577 getNumArgumentsInExpansion(CapturedPattern->getType(), TemplateArgs);
578 if (!NumArgumentsInExpansion)
579 continue;
580 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
581 AddSingleCapture(CapturedPattern, Instantiated++);
582 }
583 }
584 return false;
585}
586
587bool Sema::SetupConstraintScope(
588 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
590 if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
591 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
592 InstantiatingTemplate Inst(
593 *this, FD->getPointOfInstantiation(),
595 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
596 SourceRange());
597 if (Inst.isInvalid())
598 return true;
599
600 // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
601 // 'instantiated' parameters and adds it to the context. For the case where
602 // this function is a template being instantiated NOW, we also need to add
603 // the list of current template arguments to the list so that they also can
604 // be picked out of the map.
605 if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
606 MultiLevelTemplateArgumentList JustTemplArgs(FD, SpecArgs->asArray(),
607 /*Final=*/false);
608 if (addInstantiatedParametersToScope(
609 FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
610 return true;
611 }
612
613 // If this is a member function, make sure we get the parameters that
614 // reference the original primary template.
615 // We walk up the instantiated template chain so that nested lambdas get
616 // handled properly.
617 for (FunctionTemplateDecl *FromMemTempl =
618 PrimaryTemplate->getInstantiatedFromMemberTemplate();
619 FromMemTempl;
620 FromMemTempl = FromMemTempl->getInstantiatedFromMemberTemplate()) {
621 if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
622 Scope, MLTAL))
623 return true;
624 }
625
626 return false;
627 }
628
631 FunctionDecl *InstantiatedFrom =
635
636 InstantiatingTemplate Inst(
637 *this, FD->getPointOfInstantiation(),
639 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
640 SourceRange());
641 if (Inst.isInvalid())
642 return true;
643
644 // Case where this was not a template, but instantiated as a
645 // child-function.
646 if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
647 return true;
648 }
649
650 return false;
651}
652
653// This function collects all of the template arguments for the purposes of
654// constraint-instantiation and checking.
655std::optional<MultiLevelTemplateArgumentList>
656Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
657 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
660
661 // Collect the list of template arguments relative to the 'primary' template.
662 // We need the entire list, since the constraint is completely uninstantiated
663 // at this point.
664 MLTAL =
666 /*Final=*/false, /*Innermost=*/std::nullopt,
667 /*RelativeToPrimary=*/true,
668 /*Pattern=*/nullptr,
669 /*ForConstraintInstantiation=*/true);
670 if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
671 return std::nullopt;
672
673 return MLTAL;
674}
675
677 ConstraintSatisfaction &Satisfaction,
678 SourceLocation UsageLoc,
679 bool ForOverloadResolution) {
680 // Don't check constraints if the function is dependent. Also don't check if
681 // this is a function template specialization, as the call to
682 // CheckinstantiatedFunctionTemplateConstraints after this will check it
683 // better.
684 if (FD->isDependentContext() ||
685 FD->getTemplatedKind() ==
687 Satisfaction.IsSatisfied = true;
688 return false;
689 }
690
691 // A lambda conversion operator has the same constraints as the call operator
692 // and constraints checking relies on whether we are in a lambda call operator
693 // (and may refer to its parameters), so check the call operator instead.
694 if (const auto *MD = dyn_cast<CXXConversionDecl>(FD);
695 MD && isLambdaConversionOperator(const_cast<CXXConversionDecl *>(MD)))
696 return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
697 Satisfaction, UsageLoc,
698 ForOverloadResolution);
699
700 DeclContext *CtxToSave = const_cast<FunctionDecl *>(FD);
701
702 while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {
703 if (isLambdaCallOperator(CtxToSave))
704 CtxToSave = CtxToSave->getParent()->getParent();
705 else
706 CtxToSave = CtxToSave->getNonTransparentContext();
707 }
708
709 ContextRAII SavedContext{*this, CtxToSave};
710 LocalInstantiationScope Scope(*this, !ForOverloadResolution);
711 std::optional<MultiLevelTemplateArgumentList> MLTAL =
712 SetupConstraintCheckingTemplateArgumentsAndScope(
713 const_cast<FunctionDecl *>(FD), {}, Scope);
714
715 if (!MLTAL)
716 return true;
717
718 Qualifiers ThisQuals;
719 CXXRecordDecl *Record = nullptr;
720 if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
721 ThisQuals = Method->getMethodQualifiers();
722 Record = const_cast<CXXRecordDecl *>(Method->getParent());
723 }
724 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
725
727 *this, const_cast<FunctionDecl *>(FD), *MLTAL, Scope,
728 ForOverloadResolution);
729
731 FD, {FD->getTrailingRequiresClause()}, *MLTAL,
732 SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
733 Satisfaction);
734}
735
736
737// Figure out the to-translation-unit depth for this function declaration for
738// the purpose of seeing if they differ by constraints. This isn't the same as
739// getTemplateDepth, because it includes already instantiated parents.
740static unsigned
742 bool SkipForSpecialization = false) {
744 ND, ND->getLexicalDeclContext(), /*Final=*/false,
745 /*Innermost=*/std::nullopt,
746 /*RelativeToPrimary=*/true,
747 /*Pattern=*/nullptr,
748 /*ForConstraintInstantiation=*/true, SkipForSpecialization);
749 return MLTAL.getNumLevels();
750}
751
752namespace {
753 class AdjustConstraintDepth : public TreeTransform<AdjustConstraintDepth> {
754 unsigned TemplateDepth = 0;
755 public:
756 using inherited = TreeTransform<AdjustConstraintDepth>;
757 AdjustConstraintDepth(Sema &SemaRef, unsigned TemplateDepth)
758 : inherited(SemaRef), TemplateDepth(TemplateDepth) {}
759
760 using inherited::TransformTemplateTypeParmType;
761 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
762 TemplateTypeParmTypeLoc TL, bool) {
763 const TemplateTypeParmType *T = TL.getTypePtr();
764
765 TemplateTypeParmDecl *NewTTPDecl = nullptr;
766 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
767 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
768 TransformDecl(TL.getNameLoc(), OldTTPDecl));
769
770 QualType Result = getSema().Context.getTemplateTypeParmType(
771 T->getDepth() + TemplateDepth, T->getIndex(), T->isParameterPack(),
772 NewTTPDecl);
774 NewTL.setNameLoc(TL.getNameLoc());
775 return Result;
776 }
777 };
778} // namespace
779
781 Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo,
782 const Expr *ConstrExpr) {
784 DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
785 /*Innermost=*/std::nullopt,
786 /*RelativeToPrimary=*/true,
787 /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
788 /*SkipForSpecialization*/ false);
789
790 if (MLTAL.getNumSubstitutedLevels() == 0)
791 return ConstrExpr;
792
793 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
794
796 S, DeclInfo.getLocation(),
798 const_cast<NamedDecl *>(DeclInfo.getDecl()), SourceRange{});
799 if (Inst.isInvalid())
800 return nullptr;
801
802 // Set up a dummy 'instantiation' scope in the case of reference to function
803 // parameters that the surrounding function hasn't been instantiated yet. Note
804 // this may happen while we're comparing two templates' constraint
805 // equivalence.
806 LocalInstantiationScope ScopeForParameters(S);
807 if (auto *FD = llvm::dyn_cast<FunctionDecl>(DeclInfo.getDecl()))
808 for (auto *PVD : FD->parameters())
809 ScopeForParameters.InstantiatedLocal(PVD, PVD);
810
811 std::optional<Sema::CXXThisScopeRAII> ThisScope;
812
813 // See TreeTransform::RebuildTemplateSpecializationType. A context scope is
814 // essential for having an injected class as the canonical type for a template
815 // specialization type at the rebuilding stage. This guarantees that, for
816 // out-of-line definitions, injected class name types and their equivalent
817 // template specializations can be profiled to the same value, which makes it
818 // possible that e.g. constraints involving C<Class<T>> and C<Class> are
819 // perceived identical.
820 std::optional<Sema::ContextRAII> ContextScope;
821 if (auto *RD = dyn_cast<CXXRecordDecl>(DeclInfo.getDeclContext())) {
822 ThisScope.emplace(S, const_cast<CXXRecordDecl *>(RD), Qualifiers());
823 ContextScope.emplace(S, const_cast<DeclContext *>(cast<DeclContext>(RD)),
824 /*NewThisContext=*/false);
825 }
827 const_cast<clang::Expr *>(ConstrExpr), MLTAL);
828 if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
829 return nullptr;
830 return SubstConstr.get();
831}
832
834 const Expr *OldConstr,
836 const Expr *NewConstr) {
837 if (OldConstr == NewConstr)
838 return true;
839 // C++ [temp.constr.decl]p4
840 if (Old && !New.isInvalid() && !New.ContainsDecl(Old) &&
842 if (const Expr *SubstConstr =
844 OldConstr))
845 OldConstr = SubstConstr;
846 else
847 return false;
848 if (const Expr *SubstConstr =
850 NewConstr))
851 NewConstr = SubstConstr;
852 else
853 return false;
854 }
855
856 llvm::FoldingSetNodeID ID1, ID2;
857 OldConstr->Profile(ID1, Context, /*Canonical=*/true);
858 NewConstr->Profile(ID2, Context, /*Canonical=*/true);
859 return ID1 == ID2;
860}
861
863 assert(FD->getFriendObjectKind() && "Must be a friend!");
864
865 // The logic for non-templates is handled in ASTContext::isSameEntity, so we
866 // don't have to bother checking 'DependsOnEnclosingTemplate' for a
867 // non-function-template.
868 assert(FD->getDescribedFunctionTemplate() &&
869 "Non-function templates don't need to be checked");
870
873
874 unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
875 for (const Expr *Constraint : ACs)
876 if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
877 Constraint))
878 return true;
879
880 return false;
881}
882
884 TemplateDecl *TD, const MultiLevelTemplateArgumentList &TemplateArgsLists,
885 SourceRange TemplateIDRange) {
886 ConstraintSatisfaction Satisfaction;
887 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
888 TD->getAssociatedConstraints(AssociatedConstraints);
889 if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgsLists,
890 TemplateIDRange, Satisfaction))
891 return true;
892
893 if (!Satisfaction.IsSatisfied) {
894 SmallString<128> TemplateArgString;
895 TemplateArgString = " ";
896 TemplateArgString += getTemplateArgumentBindingsText(
897 TD->getTemplateParameters(), TemplateArgsLists.getInnermost().data(),
898 TemplateArgsLists.getInnermost().size());
899
900 Diag(TemplateIDRange.getBegin(),
901 diag::err_template_arg_list_constraints_not_satisfied)
903 << TemplateArgString << TemplateIDRange;
904 DiagnoseUnsatisfiedConstraint(Satisfaction);
905 return true;
906 }
907 return false;
908}
909
911 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
912 ArrayRef<TemplateArgument> TemplateArgs,
913 ConstraintSatisfaction &Satisfaction) {
914 // In most cases we're not going to have constraints, so check for that first.
915 FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
916 // Note - code synthesis context for the constraints check is created
917 // inside CheckConstraintsSatisfaction.
919 Template->getAssociatedConstraints(TemplateAC);
920 if (TemplateAC.empty()) {
921 Satisfaction.IsSatisfied = true;
922 return false;
923 }
924
925 // Enter the scope of this instantiation. We don't use
926 // PushDeclContext because we don't have a scope.
927 Sema::ContextRAII savedContext(*this, Decl);
929
930 std::optional<MultiLevelTemplateArgumentList> MLTAL =
931 SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
932 Scope);
933
934 if (!MLTAL)
935 return true;
936
937 Qualifiers ThisQuals;
938 CXXRecordDecl *Record = nullptr;
939 if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
940 ThisQuals = Method->getMethodQualifiers();
941 Record = Method->getParent();
942 }
943
944 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
946 *this, const_cast<FunctionDecl *>(Decl), *MLTAL, Scope);
947
949 return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
950 PointOfInstantiation, Satisfaction);
951}
952
955 bool First) {
956 assert(!Req->isSatisfied()
957 && "Diagnose() can only be used on an unsatisfied requirement");
958 switch (Req->getSatisfactionStatus()) {
960 llvm_unreachable("Diagnosing a dependent requirement");
961 break;
963 auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
964 if (!SubstDiag->DiagMessage.empty())
965 S.Diag(SubstDiag->DiagLoc,
966 diag::note_expr_requirement_expr_substitution_error)
967 << (int)First << SubstDiag->SubstitutedEntity
968 << SubstDiag->DiagMessage;
969 else
970 S.Diag(SubstDiag->DiagLoc,
971 diag::note_expr_requirement_expr_unknown_substitution_error)
972 << (int)First << SubstDiag->SubstitutedEntity;
973 break;
974 }
976 S.Diag(Req->getNoexceptLoc(),
977 diag::note_expr_requirement_noexcept_not_met)
978 << (int)First << Req->getExpr();
979 break;
981 auto *SubstDiag =
983 if (!SubstDiag->DiagMessage.empty())
984 S.Diag(SubstDiag->DiagLoc,
985 diag::note_expr_requirement_type_requirement_substitution_error)
986 << (int)First << SubstDiag->SubstitutedEntity
987 << SubstDiag->DiagMessage;
988 else
989 S.Diag(SubstDiag->DiagLoc,
990 diag::note_expr_requirement_type_requirement_unknown_substitution_error)
991 << (int)First << SubstDiag->SubstitutedEntity;
992 break;
993 }
995 ConceptSpecializationExpr *ConstraintExpr =
997 if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
998 // A simple case - expr type is the type being constrained and the concept
999 // was not provided arguments.
1000 Expr *e = Req->getExpr();
1001 S.Diag(e->getBeginLoc(),
1002 diag::note_expr_requirement_constraints_not_satisfied_simple)
1004 << ConstraintExpr->getNamedConcept();
1005 } else {
1006 S.Diag(ConstraintExpr->getBeginLoc(),
1007 diag::note_expr_requirement_constraints_not_satisfied)
1008 << (int)First << ConstraintExpr;
1009 }
1011 break;
1012 }
1014 llvm_unreachable("We checked this above");
1015 }
1016}
1017
1020 bool First) {
1021 assert(!Req->isSatisfied()
1022 && "Diagnose() can only be used on an unsatisfied requirement");
1023 switch (Req->getSatisfactionStatus()) {
1025 llvm_unreachable("Diagnosing a dependent requirement");
1026 return;
1028 auto *SubstDiag = Req->getSubstitutionDiagnostic();
1029 if (!SubstDiag->DiagMessage.empty())
1030 S.Diag(SubstDiag->DiagLoc,
1031 diag::note_type_requirement_substitution_error) << (int)First
1032 << SubstDiag->SubstitutedEntity << SubstDiag->DiagMessage;
1033 else
1034 S.Diag(SubstDiag->DiagLoc,
1035 diag::note_type_requirement_unknown_substitution_error)
1036 << (int)First << SubstDiag->SubstitutedEntity;
1037 return;
1038 }
1039 default:
1040 llvm_unreachable("Unknown satisfaction status");
1041 return;
1042 }
1043}
1045 Expr *SubstExpr,
1046 bool First = true);
1047
1050 bool First) {
1051 using SubstitutionDiagnostic = std::pair<SourceLocation, StringRef>;
1052 for (auto &Pair : Req->getConstraintSatisfaction()) {
1053 if (auto *SubstDiag = Pair.second.dyn_cast<SubstitutionDiagnostic *>())
1054 S.Diag(SubstDiag->first, diag::note_nested_requirement_substitution_error)
1055 << (int)First << Req->getInvalidConstraintEntity() << SubstDiag->second;
1056 else
1058 S, Pair.second.dyn_cast<Expr *>(), First);
1059 First = false;
1060 }
1061}
1062
1064 Expr *SubstExpr,
1065 bool First) {
1066 SubstExpr = SubstExpr->IgnoreParenImpCasts();
1067 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
1068 switch (BO->getOpcode()) {
1069 // These two cases will in practice only be reached when using fold
1070 // expressions with || and &&, since otherwise the || and && will have been
1071 // broken down into atomic constraints during satisfaction checking.
1072 case BO_LOr:
1073 // Or evaluated to false - meaning both RHS and LHS evaluated to false.
1076 /*First=*/false);
1077 return;
1078 case BO_LAnd: {
1079 bool LHSSatisfied =
1080 BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1081 if (LHSSatisfied) {
1082 // LHS is true, so RHS must be false.
1084 return;
1085 }
1086 // LHS is false
1088
1089 // RHS might also be false
1090 bool RHSSatisfied =
1091 BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1092 if (!RHSSatisfied)
1094 /*First=*/false);
1095 return;
1096 }
1097 case BO_GE:
1098 case BO_LE:
1099 case BO_GT:
1100 case BO_LT:
1101 case BO_EQ:
1102 case BO_NE:
1103 if (BO->getLHS()->getType()->isIntegerType() &&
1104 BO->getRHS()->getType()->isIntegerType()) {
1105 Expr::EvalResult SimplifiedLHS;
1106 Expr::EvalResult SimplifiedRHS;
1107 BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
1109 /*InConstantContext=*/true);
1110 BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
1112 /*InConstantContext=*/true);
1113 if (!SimplifiedLHS.Diag && ! SimplifiedRHS.Diag) {
1114 S.Diag(SubstExpr->getBeginLoc(),
1115 diag::note_atomic_constraint_evaluated_to_false_elaborated)
1116 << (int)First << SubstExpr
1117 << toString(SimplifiedLHS.Val.getInt(), 10)
1118 << BinaryOperator::getOpcodeStr(BO->getOpcode())
1119 << toString(SimplifiedRHS.Val.getInt(), 10);
1120 return;
1121 }
1122 }
1123 break;
1124
1125 default:
1126 break;
1127 }
1128 } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
1129 if (CSE->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1130 S.Diag(
1131 CSE->getSourceRange().getBegin(),
1132 diag::
1133 note_single_arg_concept_specialization_constraint_evaluated_to_false)
1134 << (int)First
1135 << CSE->getTemplateArgsAsWritten()->arguments()[0].getArgument()
1136 << CSE->getNamedConcept();
1137 } else {
1138 S.Diag(SubstExpr->getSourceRange().getBegin(),
1139 diag::note_concept_specialization_constraint_evaluated_to_false)
1140 << (int)First << CSE;
1141 }
1142 S.DiagnoseUnsatisfiedConstraint(CSE->getSatisfaction());
1143 return;
1144 } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
1145 // FIXME: RequiresExpr should store dependent diagnostics.
1146 for (concepts::Requirement *Req : RE->getRequirements())
1147 if (!Req->isDependent() && !Req->isSatisfied()) {
1148 if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
1150 else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
1152 else
1154 S, cast<concepts::NestedRequirement>(Req), First);
1155 break;
1156 }
1157 return;
1158 }
1159
1160 S.Diag(SubstExpr->getSourceRange().getBegin(),
1161 diag::note_atomic_constraint_evaluated_to_false)
1162 << (int)First << SubstExpr;
1163}
1164
1165template<typename SubstitutionDiagnostic>
1167 Sema &S, const Expr *E,
1168 const llvm::PointerUnion<Expr *, SubstitutionDiagnostic *> &Record,
1169 bool First = true) {
1170 if (auto *Diag = Record.template dyn_cast<SubstitutionDiagnostic *>()){
1171 S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
1172 << Diag->second;
1173 return;
1174 }
1175
1177 Record.template get<Expr *>(), First);
1178}
1179
1180void
1182 bool First) {
1183 assert(!Satisfaction.IsSatisfied &&
1184 "Attempted to diagnose a satisfied constraint");
1185 for (auto &Pair : Satisfaction.Details) {
1186 diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
1187 First = false;
1188 }
1189}
1190
1192 const ASTConstraintSatisfaction &Satisfaction,
1193 bool First) {
1194 assert(!Satisfaction.IsSatisfied &&
1195 "Attempted to diagnose a satisfied constraint");
1196 for (auto &Pair : Satisfaction) {
1197 diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
1198 First = false;
1199 }
1200}
1201
1204 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints) {
1205 // In case the ConstrainedDecl comes from modules, it is necessary to use
1206 // the canonical decl to avoid different atomic constraints with the 'same'
1207 // declarations.
1208 ConstrainedDecl = cast<NamedDecl>(ConstrainedDecl->getCanonicalDecl());
1209
1210 auto CacheEntry = NormalizationCache.find(ConstrainedDecl);
1211 if (CacheEntry == NormalizationCache.end()) {
1212 auto Normalized =
1213 NormalizedConstraint::fromConstraintExprs(*this, ConstrainedDecl,
1214 AssociatedConstraints);
1215 CacheEntry =
1216 NormalizationCache
1217 .try_emplace(ConstrainedDecl,
1218 Normalized
1220 std::move(*Normalized))
1221 : nullptr)
1222 .first;
1223 }
1224 return CacheEntry->second;
1225}
1226
1227static bool
1229 ConceptDecl *Concept,
1230 const MultiLevelTemplateArgumentList &MLTAL,
1231 const ASTTemplateArgumentListInfo *ArgsAsWritten) {
1232 if (!N.isAtomic()) {
1233 if (substituteParameterMappings(S, N.getLHS(), Concept, MLTAL,
1234 ArgsAsWritten))
1235 return true;
1236 return substituteParameterMappings(S, N.getRHS(), Concept, MLTAL,
1237 ArgsAsWritten);
1238 }
1239 TemplateParameterList *TemplateParams = Concept->getTemplateParameters();
1240
1242 TemplateArgumentListInfo SubstArgs;
1243 if (!Atomic.ParameterMapping) {
1244 llvm::SmallBitVector OccurringIndices(TemplateParams->size());
1245 S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
1246 /*Depth=*/0, OccurringIndices);
1247 TemplateArgumentLoc *TempArgs =
1248 new (S.Context) TemplateArgumentLoc[OccurringIndices.count()];
1249 for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
1250 if (OccurringIndices[I])
1251 new (&(TempArgs)[J++])
1253 TemplateParams->begin()[I],
1254 // Here we assume we do not support things like
1255 // template<typename A, typename B>
1256 // concept C = ...;
1257 //
1258 // template<typename... Ts> requires C<Ts...>
1259 // struct S { };
1260 // The above currently yields a diagnostic.
1261 // We still might have default arguments for concept parameters.
1262 ArgsAsWritten->NumTemplateArgs > I
1263 ? ArgsAsWritten->arguments()[I].getLocation()
1264 : SourceLocation()));
1265 Atomic.ParameterMapping.emplace(TempArgs, OccurringIndices.count());
1266 }
1268 S, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
1270 ArgsAsWritten->arguments().front().getSourceRange());
1271 if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs))
1272 return true;
1273
1274 TemplateArgumentLoc *TempArgs =
1275 new (S.Context) TemplateArgumentLoc[SubstArgs.size()];
1276 std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
1277 TempArgs);
1278 Atomic.ParameterMapping.emplace(TempArgs, SubstArgs.size());
1279 return false;
1280}
1281
1283 const ConceptSpecializationExpr *CSE) {
1286 /*Final=*/false, CSE->getTemplateArguments(),
1287 /*RelativeToPrimary=*/true,
1288 /*Pattern=*/nullptr,
1289 /*ForConstraintInstantiation=*/true);
1290
1291 return substituteParameterMappings(S, N, CSE->getNamedConcept(), MLTAL,
1293}
1294
1295std::optional<NormalizedConstraint>
1296NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
1298 assert(E.size() != 0);
1299 auto Conjunction = fromConstraintExpr(S, D, E[0]);
1300 if (!Conjunction)
1301 return std::nullopt;
1302 for (unsigned I = 1; I < E.size(); ++I) {
1303 auto Next = fromConstraintExpr(S, D, E[I]);
1304 if (!Next)
1305 return std::nullopt;
1306 *Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
1307 std::move(*Next), CCK_Conjunction);
1308 }
1309 return Conjunction;
1310}
1311
1312std::optional<NormalizedConstraint>
1313NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) {
1314 assert(E != nullptr);
1315
1316 // C++ [temp.constr.normal]p1.1
1317 // [...]
1318 // - The normal form of an expression (E) is the normal form of E.
1319 // [...]
1320 E = E->IgnoreParenImpCasts();
1321
1322 // C++2a [temp.param]p4:
1323 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1324 // Fold expression is considered atomic constraints per current wording.
1325 // See http://cplusplus.github.io/concepts-ts/ts-active.html#28
1326
1327 if (LogicalBinOp BO = E) {
1328 auto LHS = fromConstraintExpr(S, D, BO.getLHS());
1329 if (!LHS)
1330 return std::nullopt;
1331 auto RHS = fromConstraintExpr(S, D, BO.getRHS());
1332 if (!RHS)
1333 return std::nullopt;
1334
1335 return NormalizedConstraint(S.Context, std::move(*LHS), std::move(*RHS),
1336 BO.isAnd() ? CCK_Conjunction : CCK_Disjunction);
1337 } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
1338 const NormalizedConstraint *SubNF;
1339 {
1341 S, CSE->getExprLoc(),
1343 CSE->getSourceRange());
1344 // C++ [temp.constr.normal]p1.1
1345 // [...]
1346 // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
1347 // where C names a concept, is the normal form of the
1348 // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
1349 // respective template parameters in the parameter mappings in each atomic
1350 // constraint. If any such substitution results in an invalid type or
1351 // expression, the program is ill-formed; no diagnostic is required.
1352 // [...]
1353 ConceptDecl *CD = CSE->getNamedConcept();
1355 {CD->getConstraintExpr()});
1356 if (!SubNF)
1357 return std::nullopt;
1358 }
1359
1360 std::optional<NormalizedConstraint> New;
1361 New.emplace(S.Context, *SubNF);
1362
1363 if (substituteParameterMappings(S, *New, CSE))
1364 return std::nullopt;
1365
1366 return New;
1367 }
1368 return NormalizedConstraint{new (S.Context) AtomicConstraint(S, E)};
1369}
1370
1373
1374static NormalForm makeCNF(const NormalizedConstraint &Normalized) {
1375 if (Normalized.isAtomic())
1376 return {{Normalized.getAtomicConstraint()}};
1377
1378 NormalForm LCNF = makeCNF(Normalized.getLHS());
1379 NormalForm RCNF = makeCNF(Normalized.getRHS());
1381 LCNF.reserve(LCNF.size() + RCNF.size());
1382 while (!RCNF.empty())
1383 LCNF.push_back(RCNF.pop_back_val());
1384 return LCNF;
1385 }
1386
1387 // Disjunction
1388 NormalForm Res;
1389 Res.reserve(LCNF.size() * RCNF.size());
1390 for (auto &LDisjunction : LCNF)
1391 for (auto &RDisjunction : RCNF) {
1392 NormalForm::value_type Combined;
1393 Combined.reserve(LDisjunction.size() + RDisjunction.size());
1394 std::copy(LDisjunction.begin(), LDisjunction.end(),
1395 std::back_inserter(Combined));
1396 std::copy(RDisjunction.begin(), RDisjunction.end(),
1397 std::back_inserter(Combined));
1398 Res.emplace_back(Combined);
1399 }
1400 return Res;
1401}
1402
1403static NormalForm makeDNF(const NormalizedConstraint &Normalized) {
1404 if (Normalized.isAtomic())
1405 return {{Normalized.getAtomicConstraint()}};
1406
1407 NormalForm LDNF = makeDNF(Normalized.getLHS());
1408 NormalForm RDNF = makeDNF(Normalized.getRHS());
1410 LDNF.reserve(LDNF.size() + RDNF.size());
1411 while (!RDNF.empty())
1412 LDNF.push_back(RDNF.pop_back_val());
1413 return LDNF;
1414 }
1415
1416 // Conjunction
1417 NormalForm Res;
1418 Res.reserve(LDNF.size() * RDNF.size());
1419 for (auto &LConjunction : LDNF) {
1420 for (auto &RConjunction : RDNF) {
1421 NormalForm::value_type Combined;
1422 Combined.reserve(LConjunction.size() + RConjunction.size());
1423 std::copy(LConjunction.begin(), LConjunction.end(),
1424 std::back_inserter(Combined));
1425 std::copy(RConjunction.begin(), RConjunction.end(),
1426 std::back_inserter(Combined));
1427 Res.emplace_back(Combined);
1428 }
1429 }
1430 return Res;
1431}
1432
1433template<typename AtomicSubsumptionEvaluator>
1434static bool subsumes(const NormalForm &PDNF, const NormalForm &QCNF,
1435 AtomicSubsumptionEvaluator E) {
1436 // C++ [temp.constr.order] p2
1437 // Then, P subsumes Q if and only if, for every disjunctive clause Pi in the
1438 // disjunctive normal form of P, Pi subsumes every conjunctive clause Qj in
1439 // the conjuctive normal form of Q, where [...]
1440 for (const auto &Pi : PDNF) {
1441 for (const auto &Qj : QCNF) {
1442 // C++ [temp.constr.order] p2
1443 // - [...] a disjunctive clause Pi subsumes a conjunctive clause Qj if
1444 // and only if there exists an atomic constraint Pia in Pi for which
1445 // there exists an atomic constraint, Qjb, in Qj such that Pia
1446 // subsumes Qjb.
1447 bool Found = false;
1448 for (const AtomicConstraint *Pia : Pi) {
1449 for (const AtomicConstraint *Qjb : Qj) {
1450 if (E(*Pia, *Qjb)) {
1451 Found = true;
1452 break;
1453 }
1454 }
1455 if (Found)
1456 break;
1457 }
1458 if (!Found)
1459 return false;
1460 }
1461 }
1462 return true;
1463}
1464
1465template<typename AtomicSubsumptionEvaluator>
1467 NamedDecl *DQ, ArrayRef<const Expr *> Q, bool &Subsumes,
1468 AtomicSubsumptionEvaluator E) {
1469 // C++ [temp.constr.order] p2
1470 // In order to determine if a constraint P subsumes a constraint Q, P is
1471 // transformed into disjunctive normal form, and Q is transformed into
1472 // conjunctive normal form. [...]
1473 auto *PNormalized = S.getNormalizedAssociatedConstraints(DP, P);
1474 if (!PNormalized)
1475 return true;
1476 const NormalForm PDNF = makeDNF(*PNormalized);
1477
1478 auto *QNormalized = S.getNormalizedAssociatedConstraints(DQ, Q);
1479 if (!QNormalized)
1480 return true;
1481 const NormalForm QCNF = makeCNF(*QNormalized);
1482
1483 Subsumes = subsumes(PDNF, QCNF, E);
1484 return false;
1485}
1486
1489 NamedDecl *D2,
1491 bool &Result) {
1492 if (const auto *FD1 = dyn_cast<FunctionDecl>(D1)) {
1493 auto IsExpectedEntity = [](const FunctionDecl *FD) {
1495 return Kind == FunctionDecl::TK_NonTemplate ||
1497 };
1498 const auto *FD2 = dyn_cast<FunctionDecl>(D2);
1499 (void)IsExpectedEntity;
1500 (void)FD1;
1501 (void)FD2;
1502 assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
1503 "use non-instantiated function declaration for constraints partial "
1504 "ordering");
1505 }
1506
1507 if (AC1.empty()) {
1508 Result = AC2.empty();
1509 return false;
1510 }
1511 if (AC2.empty()) {
1512 // TD1 has associated constraints and TD2 does not.
1513 Result = true;
1514 return false;
1515 }
1516
1517 std::pair<NamedDecl *, NamedDecl *> Key{D1, D2};
1518 auto CacheEntry = SubsumptionCache.find(Key);
1519 if (CacheEntry != SubsumptionCache.end()) {
1520 Result = CacheEntry->second;
1521 return false;
1522 }
1523
1524 unsigned Depth1 = CalculateTemplateDepthForConstraints(*this, D1, true);
1525 unsigned Depth2 = CalculateTemplateDepthForConstraints(*this, D2, true);
1526
1527 for (size_t I = 0; I != AC1.size() && I != AC2.size(); ++I) {
1528 if (Depth2 > Depth1) {
1529 AC1[I] = AdjustConstraintDepth(*this, Depth2 - Depth1)
1530 .TransformExpr(const_cast<Expr *>(AC1[I]))
1531 .get();
1532 } else if (Depth1 > Depth2) {
1533 AC2[I] = AdjustConstraintDepth(*this, Depth1 - Depth2)
1534 .TransformExpr(const_cast<Expr *>(AC2[I]))
1535 .get();
1536 }
1537 }
1538
1539 if (subsumes(*this, D1, AC1, D2, AC2, Result,
1540 [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1541 return A.subsumes(Context, B);
1542 }))
1543 return true;
1544 SubsumptionCache.try_emplace(Key, Result);
1545 return false;
1546}
1547
1550 if (isSFINAEContext())
1551 // No need to work here because our notes would be discarded.
1552 return false;
1553
1554 if (AC1.empty() || AC2.empty())
1555 return false;
1556
1557 auto NormalExprEvaluator =
1558 [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1559 return A.subsumes(Context, B);
1560 };
1561
1562 const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
1563 auto IdenticalExprEvaluator =
1564 [&] (const AtomicConstraint &A, const AtomicConstraint &B) {
1566 return false;
1567 const Expr *EA = A.ConstraintExpr, *EB = B.ConstraintExpr;
1568 if (EA == EB)
1569 return true;
1570
1571 // Not the same source level expression - are the expressions
1572 // identical?
1573 llvm::FoldingSetNodeID IDA, IDB;
1574 EA->Profile(IDA, Context, /*Canonical=*/true);
1575 EB->Profile(IDB, Context, /*Canonical=*/true);
1576 if (IDA != IDB)
1577 return false;
1578
1579 AmbiguousAtomic1 = EA;
1580 AmbiguousAtomic2 = EB;
1581 return true;
1582 };
1583
1584 {
1585 // The subsumption checks might cause diagnostics
1586 SFINAETrap Trap(*this);
1587 auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
1588 if (!Normalized1)
1589 return false;
1590 const NormalForm DNF1 = makeDNF(*Normalized1);
1591 const NormalForm CNF1 = makeCNF(*Normalized1);
1592
1593 auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
1594 if (!Normalized2)
1595 return false;
1596 const NormalForm DNF2 = makeDNF(*Normalized2);
1597 const NormalForm CNF2 = makeCNF(*Normalized2);
1598
1599 bool Is1AtLeastAs2Normally = subsumes(DNF1, CNF2, NormalExprEvaluator);
1600 bool Is2AtLeastAs1Normally = subsumes(DNF2, CNF1, NormalExprEvaluator);
1601 bool Is1AtLeastAs2 = subsumes(DNF1, CNF2, IdenticalExprEvaluator);
1602 bool Is2AtLeastAs1 = subsumes(DNF2, CNF1, IdenticalExprEvaluator);
1603 if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
1604 Is2AtLeastAs1 == Is2AtLeastAs1Normally)
1605 // Same result - no ambiguity was caused by identical atomic expressions.
1606 return false;
1607 }
1608
1609 // A different result! Some ambiguous atomic constraint(s) caused a difference
1610 assert(AmbiguousAtomic1 && AmbiguousAtomic2);
1611
1612 Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
1613 << AmbiguousAtomic1->getSourceRange();
1614 Diag(AmbiguousAtomic2->getBeginLoc(),
1615 diag::note_ambiguous_atomic_constraints_similar_expression)
1616 << AmbiguousAtomic2->getSourceRange();
1617 return true;
1618}
1619
1621 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
1623 ConceptSpecializationExpr *SubstitutedConstraintExpr) :
1624 Requirement(IsSimple ? RK_Simple : RK_Compound, Status == SS_Dependent,
1625 Status == SS_Dependent &&
1626 (E->containsUnexpandedParameterPack() ||
1627 Req.containsUnexpandedParameterPack()),
1628 Status == SS_Satisfied), Value(E), NoexceptLoc(NoexceptLoc),
1629 TypeReq(Req), SubstitutedConstraintExpr(SubstitutedConstraintExpr),
1630 Status(Status) {
1631 assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1632 "Simple requirement must not have a return type requirement or a "
1633 "noexcept specification");
1634 assert((Status > SS_TypeRequirementSubstitutionFailure && Req.isTypeConstraint()) ==
1635 (SubstitutedConstraintExpr != nullptr));
1636}
1637
1639 SubstitutionDiagnostic *ExprSubstDiag, bool IsSimple,
1640 SourceLocation NoexceptLoc, ReturnTypeRequirement Req) :
1641 Requirement(IsSimple ? RK_Simple : RK_Compound, Req.isDependent(),
1642 Req.containsUnexpandedParameterPack(), /*IsSatisfied=*/false),
1643 Value(ExprSubstDiag), NoexceptLoc(NoexceptLoc), TypeReq(Req),
1644 Status(SS_ExprSubstitutionFailure) {
1645 assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1646 "Simple requirement must not have a return type requirement or a "
1647 "noexcept specification");
1648}
1649
1652 TypeConstraintInfo(TPL, false) {
1653 assert(TPL->size() == 1);
1654 const TypeConstraint *TC =
1655 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint();
1656 assert(TC &&
1657 "TPL must have a template type parameter with a type constraint");
1658 auto *Constraint =
1659 cast<ConceptSpecializationExpr>(TC->getImmediatelyDeclaredConstraint());
1660 bool Dependent =
1661 Constraint->getTemplateArgsAsWritten() &&
1663 Constraint->getTemplateArgsAsWritten()->arguments().drop_front(1));
1664 TypeConstraintInfo.setInt(Dependent ? true : false);
1665}
1666
1668 Requirement(RK_Type, T->getType()->isInstantiationDependentType(),
1669 T->getType()->containsUnexpandedParameterPack(),
1670 // We reach this ctor with either dependent types (in which
1671 // IsSatisfied doesn't matter) or with non-dependent type in
1672 // which the existence of the type indicates satisfaction.
1673 /*IsSatisfied=*/true),
1674 Value(T),
1675 Status(T->getType()->isInstantiationDependentType() ? SS_Dependent
1676 : SS_Satisfied) {}
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines Expressions and AST nodes for C++2a concepts.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Defines and computes precedence levels for binary/ternary operators.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static NormalForm makeCNF(const NormalizedConstraint &Normalized)
static bool subsumes(const NormalForm &PDNF, const NormalForm &QCNF, AtomicSubsumptionEvaluator E)
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, llvm::SmallVectorImpl< Expr * > &Converted, const MultiLevelTemplateArgumentList &TemplateArgsLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
static NormalForm makeDNF(const NormalizedConstraint &Normalized)
static const Expr * SubstituteConstraintExpressionWithoutSatisfaction(Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo, const Expr *ConstrExpr)
static ExprResult calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction, AtomicEvaluator &&Evaluator)
static void diagnoseUnsatisfiedConstraintExpr(Sema &S, const Expr *E, const llvm::PointerUnion< Expr *, SubstitutionDiagnostic * > &Record, bool First=true)
static bool DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID, const NamedDecl *Templ, const Expr *E, const MultiLevelTemplateArgumentList &MLTAL)
static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S, Expr *SubstExpr, bool First=true)
static void diagnoseUnsatisfiedRequirement(Sema &S, concepts::ExprRequirement *Req, bool First)
static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N, ConceptDecl *Concept, const MultiLevelTemplateArgumentList &MLTAL, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static unsigned CalculateTemplateDepthForConstraints(Sema &S, const NamedDecl *ND, bool SkipForSpecialization=false)
static bool isInvalid(LocType Loc, bool *Invalid)
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
APSInt & getInt()
Definition: APValue.h:423
bool isInt() const
Definition: APValue.h:401
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType BoolTy
Definition: ASTContext.h:1087
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6407
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6514
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3810
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2156
StringRef getOpcodeStr() const
Definition: Expr.h:3875
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4740
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2118
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprConcepts.h:143
ArrayRef< TemplateArgument > getTemplateArguments() const
Definition: ExprConcepts.h:81
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ExprConcepts.h:98
const ASTConstraintSatisfaction & getSatisfaction() const
Get elaborated satisfaction info about the template arguments' satisfaction of the named concept.
Definition: ExprConcepts.h:133
ConceptDecl * getNamedConcept() const
Definition: ExprConcepts.h:87
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
llvm::SmallVector< std::pair< const Expr *, Detail >, 4 > Details
Pairs of unsatisfied atomic constraint expressions along with the substituted constraint expr,...
Definition: ASTConcept.h:60
std::pair< SourceLocation, StringRef > SubstitutionDiagnostic
Definition: ASTConcept.h:50
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C)
Definition: ASTConcept.h:62
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1294
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1260
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1341
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition: Expr.h:110
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:655
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:186
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3034
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:239
bool isPRValue() const
Definition: Expr.h:272
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:266
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:875
Represents a function declaration or definition.
Definition: Decl.h:1959
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3997
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4317
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4117
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4133
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4061
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition: Decl.h:1964
@ TK_MemberSpecialization
Definition: Decl.h:1971
@ TK_DependentNonTemplate
Definition: Decl.h:1980
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1975
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3948
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4021
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3969
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2049
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void InstantiatedLocal(const Decl *D, Decl *Inst)
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
const ArgList & getOutermost() const
Retrieve the outermost template argument list.
Definition: Template.h:269
This represents a decl that may have a name.
Definition: Decl.h:249
void EmitToString(DiagnosticsEngine &Diags, SmallVectorImpl< char > &Buf) const
A (possibly-)qualified type.
Definition: Type.h:737
The collection of all-type qualifiers we support.
Definition: Type.h:147
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6913
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1101
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:10126
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:10157
SourceLocation getLocation() const
Definition: Sema.h:8806
bool ContainsDecl(const NamedDecl *ND) const
Definition: Sema.h:8796
const DeclContext * getDeclContext() const
Definition: Sema.h:8802
const NamedDecl * getDecl() const
Definition: Sema.h:8794
const DeclContext * getLexicalDeclContext() const
Definition: Sema.h:8798
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:425
bool CheckInstantiatedFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1924
ASTContext & Context
Definition: Sema.h:476
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1798
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckConstraintExpression(const Expr *CE, Token NextToken=Token(), bool *PossibleNonPrimary=nullptr, bool IsTrailingRequiresClause=false)
Check whether the given expression is a valid constraint expression.
Definition: SemaConcept.cpp:91
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
const LangOptions & getLangOpts() const
Definition: Sema.h:1794
@ ReuseLambdaContextDecl
Definition: Sema.h:5625
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:7675
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:2132
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1301
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void PushSatisfactionStackEntry(const NamedDecl *D, const llvm::FoldingSetNodeID &ID)
Definition: Sema.h:7598
void PopSatisfactionStackEntry()
Definition: Sema.h:7604
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool SatisfactionStackContains(const NamedDecl *D, const llvm::FoldingSetNodeID &ID) const
Definition: Sema.h:7606
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
const NormalizedConstraint * getNormalizedAssociatedConstraints(NamedDecl *ConstrainedDecl, ArrayRef< const Expr * > AssociatedConstraints)
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4100
Declaration of a template type parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:5324
bool isParameterPack() const
Definition: Type.h:5322
unsigned getIndex() const
Definition: Type.h:5321
unsigned getDepth() const
Definition: Type.h:5320
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
tok::TokenKind getKind() const
Definition: Token.h:94
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
A container of type source information.
Definition: Type.h:6872
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1606
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7411
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2419
bool isFunctionType() const
Definition: Type.h:7149
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5314
ReturnTypeRequirement()
No return type requirement was specified.
Definition: ExprConcepts.h:300
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:340
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
Definition: ExprConcepts.h:408
ConceptSpecializationExpr * getReturnTypeRequirementSubstitutedConstraintExpr() const
Definition: ExprConcepts.h:403
const ReturnTypeRequirement & getReturnTypeRequirement() const
Definition: ExprConcepts.h:398
SatisfactionStatus getSatisfactionStatus() const
Definition: ExprConcepts.h:392
SourceLocation getNoexceptLoc() const
Definition: ExprConcepts.h:390
ExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc, ReturnTypeRequirement Req, SatisfactionStatus Status, ConceptSpecializationExpr *SubstitutedConstraintExpr=nullptr)
Construct a compound requirement.
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
Definition: ExprConcepts.h:484
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
bool containsUnexpandedParameterPack() const
Definition: ExprConcepts.h:218
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:260
SatisfactionStatus getSatisfactionStatus() const
Definition: ExprConcepts.h:251
TypeRequirement(TypeSourceInfo *T)
Construct a type requirement from a type.
Provides information about an attempted template argument deduction, whose success or failure was des...
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ CPlusPlus11
Definition: LangStandard.h:55
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
ExprResult ExprEmpty()
Definition: Ownership.h:271
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
ExprResult ExprError()
Definition: Ownership.h:264
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:62
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:93
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
bool subsumes(ASTContext &C, const AtomicConstraint &Other) const
Definition: SemaConcept.h:57
bool hasMatchingParameterMapping(ASTContext &C, const AtomicConstraint &Other) const
Definition: SemaConcept.h:36
const Expr * ConstraintExpr
Definition: SemaConcept.h:30
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:629
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:631
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:617
A normalized constraint, as defined in C++ [temp.constr.normal], is either an atomic constraint,...
Definition: SemaConcept.h:81
AtomicConstraint * getAtomicConstraint() const
Definition: SemaConcept.h:140
CompoundConstraintKind getCompoundKind() const
Definition: SemaConcept.h:123
NormalizedConstraint & getRHS() const
Definition: SemaConcept.h:135
NormalizedConstraint & getLHS() const
Definition: SemaConcept.h:130
A stack object to be created when performing template instantiation.
Definition: Sema.h:9802
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:9953