[clang] [clang][Sema] Diagnose unsatisfied constraints on rejected partial specializations (PR #239106)

via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 4 22:10:45 PST 2026


https://github.com/tribhu05 created https://github.com/llvm/llvm-project/pull/239106

### Summary
Fixes #238212.

When a constrained C++20 class or variable template partial specialization fails constraint satisfaction, Clang previously silently discarded the candidate and fell back to the primary template (or selected another candidate). When an error subsequently occurred—such as a `static_assert` failure on a member trait, an error about instantiating an undefined primary template, or a missing member—Clang provided no notes explaining why the partial specialization was rejected.

This PR adds diagnostic notes for rejected constrained partial specializations, aligning class and variable template diagnostics with the behavior developers expect from function templates.

### Root Cause
During partial specialization matching in `Sema::FinishTemplateArgumentDeduction`, failed candidates were recorded in `FailedCandidates` with deduction failure info (`TemplateDeductionResult::ConstraintsNotSatisfied`), but discarded when no specialization matched and execution fell back to the primary template. If an error occurred later, no diagnostic machinery inspected the rejected partial specializations.

### Implementation Details
1. **`NoteUnsatisfiedPartialSpecializations`**: Inspects candidate partial specializations for a given template and argument list in source order:
   - Evaluates deduction and constraint satisfaction using existing `DeduceTemplateArguments`.
   - Diagnoses unsatisfied constraints with `diag::note_ovl_candidate_unsatisfied_constraints` and expands requirements via `Sema::DiagnoseUnsatisfiedConstraint`.
   - Distinguishes unsatisfied constraints from partial ordering: when another specialization is selected, candidates with satisfied constraints that were rejected due to being less constrained are diagnosed with `note_partial_spec_not_selected_less_constrained`.
2. **Diagnostic Points**: Hooked into `DiagnoseStaticAssertDetails`, `DiagnoseUninstantiableTemplate`, `BuildMemberReferenceExpr`, `BuildQualifiedDeclarationNameExpr`, `BuildQualifiedTemplateIdExpr`, `ActOnTemplateName`, and `CheckTypenameType`.
3. **`SemaOverload.cpp` Support**: Added `getTemplateParameters` to safely extract template parameters from partial specializations during bad-deduction formatting without asserting on non-`TemplateDecl`s.

### Tests
- Added `clang/test/SemaTemplate/concepts-class-template-partial-spec-notes.cpp` covering atomic constraints, concept requirements, undefined primary templates, missing members, multiple candidates, variable templates, and partial ordering.
- Updated expected notes in existing tests `partial-specializations.cpp`, `concepts-recovery-expr.cpp`, and `concepts.cpp`.
- Verified 100% pass rate across all modified tests and the entire `clang/test/CXX/temp/temp.constr/` suite.

### AI Assistance Disclosure
In accordance with the LLVM AI Tool Policy, this patch was authored and debugged with assistance from an agentic AI coding assistant (Antigravity). All source modifications, diagnostic mechanics, and tests have been compiled, run, and reviewed.


>From 0665d5ea8bbb6181b39060f410c41a88572c690a Mon Sep 17 00:00:00 2001
From: Tribhuwan <tribhuwansingh5050 at gmail.com>
Date: Wed, 4 Nov 2026 10:31:17 +0530
Subject: [PATCH] [clang][Sema] Diagnose unsatisfied constraints on rejected
 partial specializations

When a class or variable template partial specialization is rejected during
template argument deduction due to unsatisfied constraints, Clang previously
discarded the deduction failure information and fell back to the primary
template without explaining why the partial specialization candidate was not
selected. If an error occurred subsequently (e.g. static assertion failure,
instantiation of an undefined primary template, or missing member lookup), Clang
emitted no diagnostic notes for the rejected candidate, unlike function templates
which note unsatisfied constraints with note_ovl_candidate_unsatisfied_constraints.

This patch implements NoteUnsatisfiedPartialSpecializations to inspect candidate
partial specializations when fallback or subsequent diagnostic errors occur:
- Emits note_ovl_candidate_unsatisfied_constraints and details the unsatisfied
  atomic constraints and concept requirements via DiagnoseUnsatisfiedConstraint.
- When another partial specialization is selected, diagnoses candidates rejected
  due to partial ordering with note_partial_spec_not_selected_less_constrained.
- Handles both ClassTemplatePartialSpecializationDecl and VarTemplatePartialSpecializationDecl.
- Updates Diagnosing bad deduction in SemaOverload to retrieve parameter lists for
  partial specializations without asserting.

Fixes #238212.
---
 .../clang/Basic/DiagnosticSemaKinds.td        |   2 +
 clang/include/clang/Sema/Sema.h               |  18 ++
 clang/lib/Sema/SemaCXXScopeSpec.cpp           |   7 +-
 clang/lib/Sema/SemaDeclCXX.cpp                |  52 ++++++
 clang/lib/Sema/SemaExpr.cpp                   |   3 +
 clang/lib/Sema/SemaExprMember.cpp             |   6 +-
 clang/lib/Sema/SemaOverload.cpp               |  16 +-
 clang/lib/Sema/SemaTemplate.cpp               | 169 +++++++++++++++++-
 .../partial-specializations.cpp               |   4 +-
 ...epts-class-template-partial-spec-notes.cpp | 123 +++++++++++++
 .../SemaTemplate/concepts-recovery-expr.cpp   |   6 +-
 clang/test/SemaTemplate/concepts.cpp          |   4 +-
 12 files changed, 393 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/SemaTemplate/concepts-class-template-partial-spec-notes.cpp

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 671bdd63af6861..b3ef6a34cbf22d 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5982,6 +5982,8 @@ def note_non_deducible_parameter : Note<
 def err_partial_spec_ordering_ambiguous : Error<
     "ambiguous partial specializations of %0">;
 def note_partial_spec_match : Note<"partial specialization matches %0">;
+def note_partial_spec_not_selected_less_constrained : Note<
+    "candidate is less constrained than the selected specialization">;
 def err_partial_spec_redeclared : Error<
   "class template partial specialization %0 cannot be redeclared">;
 def note_prev_partial_spec_here : Note<
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index ba215e7e18d7ba..02ff0e383e1124 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11695,6 +11695,24 @@ class Sema final : public SemaBase {
       const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
       bool Complain = true, bool *Unreachable = nullptr);
 
+  /// Diagnose any candidate class template partial specializations that were
+  /// rejected due to unsatisfied constraints.
+  void NoteUnsatisfiedPartialSpecializations(
+      SourceLocation Loc, ClassTemplateDecl *Template,
+      ArrayRef<TemplateArgument> Args,
+      const ClassTemplatePartialSpecializationDecl *Selected = nullptr);
+  void NoteUnsatisfiedPartialSpecializations(
+      SourceLocation Loc, const ClassTemplateSpecializationDecl *Spec);
+
+  /// Diagnose any candidate variable template partial specializations that
+  /// were rejected due to unsatisfied constraints.
+  void NoteUnsatisfiedPartialSpecializations(
+      SourceLocation Loc, VarTemplateDecl *Template,
+      ArrayRef<TemplateArgument> Args,
+      const VarTemplatePartialSpecializationDecl *Selected = nullptr);
+  void NoteUnsatisfiedPartialSpecializations(
+      SourceLocation Loc, const VarTemplateSpecializationDecl *Spec);
+
   /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
   /// that the template parameter 'PrevDecl' is being shadowed by a new
   /// declaration at location Loc. Returns true to indicate that this is
diff --git a/clang/lib/Sema/SemaCXXScopeSpec.cpp b/clang/lib/Sema/SemaCXXScopeSpec.cpp
index 5c365de4308316..db8a092d55360e 100644
--- a/clang/lib/Sema/SemaCXXScopeSpec.cpp
+++ b/clang/lib/Sema/SemaCXXScopeSpec.cpp
@@ -803,10 +803,13 @@ bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
         Diag(ND->getLocation(), diag::note_entity_declared_at)
             << IdInfo.Identifier;
     }
