blob: e5c0fa28c11f20ab3255bf79d2060a18f5f02ff1 [file] [log] [blame]
Saar Raz5d98ba62019-10-15 15:24:26 +00001//===-- SemaConcept.cpp - Semantic Analysis for Constraints and Concepts --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ constraints and concepts.
11//
12//===----------------------------------------------------------------------===//
13
Saar Razb65b1f32020-01-09 15:07:51 +020014#include "clang/Sema/SemaConcept.h"
Saar Raz5d98ba62019-10-15 15:24:26 +000015#include "clang/Sema/Sema.h"
Saar Razfdf80e82019-12-06 01:30:21 +020016#include "clang/Sema/SemaInternal.h"
Saar Raz5d98ba62019-10-15 15:24:26 +000017#include "clang/Sema/SemaDiagnostic.h"
18#include "clang/Sema/TemplateDeduction.h"
19#include "clang/Sema/Template.h"
Saar Raza0f50d72020-01-18 09:11:43 +020020#include "clang/Sema/Overload.h"
21#include "clang/Sema/Initialization.h"
22#include "clang/Sema/SemaInternal.h"
23#include "clang/AST/ExprConcepts.h"
Saar Razdf061c32019-12-23 08:37:35 +020024#include "clang/AST/RecursiveASTVisitor.h"
Saar Razb65b1f32020-01-09 15:07:51 +020025#include "clang/Basic/OperatorPrecedence.h"
Saar Razfdf80e82019-12-06 01:30:21 +020026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/PointerUnion.h"
Saar Raz5d98ba62019-10-15 15:24:26 +000028using namespace clang;
29using namespace sema;
30
Saar Razb65b1f32020-01-09 15:07:51 +020031bool
32Sema::CheckConstraintExpression(Expr *ConstraintExpression, Token NextToken,
33 bool *PossibleNonPrimary,
34 bool IsTrailingRequiresClause) {
Saar Raz5d98ba62019-10-15 15:24:26 +000035 // C++2a [temp.constr.atomic]p1
36 // ..E shall be a constant expression of type bool.
37
38 ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
39
40 if (auto *BinOp = dyn_cast<BinaryOperator>(ConstraintExpression)) {
41 if (BinOp->getOpcode() == BO_LAnd || BinOp->getOpcode() == BO_LOr)
Saar Razb65b1f32020-01-09 15:07:51 +020042 return CheckConstraintExpression(BinOp->getLHS(), NextToken,
43 PossibleNonPrimary) &&
44 CheckConstraintExpression(BinOp->getRHS(), NextToken,
45 PossibleNonPrimary);
Saar Raz5d98ba62019-10-15 15:24:26 +000046 } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
Saar Razb65b1f32020-01-09 15:07:51 +020047 return CheckConstraintExpression(C->getSubExpr(), NextToken,
48 PossibleNonPrimary);
Saar Raz5d98ba62019-10-15 15:24:26 +000049
50 QualType Type = ConstraintExpression->getType();
Saar Razb65b1f32020-01-09 15:07:51 +020051
52 auto CheckForNonPrimary = [&] {
53 if (PossibleNonPrimary)
54 *PossibleNonPrimary =
55 // We have the following case:
56 // template<typename> requires func(0) struct S { };
57 // The user probably isn't aware of the parentheses required around
58 // the function call, and we're only going to parse 'func' as the
59 // primary-expression, and complain that it is of non-bool type.
60 (NextToken.is(tok::l_paren) &&
61 (IsTrailingRequiresClause ||
62 (Type->isDependentType() &&
63 IsDependentFunctionNameExpr(ConstraintExpression)) ||
64 Type->isFunctionType() ||
65 Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
66 // We have the following case:
67 // template<typename T> requires size_<T> == 0 struct S { };
68 // The user probably isn't aware of the parentheses required around
69 // the binary operator, and we're only going to parse 'func' as the
70 // first operand, and complain that it is of non-bool type.
71 getBinOpPrecedence(NextToken.getKind(),
72 /*GreaterThanIsOperator=*/true,
73 getLangOpts().CPlusPlus11) > prec::LogicalAnd;
74 };
75
76 // An atomic constraint!
77 if (ConstraintExpression->isTypeDependent()) {
78 CheckForNonPrimary();
79 return true;
80 }
81
Saar Raz5d98ba62019-10-15 15:24:26 +000082 if (!Context.hasSameUnqualifiedType(Type, Context.BoolTy)) {
83 Diag(ConstraintExpression->getExprLoc(),
84 diag::err_non_bool_atomic_constraint) << Type
85 << ConstraintExpression->getSourceRange();
Saar Razb65b1f32020-01-09 15:07:51 +020086 CheckForNonPrimary();
Saar Raz5d98ba62019-10-15 15:24:26 +000087 return false;
88 }
Saar Razb65b1f32020-01-09 15:07:51 +020089
90 if (PossibleNonPrimary)
91 *PossibleNonPrimary = false;
Saar Raz5d98ba62019-10-15 15:24:26 +000092 return true;
93}
94
Saar Razfdf80e82019-12-06 01:30:21 +020095template <typename AtomicEvaluator>
96static bool
97calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
98 ConstraintSatisfaction &Satisfaction,
99 AtomicEvaluator &&Evaluator) {
Saar Raz5d98ba62019-10-15 15:24:26 +0000100 ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
101
102 if (auto *BO = dyn_cast<BinaryOperator>(ConstraintExpr)) {
Saar Razfdf80e82019-12-06 01:30:21 +0200103 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
104 if (calculateConstraintSatisfaction(S, BO->getLHS(), Satisfaction,
105 Evaluator))
Saar Raz5d98ba62019-10-15 15:24:26 +0000106 return true;
Saar Razfdf80e82019-12-06 01:30:21 +0200107
108 bool IsLHSSatisfied = Satisfaction.IsSatisfied;
109
110 if (BO->getOpcode() == BO_LOr && IsLHSSatisfied)
111 // [temp.constr.op] p3
112 // A disjunction is a constraint taking two operands. To determine if
113 // a disjunction is satisfied, the satisfaction of the first operand
114 // is checked. If that is satisfied, the disjunction is satisfied.
115 // Otherwise, the disjunction is satisfied if and only if the second
116 // operand is satisfied.
Saar Raz5d98ba62019-10-15 15:24:26 +0000117 return false;
Saar Razfdf80e82019-12-06 01:30:21 +0200118
119 if (BO->getOpcode() == BO_LAnd && !IsLHSSatisfied)
120 // [temp.constr.op] p2
121 // A conjunction is a constraint taking two operands. To determine if
122 // a conjunction is satisfied, the satisfaction of the first operand
123 // is checked. If that is not satisfied, the conjunction is not
124 // satisfied. Otherwise, the conjunction is satisfied if and only if
125 // the second operand is satisfied.
Saar Raz5d98ba62019-10-15 15:24:26 +0000126 return false;
Saar Razfdf80e82019-12-06 01:30:21 +0200127
128 return calculateConstraintSatisfaction(S, BO->getRHS(), Satisfaction,
129 std::forward<AtomicEvaluator>(Evaluator));
Saar Raz5d98ba62019-10-15 15:24:26 +0000130 }
131 }
132 else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpr))
Saar Razfdf80e82019-12-06 01:30:21 +0200133 return calculateConstraintSatisfaction(S, C->getSubExpr(), Satisfaction,
134 std::forward<AtomicEvaluator>(Evaluator));
Saar Razffa214e2019-10-25 00:09:37 +0300135
Saar Razfdf80e82019-12-06 01:30:21 +0200136 // An atomic constraint expression
137 ExprResult SubstitutedAtomicExpr = Evaluator(ConstraintExpr);
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700138
Saar Razfdf80e82019-12-06 01:30:21 +0200139 if (SubstitutedAtomicExpr.isInvalid())
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700140 return true;
141
Saar Razfdf80e82019-12-06 01:30:21 +0200142 if (!SubstitutedAtomicExpr.isUsable())
143 // Evaluator has decided satisfaction without yielding an expression.
144 return false;
145
146 EnterExpressionEvaluationContext ConstantEvaluated(
147 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Saar Raz5d98ba62019-10-15 15:24:26 +0000148 SmallVector<PartialDiagnosticAt, 2> EvaluationDiags;
149 Expr::EvalResult EvalResult;
150 EvalResult.Diag = &EvaluationDiags;
Saar Razfdf80e82019-12-06 01:30:21 +0200151 if (!SubstitutedAtomicExpr.get()->EvaluateAsRValue(EvalResult, S.Context)) {
152 // C++2a [temp.constr.atomic]p1
153 // ...E shall be a constant expression of type bool.
154 S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
155 diag::err_non_constant_constraint_expression)
156 << SubstitutedAtomicExpr.get()->getSourceRange();
Saar Raz5d98ba62019-10-15 15:24:26 +0000157 for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
Saar Razfdf80e82019-12-06 01:30:21 +0200158 S.Diag(PDiag.first, PDiag.second);
Saar Raz5d98ba62019-10-15 15:24:26 +0000159 return true;
160 }
161
Saar Razfdf80e82019-12-06 01:30:21 +0200162 Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
163 if (!Satisfaction.IsSatisfied)
164 Satisfaction.Details.emplace_back(ConstraintExpr,
165 SubstitutedAtomicExpr.get());
Saar Raz5d98ba62019-10-15 15:24:26 +0000166
167 return false;
Saar Razfdf80e82019-12-06 01:30:21 +0200168}
169
Saar Razfdf80e82019-12-06 01:30:21 +0200170static bool calculateConstraintSatisfaction(
Saar Raz713562f2020-01-25 22:54:27 +0200171 Sema &S, const NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Saar Razfdf80e82019-12-06 01:30:21 +0200172 SourceLocation TemplateNameLoc, MultiLevelTemplateArgumentList &MLTAL,
173 const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction) {
174 return calculateConstraintSatisfaction(
175 S, ConstraintExpr, Satisfaction, [&](const Expr *AtomicExpr) {
176 EnterExpressionEvaluationContext ConstantEvaluated(
177 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
178
179 // Atomic constraint - substitute arguments and check satisfaction.
180 ExprResult SubstitutedExpression;
181 {
182 TemplateDeductionInfo Info(TemplateNameLoc);
183 Sema::InstantiatingTemplate Inst(S, AtomicExpr->getBeginLoc(),
Saar Raz713562f2020-01-25 22:54:27 +0200184 Sema::InstantiatingTemplate::ConstraintSubstitution{},
185 const_cast<NamedDecl *>(Template), Info,
186 AtomicExpr->getSourceRange());
Saar Razfdf80e82019-12-06 01:30:21 +0200187 if (Inst.isInvalid())
188 return ExprError();
189 // We do not want error diagnostics escaping here.
190 Sema::SFINAETrap Trap(S);
191 SubstitutedExpression = S.SubstExpr(const_cast<Expr *>(AtomicExpr),
192 MLTAL);
193 if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
194 // C++2a [temp.constr.atomic]p1
195 // ...If substitution results in an invalid type or expression, the
196 // constraint is not satisfied.
197 if (!Trap.hasErrorOccurred())
198 // A non-SFINAE error has occured as a result of this
199 // substitution.
200 return ExprError();
201
202 PartialDiagnosticAt SubstDiag{SourceLocation(),
203 PartialDiagnostic::NullDiagnostic()};
204 Info.takeSFINAEDiagnostic(SubstDiag);
205 // FIXME: Concepts: This is an unfortunate consequence of there
206 // being no serialization code for PartialDiagnostics and the fact
207 // that serializing them would likely take a lot more storage than
208 // just storing them as strings. We would still like, in the
209 // future, to serialize the proper PartialDiagnostic as serializing
210 // it as a string defeats the purpose of the diagnostic mechanism.
211 SmallString<128> DiagString;
212 DiagString = ": ";
213 SubstDiag.second.EmitToString(S.getDiagnostics(), DiagString);
214 unsigned MessageSize = DiagString.size();
215 char *Mem = new (S.Context) char[MessageSize];
216 memcpy(Mem, DiagString.c_str(), MessageSize);
217 Satisfaction.Details.emplace_back(
218 AtomicExpr,
219 new (S.Context) ConstraintSatisfaction::SubstitutionDiagnostic{
220 SubstDiag.first, StringRef(Mem, MessageSize)});
221 Satisfaction.IsSatisfied = false;
222 return ExprEmpty();
223 }
224 }
225
226 if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
227 return ExprError();
228
229 return SubstitutedExpression;
230 });
231}
232
Saar Raz713562f2020-01-25 22:54:27 +0200233static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template,
Saar Razfdf80e82019-12-06 01:30:21 +0200234 ArrayRef<const Expr *> ConstraintExprs,
235 ArrayRef<TemplateArgument> TemplateArgs,
236 SourceRange TemplateIDRange,
237 ConstraintSatisfaction &Satisfaction) {
238 if (ConstraintExprs.empty()) {
239 Satisfaction.IsSatisfied = true;
240 return false;
241 }
242
243 for (auto& Arg : TemplateArgs)
244 if (Arg.isInstantiationDependent()) {
245 // No need to check satisfaction for dependent constraint expressions.
246 Satisfaction.IsSatisfied = true;
247 return false;
248 }
249
250 Sema::InstantiatingTemplate Inst(S, TemplateIDRange.getBegin(),
Saar Raz713562f2020-01-25 22:54:27 +0200251 Sema::InstantiatingTemplate::ConstraintsCheck{},
252 const_cast<NamedDecl *>(Template), TemplateArgs, TemplateIDRange);
Saar Razfdf80e82019-12-06 01:30:21 +0200253 if (Inst.isInvalid())
254 return true;
255
256 MultiLevelTemplateArgumentList MLTAL;
257 MLTAL.addOuterTemplateArguments(TemplateArgs);
258
259 for (const Expr *ConstraintExpr : ConstraintExprs) {
260 if (calculateConstraintSatisfaction(S, Template, TemplateArgs,
261 TemplateIDRange.getBegin(), MLTAL,
262 ConstraintExpr, Satisfaction))
263 return true;
264 if (!Satisfaction.IsSatisfied)
265 // [temp.constr.op] p2
266 // [...] To determine if a conjunction is satisfied, the satisfaction
267 // of the first operand is checked. If that is not satisfied, the
268 // conjunction is not satisfied. [...]
269 return false;
270 }
271 return false;
272}
273
Saar Razb933d372020-01-22 02:50:12 +0200274bool Sema::CheckConstraintSatisfaction(
Saar Raz713562f2020-01-25 22:54:27 +0200275 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
Saar Razb933d372020-01-22 02:50:12 +0200276 ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange,
277 ConstraintSatisfaction &OutSatisfaction) {
278 if (ConstraintExprs.empty()) {
279 OutSatisfaction.IsSatisfied = true;
280 return false;
281 }
Saar Razfdf80e82019-12-06 01:30:21 +0200282
Saar Razb933d372020-01-22 02:50:12 +0200283 llvm::FoldingSetNodeID ID;
284 void *InsertPos;
285 ConstraintSatisfaction *Satisfaction = nullptr;
Saar Raz713562f2020-01-25 22:54:27 +0200286 bool ShouldCache = LangOpts.ConceptSatisfactionCaching && Template;
287 if (ShouldCache) {
Saar Razb933d372020-01-22 02:50:12 +0200288 ConstraintSatisfaction::Profile(ID, Context, Template, TemplateArgs);
289 Satisfaction = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos);
290 if (Satisfaction) {
291 OutSatisfaction = *Satisfaction;
292 return false;
293 }
294 Satisfaction = new ConstraintSatisfaction(Template, TemplateArgs);
295 } else {
296 Satisfaction = &OutSatisfaction;
297 }
Saar Raz713562f2020-01-25 22:54:27 +0200298 if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,
299 TemplateArgs, TemplateIDRange,
300 *Satisfaction)) {
301 if (ShouldCache)
Saar Razb933d372020-01-22 02:50:12 +0200302 delete Satisfaction;
303 return true;
304 }
Saar Razfdf80e82019-12-06 01:30:21 +0200305
Saar Raz713562f2020-01-25 22:54:27 +0200306 if (ShouldCache) {
Saar Razb933d372020-01-22 02:50:12 +0200307 // We cannot use InsertNode here because CheckConstraintSatisfaction might
308 // have invalidated it.
309 SatisfactionCache.InsertNode(Satisfaction);
310 OutSatisfaction = *Satisfaction;
311 }
312 return false;
Saar Razfdf80e82019-12-06 01:30:21 +0200313}
314
315bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr,
316 ConstraintSatisfaction &Satisfaction) {
317 return calculateConstraintSatisfaction(
318 *this, ConstraintExpr, Satisfaction,
319 [](const Expr *AtomicExpr) -> ExprResult {
320 return ExprResult(const_cast<Expr *>(AtomicExpr));
321 });
322}
323
Saar Raz713562f2020-01-25 22:54:27 +0200324bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
325 ConstraintSatisfaction &Satisfaction,
326 SourceLocation UsageLoc) {
327 const Expr *RC = FD->getTrailingRequiresClause();
328 assert(!RC->isInstantiationDependent() &&
329 "CheckFunctionConstraints can only be used with functions with "
330 "non-dependent constraints");
331 // We substitute with empty arguments in order to rebuild the atomic
332 // constraint in a constant-evaluated context.
333 // FIXME: Should this be a dedicated TreeTransform?
334 return CheckConstraintSatisfaction(
335 FD, {RC}, /*TemplateArgs=*/{},
336 SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
337 Satisfaction);
338}
339
Saar Razfdf80e82019-12-06 01:30:21 +0200340bool Sema::EnsureTemplateArgumentListConstraints(
341 TemplateDecl *TD, ArrayRef<TemplateArgument> TemplateArgs,
342 SourceRange TemplateIDRange) {
343 ConstraintSatisfaction Satisfaction;
344 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
345 TD->getAssociatedConstraints(AssociatedConstraints);
346 if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgs,
347 TemplateIDRange, Satisfaction))
348 return true;
349
350 if (!Satisfaction.IsSatisfied) {
351 SmallString<128> TemplateArgString;
352 TemplateArgString = " ";
353 TemplateArgString += getTemplateArgumentBindingsText(
354 TD->getTemplateParameters(), TemplateArgs.data(), TemplateArgs.size());
355
356 Diag(TemplateIDRange.getBegin(),
357 diag::err_template_arg_list_constraints_not_satisfied)
358 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << TD
359 << TemplateArgString << TemplateIDRange;
360 DiagnoseUnsatisfiedConstraint(Satisfaction);
361 return true;
362 }
363 return false;
364}
365
Saar Raza0f50d72020-01-18 09:11:43 +0200366static void diagnoseUnsatisfiedRequirement(Sema &S,
367 concepts::ExprRequirement *Req,
368 bool First) {
369 assert(!Req->isSatisfied()
370 && "Diagnose() can only be used on an unsatisfied requirement");
371 switch (Req->getSatisfactionStatus()) {
372 case concepts::ExprRequirement::SS_Dependent:
373 llvm_unreachable("Diagnosing a dependent requirement");
374 break;
375 case concepts::ExprRequirement::SS_ExprSubstitutionFailure: {
376 auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
377 if (!SubstDiag->DiagMessage.empty())
378 S.Diag(SubstDiag->DiagLoc,
379 diag::note_expr_requirement_expr_substitution_error)
380 << (int)First << SubstDiag->SubstitutedEntity
381 << SubstDiag->DiagMessage;
382 else
383 S.Diag(SubstDiag->DiagLoc,
384 diag::note_expr_requirement_expr_unknown_substitution_error)
385 << (int)First << SubstDiag->SubstitutedEntity;
386 break;
387 }
388 case concepts::ExprRequirement::SS_NoexceptNotMet:
389 S.Diag(Req->getNoexceptLoc(),
390 diag::note_expr_requirement_noexcept_not_met)
391 << (int)First << Req->getExpr();
392 break;
393 case concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure: {
394 auto *SubstDiag =
395 Req->getReturnTypeRequirement().getSubstitutionDiagnostic();
396 if (!SubstDiag->DiagMessage.empty())
397 S.Diag(SubstDiag->DiagLoc,
398 diag::note_expr_requirement_type_requirement_substitution_error)
399 << (int)First << SubstDiag->SubstitutedEntity
400 << SubstDiag->DiagMessage;
401 else
402 S.Diag(SubstDiag->DiagLoc,
403 diag::note_expr_requirement_type_requirement_unknown_substitution_error)
404 << (int)First << SubstDiag->SubstitutedEntity;
405 break;
406 }
407 case concepts::ExprRequirement::SS_ConstraintsNotSatisfied: {
408 ConceptSpecializationExpr *ConstraintExpr =
409 Req->getReturnTypeRequirementSubstitutedConstraintExpr();
410 if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1)
411 // A simple case - expr type is the type being constrained and the concept
412 // was not provided arguments.
413 S.Diag(ConstraintExpr->getBeginLoc(),
414 diag::note_expr_requirement_constraints_not_satisfied_simple)
415 << (int)First << S.BuildDecltypeType(Req->getExpr(),
416 Req->getExpr()->getBeginLoc())
417 << ConstraintExpr->getNamedConcept();
418 else
419 S.Diag(ConstraintExpr->getBeginLoc(),
420 diag::note_expr_requirement_constraints_not_satisfied)
421 << (int)First << ConstraintExpr;
422 S.DiagnoseUnsatisfiedConstraint(ConstraintExpr->getSatisfaction());
423 break;
424 }
425 case concepts::ExprRequirement::SS_Satisfied:
426 llvm_unreachable("We checked this above");
427 }
428}
429
430static void diagnoseUnsatisfiedRequirement(Sema &S,
431 concepts::TypeRequirement *Req,
432 bool First) {
433 assert(!Req->isSatisfied()
434 && "Diagnose() can only be used on an unsatisfied requirement");
435 switch (Req->getSatisfactionStatus()) {
436 case concepts::TypeRequirement::SS_Dependent:
437 llvm_unreachable("Diagnosing a dependent requirement");
438 return;
439 case concepts::TypeRequirement::SS_SubstitutionFailure: {
440 auto *SubstDiag = Req->getSubstitutionDiagnostic();
441 if (!SubstDiag->DiagMessage.empty())
442 S.Diag(SubstDiag->DiagLoc,
443 diag::note_type_requirement_substitution_error) << (int)First
444 << SubstDiag->SubstitutedEntity << SubstDiag->DiagMessage;
445 else
446 S.Diag(SubstDiag->DiagLoc,
447 diag::note_type_requirement_unknown_substitution_error)
448 << (int)First << SubstDiag->SubstitutedEntity;
449 return;
450 }
451 default:
452 llvm_unreachable("Unknown satisfaction status");
453 return;
454 }
455}
456
457static void diagnoseUnsatisfiedRequirement(Sema &S,
458 concepts::NestedRequirement *Req,
459 bool First) {
460 if (Req->isSubstitutionFailure()) {
461 concepts::Requirement::SubstitutionDiagnostic *SubstDiag =
462 Req->getSubstitutionDiagnostic();
463 if (!SubstDiag->DiagMessage.empty())
464 S.Diag(SubstDiag->DiagLoc,
465 diag::note_nested_requirement_substitution_error)
466 << (int)First << SubstDiag->SubstitutedEntity
467 << SubstDiag->DiagMessage;
468 else
469 S.Diag(SubstDiag->DiagLoc,
470 diag::note_nested_requirement_unknown_substitution_error)
471 << (int)First << SubstDiag->SubstitutedEntity;
472 return;
473 }
474 S.DiagnoseUnsatisfiedConstraint(Req->getConstraintSatisfaction(), First);
475}
476
477
Saar Razfdf80e82019-12-06 01:30:21 +0200478static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
479 Expr *SubstExpr,
480 bool First = true) {
481 SubstExpr = SubstExpr->IgnoreParenImpCasts();
482 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
483 switch (BO->getOpcode()) {
484 // These two cases will in practice only be reached when using fold
485 // expressions with || and &&, since otherwise the || and && will have been
486 // broken down into atomic constraints during satisfaction checking.
487 case BO_LOr:
488 // Or evaluated to false - meaning both RHS and LHS evaluated to false.
489 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
490 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
491 /*First=*/false);
492 return;
493 case BO_LAnd:
494 bool LHSSatisfied;
495 BO->getLHS()->EvaluateAsBooleanCondition(LHSSatisfied, S.Context);
496 if (LHSSatisfied) {
497 // LHS is true, so RHS must be false.
498 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(), First);
499 return;
500 }
501 // LHS is false
502 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
503
504 // RHS might also be false
505 bool RHSSatisfied;
506 BO->getRHS()->EvaluateAsBooleanCondition(RHSSatisfied, S.Context);
507 if (!RHSSatisfied)
508 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
509 /*First=*/false);
510 return;
511 case BO_GE:
512 case BO_LE:
513 case BO_GT:
514 case BO_LT:
515 case BO_EQ:
516 case BO_NE:
517 if (BO->getLHS()->getType()->isIntegerType() &&
518 BO->getRHS()->getType()->isIntegerType()) {
519 Expr::EvalResult SimplifiedLHS;
520 Expr::EvalResult SimplifiedRHS;
521 BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context);
522 BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context);
523 if (!SimplifiedLHS.Diag && ! SimplifiedRHS.Diag) {
524 S.Diag(SubstExpr->getBeginLoc(),
525 diag::note_atomic_constraint_evaluated_to_false_elaborated)
526 << (int)First << SubstExpr
527 << SimplifiedLHS.Val.getInt().toString(10)
528 << BinaryOperator::getOpcodeStr(BO->getOpcode())
529 << SimplifiedRHS.Val.getInt().toString(10);
530 return;
531 }
532 }
533 break;
534
535 default:
536 break;
537 }
538 } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
539 if (CSE->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
540 S.Diag(
541 CSE->getSourceRange().getBegin(),
542 diag::
543 note_single_arg_concept_specialization_constraint_evaluated_to_false)
544 << (int)First
545 << CSE->getTemplateArgsAsWritten()->arguments()[0].getArgument()
546 << CSE->getNamedConcept();
547 } else {
548 S.Diag(SubstExpr->getSourceRange().getBegin(),
549 diag::note_concept_specialization_constraint_evaluated_to_false)
550 << (int)First << CSE;
551 }
552 S.DiagnoseUnsatisfiedConstraint(CSE->getSatisfaction());
553 return;
Saar Raza0f50d72020-01-18 09:11:43 +0200554 } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
555 for (concepts::Requirement *Req : RE->getRequirements())
556 if (!Req->isDependent() && !Req->isSatisfied()) {
557 if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
558 diagnoseUnsatisfiedRequirement(S, E, First);
559 else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
560 diagnoseUnsatisfiedRequirement(S, T, First);
561 else
562 diagnoseUnsatisfiedRequirement(
563 S, cast<concepts::NestedRequirement>(Req), First);
564 break;
565 }
566 return;
Saar Razfdf80e82019-12-06 01:30:21 +0200567 }
568
569 S.Diag(SubstExpr->getSourceRange().getBegin(),
570 diag::note_atomic_constraint_evaluated_to_false)
571 << (int)First << SubstExpr;
572}
573
574template<typename SubstitutionDiagnostic>
575static void diagnoseUnsatisfiedConstraintExpr(
576 Sema &S, const Expr *E,
577 const llvm::PointerUnion<Expr *, SubstitutionDiagnostic *> &Record,
578 bool First = true) {
579 if (auto *Diag = Record.template dyn_cast<SubstitutionDiagnostic *>()){
580 S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
581 << Diag->second;
582 return;
583 }
584
585 diagnoseWellFormedUnsatisfiedConstraintExpr(S,
586 Record.template get<Expr *>(), First);
587}
588
Saar Raza0f50d72020-01-18 09:11:43 +0200589void
590Sema::DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction,
591 bool First) {
Saar Razfdf80e82019-12-06 01:30:21 +0200592 assert(!Satisfaction.IsSatisfied &&
593 "Attempted to diagnose a satisfied constraint");
Saar Razfdf80e82019-12-06 01:30:21 +0200594 for (auto &Pair : Satisfaction.Details) {
595 diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
596 First = false;
597 }
598}
599
600void Sema::DiagnoseUnsatisfiedConstraint(
Saar Raza0f50d72020-01-18 09:11:43 +0200601 const ASTConstraintSatisfaction &Satisfaction,
602 bool First) {
Saar Razfdf80e82019-12-06 01:30:21 +0200603 assert(!Satisfaction.IsSatisfied &&
604 "Attempted to diagnose a satisfied constraint");
Saar Razfdf80e82019-12-06 01:30:21 +0200605 for (auto &Pair : Satisfaction) {
606 diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
607 First = false;
608 }
Saar Razdf061c32019-12-23 08:37:35 +0200609}
610
Saar Razb65b1f32020-01-09 15:07:51 +0200611const NormalizedConstraint *
612Sema::getNormalizedAssociatedConstraints(
613 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints) {
614 auto CacheEntry = NormalizationCache.find(ConstrainedDecl);
615 if (CacheEntry == NormalizationCache.end()) {
616 auto Normalized =
617 NormalizedConstraint::fromConstraintExprs(*this, ConstrainedDecl,
618 AssociatedConstraints);
619 CacheEntry =
620 NormalizationCache
621 .try_emplace(ConstrainedDecl,
622 Normalized
623 ? new (Context) NormalizedConstraint(
624 std::move(*Normalized))
625 : nullptr)
626 .first;
Saar Razdf061c32019-12-23 08:37:35 +0200627 }
Saar Razb65b1f32020-01-09 15:07:51 +0200628 return CacheEntry->second;
629}
Saar Razdf061c32019-12-23 08:37:35 +0200630
631static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
632 ConceptDecl *Concept, ArrayRef<TemplateArgument> TemplateArgs,
633 const ASTTemplateArgumentListInfo *ArgsAsWritten) {
634 if (!N.isAtomic()) {
635 if (substituteParameterMappings(S, N.getLHS(), Concept, TemplateArgs,
636 ArgsAsWritten))
637 return true;
638 return substituteParameterMappings(S, N.getRHS(), Concept, TemplateArgs,
639 ArgsAsWritten);
640 }
641 TemplateParameterList *TemplateParams = Concept->getTemplateParameters();
642
643 AtomicConstraint &Atomic = *N.getAtomicConstraint();
644 TemplateArgumentListInfo SubstArgs;
645 MultiLevelTemplateArgumentList MLTAL;
646 MLTAL.addOuterTemplateArguments(TemplateArgs);
647 if (!Atomic.ParameterMapping) {
648 llvm::SmallBitVector OccurringIndices(TemplateParams->size());
649 S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
650 /*Depth=*/0, OccurringIndices);
Saar Razb65b1f32020-01-09 15:07:51 +0200651 Atomic.ParameterMapping.emplace(
652 MutableArrayRef<TemplateArgumentLoc>(
653 new (S.Context) TemplateArgumentLoc[OccurringIndices.count()],
654 OccurringIndices.count()));
655 for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
Saar Razdf061c32019-12-23 08:37:35 +0200656 if (OccurringIndices[I])
Saar Razb65b1f32020-01-09 15:07:51 +0200657 new (&(*Atomic.ParameterMapping)[J++]) TemplateArgumentLoc(
Saar Razdf061c32019-12-23 08:37:35 +0200658 S.getIdentityTemplateArgumentLoc(TemplateParams->begin()[I],
659 // Here we assume we do not support things like
660 // template<typename A, typename B>
661 // concept C = ...;
662 //
663 // template<typename... Ts> requires C<Ts...>
664 // struct S { };
665 // The above currently yields a diagnostic.
666 // We still might have default arguments for concept parameters.
667 ArgsAsWritten->NumTemplateArgs > I ?
668 ArgsAsWritten->arguments()[I].getLocation() :
669 SourceLocation()));
670 }
671 Sema::InstantiatingTemplate Inst(
672 S, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
673 Sema::InstantiatingTemplate::ParameterMappingSubstitution{}, Concept,
674 SourceRange(ArgsAsWritten->arguments()[0].getSourceRange().getBegin(),
675 ArgsAsWritten->arguments().back().getSourceRange().getEnd()));
676 if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs))
677 return true;
678 std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
679 N.getAtomicConstraint()->ParameterMapping->begin());
680 return false;
681}
682
Saar Razb65b1f32020-01-09 15:07:51 +0200683Optional<NormalizedConstraint>
684NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
685 ArrayRef<const Expr *> E) {
686 assert(E.size() != 0);
687 auto First = fromConstraintExpr(S, D, E[0]);
688 if (E.size() == 1)
689 return First;
690 auto Second = fromConstraintExpr(S, D, E[1]);
691 if (!Second)
692 return None;
693 llvm::Optional<NormalizedConstraint> Conjunction;
694 Conjunction.emplace(S.Context, std::move(*First), std::move(*Second),
695 CCK_Conjunction);
696 for (unsigned I = 2; I < E.size(); ++I) {
697 auto Next = fromConstraintExpr(S, D, E[I]);
698 if (!Next)
699 return llvm::Optional<NormalizedConstraint>{};
700 NormalizedConstraint NewConjunction(S.Context, std::move(*Conjunction),
701 std::move(*Next), CCK_Conjunction);
702 *Conjunction = std::move(NewConjunction);
703 }
704 return Conjunction;
705}
706
Saar Razdf061c32019-12-23 08:37:35 +0200707llvm::Optional<NormalizedConstraint>
708NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) {
709 assert(E != nullptr);
710
711 // C++ [temp.constr.normal]p1.1
712 // [...]
713 // - The normal form of an expression (E) is the normal form of E.
714 // [...]
715 E = E->IgnoreParenImpCasts();
716 if (auto *BO = dyn_cast<const BinaryOperator>(E)) {
717 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
718 auto LHS = fromConstraintExpr(S, D, BO->getLHS());
719 if (!LHS)
720 return None;
721 auto RHS = fromConstraintExpr(S, D, BO->getRHS());
722 if (!RHS)
723 return None;
724
725 return NormalizedConstraint(
Saar Razb65b1f32020-01-09 15:07:51 +0200726 S.Context, std::move(*LHS), std::move(*RHS),
Saar Razdf061c32019-12-23 08:37:35 +0200727 BO->getOpcode() == BO_LAnd ? CCK_Conjunction : CCK_Disjunction);
728 }
729 } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
Saar Razb65b1f32020-01-09 15:07:51 +0200730 const NormalizedConstraint *SubNF;
Saar Razdf061c32019-12-23 08:37:35 +0200731 {
732 Sema::InstantiatingTemplate Inst(
733 S, CSE->getExprLoc(),
734 Sema::InstantiatingTemplate::ConstraintNormalization{}, D,
735 CSE->getSourceRange());
736 // C++ [temp.constr.normal]p1.1
737 // [...]
738 // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
739 // where C names a concept, is the normal form of the
740 // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
741 // respective template parameters in the parameter mappings in each atomic
742 // constraint. If any such substitution results in an invalid type or
743 // expression, the program is ill-formed; no diagnostic is required.
744 // [...]
Saar Razb65b1f32020-01-09 15:07:51 +0200745 ConceptDecl *CD = CSE->getNamedConcept();
746 SubNF = S.getNormalizedAssociatedConstraints(CD,
747 {CD->getConstraintExpr()});
Saar Razdf061c32019-12-23 08:37:35 +0200748 if (!SubNF)
749 return None;
750 }
751
Saar Razb65b1f32020-01-09 15:07:51 +0200752 Optional<NormalizedConstraint> New;
753 New.emplace(S.Context, *SubNF);
754
Saar Razdf061c32019-12-23 08:37:35 +0200755 if (substituteParameterMappings(
Saar Razb65b1f32020-01-09 15:07:51 +0200756 S, *New, CSE->getNamedConcept(),
Saar Razdf061c32019-12-23 08:37:35 +0200757 CSE->getTemplateArguments(), CSE->getTemplateArgsAsWritten()))
758 return None;
759
Saar Razb65b1f32020-01-09 15:07:51 +0200760 return New;
Saar Razdf061c32019-12-23 08:37:35 +0200761 }
762 return NormalizedConstraint{new (S.Context) AtomicConstraint(S, E)};
763}
764
Saar Razdf061c32019-12-23 08:37:35 +0200765using NormalForm =
766 llvm::SmallVector<llvm::SmallVector<AtomicConstraint *, 2>, 4>;
767
768static NormalForm makeCNF(const NormalizedConstraint &Normalized) {
769 if (Normalized.isAtomic())
770 return {{Normalized.getAtomicConstraint()}};
771
772 NormalForm LCNF = makeCNF(Normalized.getLHS());
773 NormalForm RCNF = makeCNF(Normalized.getRHS());
774 if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Conjunction) {
775 LCNF.reserve(LCNF.size() + RCNF.size());
776 while (!RCNF.empty())
777 LCNF.push_back(RCNF.pop_back_val());
778 return LCNF;
779 }
780
781 // Disjunction
782 NormalForm Res;
783 Res.reserve(LCNF.size() * RCNF.size());
784 for (auto &LDisjunction : LCNF)
785 for (auto &RDisjunction : RCNF) {
786 NormalForm::value_type Combined;
787 Combined.reserve(LDisjunction.size() + RDisjunction.size());
788 std::copy(LDisjunction.begin(), LDisjunction.end(),
789 std::back_inserter(Combined));
790 std::copy(RDisjunction.begin(), RDisjunction.end(),
791 std::back_inserter(Combined));
792 Res.emplace_back(Combined);
793 }
794 return Res;
795}
796
797static NormalForm makeDNF(const NormalizedConstraint &Normalized) {
798 if (Normalized.isAtomic())
799 return {{Normalized.getAtomicConstraint()}};
800
801 NormalForm LDNF = makeDNF(Normalized.getLHS());
802 NormalForm RDNF = makeDNF(Normalized.getRHS());
803 if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Disjunction) {
804 LDNF.reserve(LDNF.size() + RDNF.size());
805 while (!RDNF.empty())
806 LDNF.push_back(RDNF.pop_back_val());
807 return LDNF;
808 }
809
810 // Conjunction
811 NormalForm Res;
812 Res.reserve(LDNF.size() * RDNF.size());
813 for (auto &LConjunction : LDNF) {
814 for (auto &RConjunction : RDNF) {
815 NormalForm::value_type Combined;
816 Combined.reserve(LConjunction.size() + RConjunction.size());
817 std::copy(LConjunction.begin(), LConjunction.end(),
818 std::back_inserter(Combined));
819 std::copy(RConjunction.begin(), RConjunction.end(),
820 std::back_inserter(Combined));
821 Res.emplace_back(Combined);
822 }
823 }
824 return Res;
825}
826
Saar Razb65b1f32020-01-09 15:07:51 +0200827template<typename AtomicSubsumptionEvaluator>
828static bool subsumes(NormalForm PDNF, NormalForm QCNF,
829 AtomicSubsumptionEvaluator E) {
Saar Razdf061c32019-12-23 08:37:35 +0200830 // C++ [temp.constr.order] p2
831 // Then, P subsumes Q if and only if, for every disjunctive clause Pi in the
832 // disjunctive normal form of P, Pi subsumes every conjunctive clause Qj in
833 // the conjuctive normal form of Q, where [...]
834 for (const auto &Pi : PDNF) {
835 for (const auto &Qj : QCNF) {
836 // C++ [temp.constr.order] p2
837 // - [...] a disjunctive clause Pi subsumes a conjunctive clause Qj if
838 // and only if there exists an atomic constraint Pia in Pi for which
839 // there exists an atomic constraint, Qjb, in Qj such that Pia
840 // subsumes Qjb.
841 bool Found = false;
842 for (const AtomicConstraint *Pia : Pi) {
843 for (const AtomicConstraint *Qjb : Qj) {
Saar Razb65b1f32020-01-09 15:07:51 +0200844 if (E(*Pia, *Qjb)) {
Saar Razdf061c32019-12-23 08:37:35 +0200845 Found = true;
846 break;
847 }
848 }
849 if (Found)
850 break;
851 }
Saar Razb65b1f32020-01-09 15:07:51 +0200852 if (!Found)
Saar Razdf061c32019-12-23 08:37:35 +0200853 return false;
Saar Razdf061c32019-12-23 08:37:35 +0200854 }
855 }
Saar Razb65b1f32020-01-09 15:07:51 +0200856 return true;
857}
858
859template<typename AtomicSubsumptionEvaluator>
860static bool subsumes(Sema &S, NamedDecl *DP, ArrayRef<const Expr *> P,
861 NamedDecl *DQ, ArrayRef<const Expr *> Q, bool &Subsumes,
862 AtomicSubsumptionEvaluator E) {
863 // C++ [temp.constr.order] p2
864 // In order to determine if a constraint P subsumes a constraint Q, P is
865 // transformed into disjunctive normal form, and Q is transformed into
866 // conjunctive normal form. [...]
867 auto *PNormalized = S.getNormalizedAssociatedConstraints(DP, P);
868 if (!PNormalized)
869 return true;
870 const NormalForm PDNF = makeDNF(*PNormalized);
871
872 auto *QNormalized = S.getNormalizedAssociatedConstraints(DQ, Q);
873 if (!QNormalized)
874 return true;
875 const NormalForm QCNF = makeCNF(*QNormalized);
876
877 Subsumes = subsumes(PDNF, QCNF, E);
Saar Razdf061c32019-12-23 08:37:35 +0200878 return false;
879}
880
881bool Sema::IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
882 NamedDecl *D2, ArrayRef<const Expr *> AC2,
883 bool &Result) {
884 if (AC1.empty()) {
885 Result = AC2.empty();
886 return false;
887 }
888 if (AC2.empty()) {
889 // TD1 has associated constraints and TD2 does not.
890 Result = true;
891 return false;
892 }
893
894 std::pair<NamedDecl *, NamedDecl *> Key{D1, D2};
895 auto CacheEntry = SubsumptionCache.find(Key);
896 if (CacheEntry != SubsumptionCache.end()) {
897 Result = CacheEntry->second;
898 return false;
899 }
Saar Razb65b1f32020-01-09 15:07:51 +0200900
901 if (subsumes(*this, D1, AC1, D2, AC2, Result,
902 [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
903 return A.subsumes(Context, B);
904 }))
Saar Razdf061c32019-12-23 08:37:35 +0200905 return true;
906 SubsumptionCache.try_emplace(Key, Result);
907 return false;
Saar Razb65b1f32020-01-09 15:07:51 +0200908}
909
910bool Sema::MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
911 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2) {
912 if (isSFINAEContext())
913 // No need to work here because our notes would be discarded.
914 return false;
915
916 if (AC1.empty() || AC2.empty())
917 return false;
918
919 auto NormalExprEvaluator =
920 [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
921 return A.subsumes(Context, B);
922 };
923
924 const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
925 auto IdenticalExprEvaluator =
926 [&] (const AtomicConstraint &A, const AtomicConstraint &B) {
927 if (!A.hasMatchingParameterMapping(Context, B))
928 return false;
929 const Expr *EA = A.ConstraintExpr, *EB = B.ConstraintExpr;
930 if (EA == EB)
931 return true;
932
933 // Not the same source level expression - are the expressions
934 // identical?
935 llvm::FoldingSetNodeID IDA, IDB;
936 EA->Profile(IDA, Context, /*Cannonical=*/true);
937 EB->Profile(IDB, Context, /*Cannonical=*/true);
938 if (IDA != IDB)
939 return false;
940
941 AmbiguousAtomic1 = EA;
942 AmbiguousAtomic2 = EB;
943 return true;
944 };
945
946 {
947 // The subsumption checks might cause diagnostics
948 SFINAETrap Trap(*this);
949 auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
950 if (!Normalized1)
951 return false;
952 const NormalForm DNF1 = makeDNF(*Normalized1);
953 const NormalForm CNF1 = makeCNF(*Normalized1);
954
955 auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
956 if (!Normalized2)
957 return false;
958 const NormalForm DNF2 = makeDNF(*Normalized2);
959 const NormalForm CNF2 = makeCNF(*Normalized2);
960
961 bool Is1AtLeastAs2Normally = subsumes(DNF1, CNF2, NormalExprEvaluator);
962 bool Is2AtLeastAs1Normally = subsumes(DNF2, CNF1, NormalExprEvaluator);
963 bool Is1AtLeastAs2 = subsumes(DNF1, CNF2, IdenticalExprEvaluator);
964 bool Is2AtLeastAs1 = subsumes(DNF2, CNF1, IdenticalExprEvaluator);
965 if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
966 Is2AtLeastAs1 == Is2AtLeastAs1Normally)
967 // Same result - no ambiguity was caused by identical atomic expressions.
968 return false;
969 }
970
971 // A different result! Some ambiguous atomic constraint(s) caused a difference
972 assert(AmbiguousAtomic1 && AmbiguousAtomic2);
973
974 Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
975 << AmbiguousAtomic1->getSourceRange();
976 Diag(AmbiguousAtomic2->getBeginLoc(),
977 diag::note_ambiguous_atomic_constraints_similar_expression)
978 << AmbiguousAtomic2->getSourceRange();
979 return true;
980}
Saar Raza0f50d72020-01-18 09:11:43 +0200981
982concepts::ExprRequirement::ExprRequirement(
983 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
984 ReturnTypeRequirement Req, SatisfactionStatus Status,
985 ConceptSpecializationExpr *SubstitutedConstraintExpr) :
986 Requirement(IsSimple ? RK_Simple : RK_Compound, Status == SS_Dependent,
987 Status == SS_Dependent &&
988 (E->containsUnexpandedParameterPack() ||
989 Req.containsUnexpandedParameterPack()),
990 Status == SS_Satisfied), Value(E), NoexceptLoc(NoexceptLoc),
991 TypeReq(Req), SubstitutedConstraintExpr(SubstitutedConstraintExpr),
992 Status(Status) {
993 assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
994 "Simple requirement must not have a return type requirement or a "
995 "noexcept specification");
996 assert((Status > SS_TypeRequirementSubstitutionFailure && Req.isTypeConstraint()) ==
997 (SubstitutedConstraintExpr != nullptr));
998}
999
1000concepts::ExprRequirement::ExprRequirement(
1001 SubstitutionDiagnostic *ExprSubstDiag, bool IsSimple,
1002 SourceLocation NoexceptLoc, ReturnTypeRequirement Req) :
1003 Requirement(IsSimple ? RK_Simple : RK_Compound, Req.isDependent(),
1004 Req.containsUnexpandedParameterPack(), /*IsSatisfied=*/false),
1005 Value(ExprSubstDiag), NoexceptLoc(NoexceptLoc), TypeReq(Req),
1006 Status(SS_ExprSubstitutionFailure) {
1007 assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1008 "Simple requirement must not have a return type requirement or a "
1009 "noexcept specification");
1010}
1011
1012concepts::ExprRequirement::ReturnTypeRequirement::
1013ReturnTypeRequirement(TemplateParameterList *TPL) :
1014 TypeConstraintInfo(TPL, 0) {
1015 assert(TPL->size() == 1);
1016 const TypeConstraint *TC =
1017 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint();
1018 assert(TC &&
1019 "TPL must have a template type parameter with a type constraint");
1020 auto *Constraint =
1021 cast_or_null<ConceptSpecializationExpr>(
1022 TC->getImmediatelyDeclaredConstraint());
1023 bool Dependent = false;
1024 if (Constraint->getTemplateArgsAsWritten()) {
1025 for (auto &ArgLoc :
1026 Constraint->getTemplateArgsAsWritten()->arguments().drop_front(1)) {
1027 if (ArgLoc.getArgument().isDependent()) {
1028 Dependent = true;
1029 break;
1030 }
1031 }
1032 }
1033 TypeConstraintInfo.setInt(Dependent ? 1 : 0);
1034}
1035
1036concepts::TypeRequirement::TypeRequirement(TypeSourceInfo *T) :
1037 Requirement(RK_Type, T->getType()->isDependentType(),
1038 T->getType()->containsUnexpandedParameterPack(),
1039 // We reach this ctor with either dependent types (in which
1040 // IsSatisfied doesn't matter) or with non-dependent type in
1041 // which the existence of the type indicates satisfaction.
1042 /*IsSatisfied=*/true
1043 ), Value(T),
1044 Status(T->getType()->isDependentType() ? SS_Dependent : SS_Satisfied) {}