-  } else if (SS.isSet())
+  } else if (SS.isSet()) {
     Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
         << LookupCtx << SS.getRange();
-  else
+    if (const auto *CTSD =
+            dyn_cast_or_null<ClassTemplateSpecializationDecl>(LookupCtx))
+      NoteUnsatisfiedPartialSpecializations(IdInfo.IdentifierLoc, CTSD);
+  } else
     Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
         << IdInfo.Identifier;
 
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 9cf100221704f0..6efe33096fd07b 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -13455,6 +13455,9 @@ NamedDecl *Sema::BuildUsingDeclaration(
     } else {
       Diag(IdentLoc, diag::err_no_member)
         << NameInfo.getName() << LookupContext << SS.getRange();
+      if (const auto *CTSD =
+              dyn_cast_or_null<ClassTemplateSpecializationDecl>(LookupContext))
+        NoteUnsatisfiedPartialSpecializations(IdentLoc, CTSD);
       return BuildInvalid();
     }
   }
@@ -17885,6 +17888,52 @@ static bool UsefulToPrintExpr(const Expr *E) {
   return true;
 }
 
+static void DiagnoseStaticAssertPartialSpecializations(Sema &S, const Expr *E) {
+  if (!E)
+    return;
+  E = E->IgnoreParenImpCasts();
+  if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
+    DiagnoseStaticAssertPartialSpecializations(S, UO->getSubExpr());
+    return;
+  }
+  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
+    DiagnoseStaticAssertPartialSpecializations(S, BO->getLHS());
+    DiagnoseStaticAssertPartialSpecializations(S, BO->getRHS());
+    return;
+  }
+  if (const auto *Ref = dyn_cast<DeclRefExpr>(E)) {
+    if (const auto *VTSD =
+            dyn_cast<VarTemplateSpecializationDecl>(Ref->getDecl())) {
+      S.NoteUnsatisfiedPartialSpecializations(E->getExprLoc(), VTSD);
+      return;
+    }
+    if (Ref->hasQualifier()) {
+      if (const Type *T = Ref->getQualifier().getAsType()) {
+        if (const auto *RD = T->getAsCXXRecordDecl()) {
+          if (const auto *CTSD =
+                  dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
+            S.NoteUnsatisfiedPartialSpecializations(E->getExprLoc(), CTSD);
+            return;
+          }
+        }
+      }
+    }
+    if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(
+            Ref->getDecl()->getDeclContext())) {
+      S.NoteUnsatisfiedPartialSpecializations(E->getExprLoc(), CTSD);
+      return;
+    }
+  }
+  if (const auto *ME = dyn_cast<MemberExpr>(E)) {
+    if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(
+            ME->getMemberDecl()->getDeclContext())) {
+      S.NoteUnsatisfiedPartialSpecializations(E->getExprLoc(), CTSD);
+      return;
+    }
+    DiagnoseStaticAssertPartialSpecializations(S, ME->getBase());
+  }
+}
+
 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
   // FIXME: Should we also ignore explicit casts?
   E = E->IgnoreParenImpCasts();
@@ -17922,10 +17971,13 @@ void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
           << DiagSides[0].ValueString << Op->getOpcodeStr()
           << DiagSides[1].ValueString << Op->getSourceRange();
     }
+    DiagnoseStaticAssertPartialSpecializations(*this, LHS);
+    DiagnoseStaticAssertPartialSpecializations(*this, RHS);
   } else if (const auto *RE = dyn_cast<RequiresExpr>(E)) {
     DiagnoseUnsatisfiedRequiresExpr(RE);
   } else {
     DiagnoseTypeTraitDetails(E);
+    DiagnoseStaticAssertPartialSpecializations(*this, E);
   }
 }
 
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index a14c3d50d12851..89128a6722054b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -3120,6 +3120,9 @@ ExprResult Sema::BuildQualifiedDeclarationNameExpr(
         return ExprError();
     Diag(NameInfo.getLoc(), diag::err_no_member)
       << NameInfo.getName() << DC << SS.getRange();
+    if (const auto *CTSD =
+            dyn_cast_or_null<ClassTemplateSpecializationDecl>(DC))
+      NoteUnsatisfiedPartialSpecializations(NameInfo.getLoc(), CTSD);
     return ExprError();
   }
 
diff --git a/clang/lib/Sema/SemaExprMember.cpp b/clang/lib/Sema/SemaExprMember.cpp
index 14248802a6c7d1..d003a965ad094f 100644
--- a/clang/lib/Sema/SemaExprMember.cpp
+++ b/clang/lib/Sema/SemaExprMember.cpp
@@ -962,12 +962,16 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
     if (RetryExpr.isUsable())
       Diag(OpLoc, diag::err_no_member_overloaded_arrow)
           << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
-    else
+    else {
       Diag(R.getNameLoc(), diag::err_no_member)
           << MemberName << DC
           << (SS.isSet()
                   ? SS.getRange()
                   : (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()));
+      if (const auto *CTSD =
+              dyn_cast_or_null<ClassTemplateSpecializationDecl>(DC))
+        NoteUnsatisfiedPartialSpecializations(R.getNameLoc(), CTSD);
+    }
     return RetryExpr;
   }
 
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 8219d5568bdfdd..02dd377b4fcb5f 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -12525,6 +12525,16 @@ static TemplateDecl *getDescribedTemplate(Decl *Templated) {
                    " for bad deduction diagnosis");
 }
 
+static const TemplateParameterList *getTemplateParameters(Decl *Templated) {
+  if (auto *TD = dyn_cast<TemplateDecl>(Templated))
+    return TD->getTemplateParameters();
+  if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Templated))
+    return CTPSD->getTemplateParameters();
+  if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Templated))
+    return VTPSD->getTemplateParameters();
+  return getDescribedTemplate(Templated)->getTemplateParameters();
+}
+
 /// Diagnose a failed template-argument deduction.
 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
                                  DeductionFailureInfo &DeductionFailure,
@@ -12665,7 +12675,7 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
     TemplateArgString = " ";
     TemplateArgString += S.getTemplateArgumentBindingsText(
-        getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
+        getTemplateParameters(Templated), *Args);
     if (TemplateArgString.size() == 1)
       TemplateArgString.clear();
     S.Diag(Templated->getLocation(),
@@ -12694,7 +12704,7 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
             DeductionFailure.getTemplateArgumentList()) {
       TemplateArgString = " ";
       TemplateArgString += S.getTemplateArgumentBindingsText(
-          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
+          getTemplateParameters(Templated), *Args);
       if (TemplateArgString.size() == 1)
         TemplateArgString.clear();
     }
@@ -12745,7 +12755,7 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
             DeductionFailure.getTemplateArgumentList()) {
       TemplateArgString = " ";
       TemplateArgString += S.getTemplateArgumentBindingsText(
-          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
+          getTemplateParameters(Templated), *Args);
       if (TemplateArgString.size() == 1)
         TemplateArgString.clear();
     }
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 0caf7593ca9d5b..12f81e0714ada5 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -891,12 +891,18 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
         << (TSK != TSK_ImplicitInstantiation)
         << InstantiationTy;
       NoteTemplateLocation(*Pattern);
+      if (const auto *CTSD =
+              dyn_cast<ClassTemplateSpecializationDecl>(Instantiation))
+        NoteUnsatisfiedPartialSpecializations(PointOfInstantiation, CTSD);
     } else {
       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
         Diag(PointOfInstantiation,
              diag::err_explicit_instantiation_undefined_var_template)
           << Instantiation;
+        if (const auto *VTSD =
+                dyn_cast<VarTemplateSpecializationDecl>(Instantiation))
+          NoteUnsatisfiedPartialSpecializations(PointOfInstantiation, VTSD);
         Instantiation->setInvalidDecl();
       } else
         Diag(PointOfInstantiation,
@@ -916,6 +922,152 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
   return true;
 }
 
+void Sema::NoteUnsatisfiedPartialSpecializations(
+    SourceLocation Loc, ClassTemplateDecl *Template,
+    ArrayRef<TemplateArgument> Args,
+    const ClassTemplatePartialSpecializationDecl *Selected) {
+  if (!Template)
+    return;
+
+  SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
+  Template->getPartialSpecializations(PartialSpecs);
+  if (PartialSpecs.empty())
+    return;
+
+  llvm::sort(PartialSpecs, [this](const auto *A, const auto *B) {
+    return SourceMgr.isBeforeInTranslationUnit(A->getLocation(),
+                                               B->getLocation());
+  });
+
+  for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
+    if (Partial == Selected)
+      continue;
+
+    if (!Partial->hasAssociatedConstraints())
+      continue;
+
+    TemplateDeductionInfo Info(Loc);
+    TemplateDeductionResult Result =
+        DeduceTemplateArguments(Partial, Args, Info);
+
+    if (Result == TemplateDeductionResult::ConstraintsNotSatisfied) {
+      SmallString<128> TemplateArgString;
+      TemplateArgumentList *DeducedArgs = Info.takeSugared();
+      if (!DeducedArgs)
+        DeducedArgs = Info.takeCanonical();
+      if (DeducedArgs) {
+        TemplateArgString = " ";
+        TemplateArgString += getTemplateArgumentBindingsText(
+            Partial->getTemplateParameters(), *DeducedArgs);
+        if (TemplateArgString.size() == 1)
+          TemplateArgString.clear();
+      }
+      Diag(Partial->getLocation(),
+           diag::note_ovl_candidate_unsatisfied_constraints)
+          << TemplateArgString;
+      DiagnoseUnsatisfiedConstraint(Info.AssociatedConstraintsSatisfaction);
+    } else if (Result == TemplateDeductionResult::Success && Selected) {
+      llvm::SmallVector<AssociatedConstraint, 3> ACSelected, ACPartial;
+      Selected->getAssociatedConstraints(ACSelected);
+      Partial->getAssociatedConstraints(ACPartial);
+      bool SelectedAtLeastAsConstrained = false;
+      bool PartialAtLeastAsConstrained = false;
+      if (!IsAtLeastAsConstrained(Selected, ACSelected, Partial, ACPartial,
+                                  SelectedAtLeastAsConstrained) &&
+          !IsAtLeastAsConstrained(Partial, ACPartial, Selected, ACSelected,
+                                  PartialAtLeastAsConstrained) &&
+          SelectedAtLeastAsConstrained && !PartialAtLeastAsConstrained) {
+        Diag(Partial->getLocation(),
+             diag::note_partial_spec_not_selected_less_constrained);
+      }
+    }
+  }
+}
+
+void Sema::NoteUnsatisfiedPartialSpecializations(
+    SourceLocation Loc, const ClassTemplateSpecializationDecl *Spec) {
+  if (!Spec)
+    return;
+  ClassTemplateDecl *Template = Spec->getSpecializedTemplate();
+  auto *Selected = dyn_cast<ClassTemplatePartialSpecializationDecl *>(
+      Spec->getSpecializedTemplateOrPartial());
+  NoteUnsatisfiedPartialSpecializations(
+      Loc, Template, Spec->getTemplateArgs().asArray(), Selected);
+}
+
+void Sema::NoteUnsatisfiedPartialSpecializations(
+    SourceLocation Loc, VarTemplateDecl *Template,
+    ArrayRef<TemplateArgument> Args,
+    const VarTemplatePartialSpecializationDecl *Selected) {
+  if (!Template)
+    return;
+
+  SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
+  Template->getPartialSpecializations(PartialSpecs);
+  if (PartialSpecs.empty())
+    return;
+
+  llvm::sort(PartialSpecs, [this](const auto *A, const auto *B) {
+    return SourceMgr.isBeforeInTranslationUnit(A->getLocation(),
+                                               B->getLocation());
+  });
+
+  for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
+    if (Partial == Selected)
+      continue;
+
+    if (!Partial->hasAssociatedConstraints())
+      continue;
+
+    TemplateDeductionInfo Info(Loc);
+    TemplateDeductionResult Result =
+        DeduceTemplateArguments(Partial, Args, Info);
+
+    if (Result == TemplateDeductionResult::ConstraintsNotSatisfied) {
+      SmallString<128> TemplateArgString;
+      TemplateArgumentList *DeducedArgs = Info.takeSugared();
+      if (!DeducedArgs)
+        DeducedArgs = Info.takeCanonical();
+      if (DeducedArgs) {
+        TemplateArgString = " ";
+        TemplateArgString += getTemplateArgumentBindingsText(
+            Partial->getTemplateParameters(), *DeducedArgs);
+        if (TemplateArgString.size() == 1)
+          TemplateArgString.clear();
+      }
+      Diag(Partial->getLocation(),
+           diag::note_ovl_candidate_unsatisfied_constraints)
+          << TemplateArgString;
+      DiagnoseUnsatisfiedConstraint(Info.AssociatedConstraintsSatisfaction);
+    } else if (Result == TemplateDeductionResult::Success && Selected) {
+      llvm::SmallVector<AssociatedConstraint, 3> ACSelected, ACPartial;
+      Selected->getAssociatedConstraints(ACSelected);
+      Partial->getAssociatedConstraints(ACPartial);
+      bool SelectedAtLeastAsConstrained = false;
+      bool PartialAtLeastAsConstrained = false;
+      if (!IsAtLeastAsConstrained(Selected, ACSelected, Partial, ACPartial,
+                                  SelectedAtLeastAsConstrained) &&
+          !IsAtLeastAsConstrained(Partial, ACPartial, Selected, ACSelected,
+                                  PartialAtLeastAsConstrained) &&
+          SelectedAtLeastAsConstrained && !PartialAtLeastAsConstrained) {
+        Diag(Partial->getLocation(),
+             diag::note_partial_spec_not_selected_less_constrained);
+      }
+    }
+  }
+}
+
+void Sema::NoteUnsatisfiedPartialSpecializations(
+    SourceLocation Loc, const VarTemplateSpecializationDecl *Spec) {
+  if (!Spec)
+    return;
+  VarTemplateDecl *Template = Spec->getSpecializedTemplate();
+  auto *Selected = dyn_cast<VarTemplatePartialSpecializationDecl *>(
+      Spec->getSpecializedTemplateOrPartial());
+  NoteUnsatisfiedPartialSpecializations(
+      Loc, Template, Spec->getTemplateArgs().asArray(), Selected);
+}
+
 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
                                            bool SupportedForCompatibility) {
   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
@@ -5079,6 +5231,9 @@ ExprResult Sema::BuildQualifiedTemplateIdExpr(
     DeclContext *DC = computeDeclContext(SS);
     Diag(NameInfo.getLoc(), diag::err_no_member)
       << NameInfo.getName() << DC << SS.getRange();
+    if (const auto *CTSD =
+            dyn_cast_or_null<ClassTemplateSpecializationDecl>(DC))
+      NoteUnsatisfiedPartialSpecializations(NameInfo.getLoc(), CTSD);
     return ExprError();
   }
 
@@ -5172,10 +5327,13 @@ TemplateNameKind Sema::ActOnTemplateName(Scope *S,
     if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
                             /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
         !R.isAmbiguous()) {
-      if (LookupCtx)
+      if (LookupCtx) {
         Diag(Name.getBeginLoc(), diag::err_no_member)
             << DNI.getName() << LookupCtx << SS.getRange();
-      else
+        if (const auto *CTSD =
+                dyn_cast_or_null<ClassTemplateSpecializationDecl>(LookupCtx))
+          NoteUnsatisfiedPartialSpecializations(Name.getBeginLoc(), CTSD);
+      } else
         Diag(Name.getBeginLoc(), diag::err_undeclared_use)
             << DNI.getName() << SS.getRange();
     }
@@ -11646,9 +11804,12 @@ Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
   // type. Emit an appropriate diagnostic and return an error.
   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
                         IILoc);
-  if (Ctx)
+  if (Ctx) {
     Diag(IILoc, DiagID) << FullRange << Name << Ctx;
-  else
+    if (const auto *CTSD =
+            dyn_cast_or_null<ClassTemplateSpecializationDecl>(Ctx))
+      NoteUnsatisfiedPartialSpecializations(IILoc, CTSD);
+  } else
     Diag(IILoc, DiagID) << FullRange << Name;
   if (Referenced)
     Diag(Referenced->getLocation(),
diff --git a/clang/test/CXX/temp/temp.constr/temp.constr.constr/partial-specializations.cpp b/clang/test/CXX/temp/temp.constr/temp.constr.constr/partial-specializations.cpp
index 309a434b7fb341..caeb0e3190bbac 100644
--- a/clang/test/CXX/temp/temp.constr/temp.constr.constr/partial-specializations.cpp
+++ b/clang/test/CXX/temp/temp.constr/temp.constr.constr/partial-specializations.cpp
@@ -70,10 +70,10 @@ namespace variable_templates
 
   template<typename T> requires A<T>::type // expected-note{{in instantiation of template class 'variable_templates::A<int *>' requested here}}
                                            // expected-note at -1{{while substituting template arguments into constraint expression here}}
-  constexpr bool v1<T*> = true;
+  constexpr bool v1<T*> = true; // expected-note{{candidate template ignored: constraints not satisfied [with T = int *]}}
 
   template<typename T> requires (T{}) // expected-error{{atomic constraint must be of type 'bool' (found 'int')}}
-  constexpr bool v1<T**> = true;
+  constexpr bool v1<T**> = true; // expected-note{{candidate template ignored: constraints not satisfied [with T = int]}}
 
   static_assert(v1<int**>); // expected-note{{while checking constraint satisfaction for variable template partial specialization 'v1<int *>' required here}}
   // expected-note at -1{{while checking constraint satisfaction for variable template partial specialization 'v1<int>' required here}}
diff --git a/clang/test/SemaTemplate/concepts-class-template-partial-spec-notes.cpp b/clang/test/SemaTemplate/concepts-class-template-partial-spec-notes.cpp
new file mode 100644
index 00000000000000..0284274ddd22e5
--- /dev/null
+++ b/clang/test/SemaTemplate/concepts-class-template-partial-spec-notes.cpp
@@ -0,0 +1,123 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template <typename T>
+concept integral = __is_integral(T); // expected-note 5 {{because '__is_integral(double)' evaluated to false}}
+
+// Case 1: Issue #238212 reproducer (static_assert failure with concept constraint)
+namespace case1 {
+  template <typename T>
+  struct trait {
+    static constexpr bool value = false;
+  };
+
+  template <integral T> // expected-note {{because 'double' does not satisfy 'integral'}}
+  struct trait<T> { // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+    static constexpr bool value = true;
+  };
+
+  static_assert(trait<int>::value); // OK, successful compilation has no diagnostics
+  static_assert(trait<double>::value, "expected integral"); // expected-error {{static assertion failed due to requirement 'case1::trait<double>::value': expected integral}}
+}
+
+// Case 2: requires-clause with unsatisfied atomic constraint
+namespace case2 {
+  template <typename T>
+  struct trait {
+    static constexpr bool value = false;
+  };
+
+  template <typename T>
+  requires (sizeof(T) == 4) // expected-note {{because 'sizeof(double) == 4' (8 == 4) evaluated to false}}
+  struct trait<T> { // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+    static constexpr bool value = true;
+  };
+
+  static_assert(trait<double>::value); // expected-error {{static assertion failed due to requirement 'case2::trait<double>::value'}}
+}
+
+// Case 3: Undefined primary template
+namespace case3 {
+  template <typename T>
+  struct trait; // expected-note {{template is declared here}}
+
+  template <integral T> // expected-note {{because 'double' does not satisfy 'integral'}}
+  struct trait<T> { // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+    using type = int;
+  };
+
+  trait<double> t; // expected-error {{implicit instantiation of undefined template 'case3::trait<double>'}}
+}
+
+// Case 4: Missing member in primary template
+namespace case4 {
+  template <typename T>
+  struct trait {};
+
+  template <integral T> // expected-note {{because 'double' does not satisfy 'integral'}}
+  struct trait<T> { // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+    using type = int;
+  };
+
+  typename trait<double>::type x; // expected-error {{no type named 'type' in 'case4::trait<double>'}}
+  typename trait<int>::type y; // OK
+}
+
+// Case 5: Multiple constrained partial specializations
+namespace case5 {
+  template <typename T>
+  struct trait {
+    static constexpr bool value = false;
+  };
+
+  template <typename T>
+  requires (sizeof(T) == 1) // expected-note {{because 'sizeof(double) == 1' (8 == 1) evaluated to false}}
+  struct trait<T> { // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+    static constexpr bool value = true;
+  };
+
+  template <integral T> // expected-note {{because 'double' does not satisfy 'integral'}}
+  struct trait<T> { // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+    static constexpr bool value = true;
+  };
+
+  static_assert(trait<double>::value); // expected-error {{static assertion failed due to requirement 'case5::trait<double>::value'}}
+}
+
+// Case 6: Variable template partial specialization
+namespace case6 {
+  template <typename T>
+  constexpr bool trait_v = false;
+
+  template <integral T> // expected-note {{because 'double' does not satisfy 'integral'}}
+  constexpr bool trait_v<T> = true; // expected-note {{candidate template ignored: constraints not satisfied [with T = double]}}
+
+  static_assert(trait_v<int>); // OK
+  static_assert(trait_v<double>); // expected-error {{static assertion failed due to requirement 'trait_v<double>'}}
+}
+
+// Case 7: Partial ordering - candidate rejected due to partial ordering rather than constraints
+namespace case7 {
+  template <typename T>
+  concept C1 = sizeof(T) >= 4;
+
+  template <typename T>
+  concept C2 = C1<T> && sizeof(T) <= 8;
+
+  template <typename T>
+  struct trait {
+    static constexpr int value = 0;
+  };
+
+  template <C1 T>
+  struct trait<T> { // expected-note {{candidate is less constrained than the selected specialization}}
+    static constexpr int value = 1;
+  };
+
+  template <C2 T>
+  struct trait<T> {
+    static constexpr int value = 2;
+  };
+
+  static_assert(trait<int>::value == 1); // expected-error {{static assertion failed due to requirement 'case7::trait<int>::value == 1'}} \
+                                         // expected-note {{expression evaluates to '2 == 1'}}
+}
diff --git a/clang/test/SemaTemplate/concepts-recovery-expr.cpp b/clang/test/SemaTemplate/concepts-recovery-expr.cpp
index aa4ed53ec4ed34..a0e14b195b41e9 100644
--- a/clang/test/SemaTemplate/concepts-recovery-expr.cpp
+++ b/clang/test/SemaTemplate/concepts-recovery-expr.cpp
@@ -198,11 +198,11 @@ template <class, class> struct basic_format_context {};
 
 template <typename CharType>
 concept has_format_function =
-    format(basic_format_context<CharType, CharType>());
+    format(basic_format_context<CharType, CharType>()); // expected-note {{because substituted constraint expression is ill-formed: use of undeclared identifier 'format'}}
 
 template <typename ValueType, typename CharType>
-  requires has_format_function<CharType>
-struct formatter<ValueType, CharType> {
+  requires has_format_function<CharType> // expected-note {{because 'int' does not satisfy 'has_format_function'}}
+struct formatter<ValueType, CharType> { // expected-note {{candidate template ignored: constraints not satisfied [with ValueType = int, CharType = int]}}
   template <typename OutputIt>
   CharType format(basic_format_context<OutputIt, CharType>);
 };
diff --git a/clang/test/SemaTemplate/concepts.cpp b/clang/test/SemaTemplate/concepts.cpp
index 4e7001b5c519df..127689cb26f719 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -328,8 +328,8 @@ template <typename Itr> struct ItrTraits {
   template <typename PtrItr> struct Ptr {
   };
   template <typename PtrItr>
-    requires requires { typename PtrItr::pointer; }
-  struct Ptr<PtrItr> {
+    requires requires { typename PtrItr::pointer; } // expected-note {{because 'typename PtrItr::pointer' would be invalid: no type named 'pointer' in 'DeducedTemplateArgs::not_complete_itr'}}
+  struct Ptr<PtrItr> { // expected-note {{candidate template ignored: constraints not satisfied [with PtrItr = DeducedTemplateArgs::not_complete_itr]}}
     using type = typename Itr::pointer;
   };
   using pointer = typename Ptr<Itr>::type; // #TRAITS_PTR



More information about the cfe-commits mailing list