← Back to Pull requests

[clang] Add regression tests for GH214477 #217709

Merged
akash-manna-sky merged 2 files (79 lines) on Nov 30, 2026 16:55 UTC
View on GitHub
akash-manna-sky akash-manna-sky commented on Aug 20, 2026 17:40 UTC
Author

Fixes #214477

The bogus "deduced type depends on itself" error was fixed by #237843. I added the issue's reproducers tests for this.

LLM tools were used for this contribution.

Diff: 79 lines (+79 / -0) across 2 files Reviewer: cor3ntin Review duration: 146834m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.36) × (1 − Review Confidence (0.74)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.36 · 79 lines diff across 2 files
0.36
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.51 · 5 substantive comment(s)
0.51
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
74%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.262
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
16 items
github-actions[bot] github-actions[bot] commented on Aug 20, 2026 17:43 UTC
Bot

<!--LLVM NEW CONTRIBUTOR COMMENT-->

Hello @akash-manna-sky :wave:

Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.

All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.

  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.
  • Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.

    ---

    Frequently asked questions

    How do I add reviewers?

    This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.

    You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.

    What if there are no comments?

    If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.

    Are any special GitHub settings required to contribute to LLVM?

    We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.

    ---

    If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.

    Thank you,
    The LLVM Community

    llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Aug 21, 2026 04:44 UTC
    Bot

    <!--LLVM PR SUMMARY COMMENT-->

    @llvm/pr-subscribers-clang

    Author: Akash Manna (akash-manna-sky)

    <details>
    <summary>Changes</summary>

    Fixes #<!-- -->214477

    When a variable template specialization with a deduced type is first named in a context that doesn't require its definition (e.g. decltype(obj&lt;0&gt;)), Clang creates the specialization declaration, but for a member variable template of a class template the initializer still lives on the in-class pattern, so the type stays undeduced. Nothing completes it afterwards: the undeduced-type clause in DoMarkVarDeclReferenced skips variables usable in constant expressions, and the constant-evaluation path doesn't apply in unevaluated contexts. On the next reference, CheckVarTemplateId finds the existing specialization with an undeduced type and just assumes it is substituting the variable's own initializer, emitting "the type of variable template specialization declared with deduced type depends on itself" for perfectly valid code. As a side effect, decltype on such a specialization also yields the undeduced placeholder type instead of the deduced one.

    CheckVarTemplateId now emits that error only when the specialization's initializer instantiation is actually in progress, checked against Sema::InstantiatingSpecializations. The eager initializer instantiation in BuildVariableInstantiation registers itself there with a RecursiveInstGuard, so genuine cycles (including indirect ones like a&lt;0&gt; = b&lt;0&gt;; b&lt;0&gt; = a&lt;0&gt;;) are still diagnosed. Finally, the !UsableInConstantExpr restriction in DoMarkVarDeclReferenced is dropped so that any reference to a specialization with a still-undeduced type instantiates its definition, meaning decltype deduces the type the same way GCC does.

    LLM tools were used for this contribution. I've reviewed, built, and tested the change myself before pushing to GitHub.

    ---
    Full diff: https://github.com/llvm/llvm-project/pull/217709.diff

    5 Files Affected:

  • (modified) clang/docs/ReleaseNotes.md (+5)

  • (modified) clang/lib/Sema/SemaExpr.cpp (+1-2)

  • (modified) clang/lib/Sema/SemaTemplate.cpp (+10-4)

  • (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+2)

  • (added) clang/test/SemaTemplate/GH214477.cpp (+76)
  • ``````

    diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
    index 8c9467ca7b742..0ac80a68f46ef 100644
    --- a/clang/docs/ReleaseNotes.md
    +++ b/clang/docs/ReleaseNotes.md
    @@ -528,6 +528,11 @@ features cannot lower the translation-unit ABI level;
       parameter that follows a parameter pack (e.g.
       `template <typename... T> S::S(T..., int = 10) {}`).  (#GH216211)
     
    +- Fixed a bogus "deduced type depends on itself" error when a variable template
    +  specialization with a deduced type was first named in a context that did not
    +  require its definition (such as ``decltype``) and then referenced again;
    +  Clang now instantiates the definition to deduce the type instead. (#GH214477)
    +
     #### Bug Fixes to AST Handling
     
     - Fixed a non-deterministic ordering of unused local typedefs that made
    diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
    index da76bbf3c35f0..a5a7398aee15f 100644
    --- a/clang/lib/Sema/SemaExpr.cpp
    +++ b/clang/lib/Sema/SemaExpr.cpp
    @@ -20715,8 +20715,7 @@ static void DoMarkVarDeclReferenced(
     
       bool NeedDefinition =
           OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
    -      (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
    -       Var->getType()->isUndeducedType());
    +      (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());
     
       assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
              "Can't instantiate a partial template specialization.");
    diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
    index 1fde412749cc9..9b844a8da1403 100644
    --- a/clang/lib/Sema/SemaTemplate.cpp
    +++ b/clang/lib/Sema/SemaTemplate.cpp
    @@ -4658,18 +4658,24 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
               Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
         checkSpecializationReachability(TemplateNameLoc, Spec);
         if (Spec->getType()->isUndeducedType()) {
    -      if (ParsingInitForAutoVars.count(Spec))
    +      if (ParsingInitForAutoVars.count(Spec)) {
             Diag(TemplateNameLoc,
                  diag::err_auto_variable_cannot_appear_in_own_initializer)
                 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
                 << Spec->getType();
    -      else
    +        return true;
    +      }
    +      if (InstantiatingSpecializations.contains(
    +              {Spec->getCanonicalDecl(),
    +               unsigned(RecursiveInstGuard::Kind::Template)})) {
             // We are substituting the initializer of this variable template
             // specialization.
             Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
                 << Spec << Spec->getType();
    -
    -      return true;
    +        return true;
    +      }
    +      // Not yet deduced; the type is completed when the definition is
    +      // instantiated.
         }
         // If we already have a variable template specialization, return it.
         return Spec;
    diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
    index ff29ae27a3b66..fab93559a3f6c 100644
    --- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
    +++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
    @@ -6523,6 +6523,8 @@ void Sema::BuildVariableInstantiation(
         // We're producing a template. Don't instantiate the initializer yet.
       } else if (NewVar->getType()->isUndeducedType()) {
         // We need the type to complete the declaration of the variable.
    +    RecursiveInstGuard AlreadyInstantiating(*this, NewVar,
    +                                            RecursiveInstGuard::Kind::Template);
         InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
       } else if (InstantiatingSpecFromTemplate ||
                  (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
    diff --git a/clang/test/SemaTemplate/GH214477.cpp b/clang/test/SemaTemplate/GH214477.cpp
    new file mode 100644
    index 0000000000000..76f8e9a2c51e8
    --- /dev/null
    +++ b/clang/test/SemaTemplate/GH214477.cpp
    @@ -0,0 +1,76 @@
    +// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
    +// RUN: %clang_cc1 -fsyntax-only -std=c++26 -verify %s
    +
    +namespace GH214477 {
    +
    +struct dummy {};
    +template <typename A> struct real { A a; };
    +
    +template <typename V> struct Tests {
    +  template <int> static constexpr dummy obj = {};
    +
    +  const int reg = [] {
    +    using X = decltype(obj<0>);
    +    static_assert(__is_same(X, const real<int>));
    +    (void)&obj<0>;
    +    return 0;
    +  }();
    +
    +  template <int Tmp>
    +    requires(Tmp == 0)
    +  static constexpr real obj<Tmp> = {0};
    +};
    +
    +void test() { (void)Tests<int>{}; }
    +
    +template <typename V> struct Tests2 {
    +  template <int> static constexpr dummy obj = {};
    +
    +  void f() {
    +    using X = decltype(obj<0>);
    +    static_assert(__is_same(X, const real<int>));
    +    (void)&obj<0>;
    +  }
    +
    +  template <int Tmp>
    +    requires(Tmp == 0)
    +  static constexpr real obj<Tmp> = {0};
    +};
    +
    +void test2() { Tests2<int>{}.f(); }
    +
    +template <typename V> struct Tests3 {
    +  template <int> static constexpr dummy obj = {};
    +
    +  const int reg = [] {
    +    (void)&obj<0>;
    +    using X = decltype(obj<0>);
    +    static_assert(__is_same(X, const real<int>));
    +    return 0;
    +  }();
    +
    +  template <int Tmp>
    +    requires(Tmp == 0)
    +  static constexpr real obj<Tmp> = {0};
    +};
    +
    +void test3() { (void)Tests3<int>{}; }
    +
    +} // namespace GH214477
    +
    +namespace deduced_type_cycle {
    +
    +template <int> constexpr auto a = 0;
    +template <int> constexpr auto b = 0;
    +
    +template <int N>
    +  requires(N == 0)
    +constexpr auto a<N> = b<N>; // expected-note {{in instantiation of variable template specialization 'deduced_type_cycle::b<N>' requested here}}
    +
    +template <int N>
    +  requires(N == 0)
    +constexpr auto b<N> = a<N>; // expected-error {{the type of variable template specialization 'a<0>' declared with deduced type 'const auto' depends on itself}}
    +
    +auto y = a<0>; // expected-note {{in instantiation of variable template specialization 'deduced_type_cycle::a<N>' requested here}}
    +
    +} // namespace deduced_type_cycle
    
    
    ``````

    </details>

    zyn0217 zyn0217 commented on code on Aug 21, 2026 05:55 UTC
    Code Review
    clang/lib/Sema/SemaExpr.cpp:1
    @@ -20715,8 +20715,7 @@ static void DoMarkVarDeclReferenced(
     
       bool NeedDefinition =
           OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
    -      (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
    -       Var->getType()->isUndeducedType());
    +      (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());

    Why is UsableInConstantExpr set for this issue?

    zyn0217 zyn0217 requested changes on Aug 21, 2026 05:55 UTC
    Changes Requested Reviewer

    Requested changes.

    akash-manna-sky akash-manna-sky commented on code on Aug 21, 2026 06:16 UTC
    Code Review
    clang/lib/Sema/SemaExpr.cpp:1
    @@ -20715,8 +20715,7 @@ static void DoMarkVarDeclReferenced(
     
       bool NeedDefinition =
           OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
    -      (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
    -       Var->getType()->isUndeducedType());
    +      (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());

    So I think here obj<0> is constexpr, and mightBeUsableInConstantExpressions() returns true for constexpr variables even while the type is still undeduced. The !UsableInConstantExpr guard assumed the NeededForConstantEvaluation branch would instantiate such variables, but that branch requires isPotentiallyConstantEvaluatedContext(), which is false in an unevaluated operand like decltype. So when the first reference is in decltype, neither branch requested the definition and the type never got deduced — that's the state the "depends on itself" diagnostic then misreads. Since the type of a deduced-type variable is needed at any reference, the undeduced case shouldn't be gated on constant-expression usability...

    zyn0217 zyn0217 commented on code on Aug 21, 2026 06:57 UTC
    Code Review
    clang/lib/Sema/SemaExpr.cpp:1
    @@ -20715,8 +20715,7 @@ static void DoMarkVarDeclReferenced(
     
       bool NeedDefinition =
           OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
    -      (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
    -       Var->getType()->isUndeducedType());
    +      (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());

    I don't think it makes much sense to allow instantiation within unevaluated context. I question if this should be IFNDR @cor3ntin

    akash-manna-sky akash-manna-sky commented on code on Aug 21, 2026 10:03 UTC
    Code Review
    clang/lib/Sema/SemaExpr.cpp:1
    @@ -20715,8 +20715,7 @@ static void DoMarkVarDeclReferenced(
     
       bool NeedDefinition =
           OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
    -      (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
    -       Var->getType()->isUndeducedType());
    +      (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());

    what do you think would be the right approach here? If you have a better way to address this issue, I'd be happy to give it a try. @zyn0217 @cor3ntin

    akash-manna-sky akash-manna-sky commented on Aug 27, 2026 08:46 UTC
    Author

    Hi @zyn0217 and @cor3ntin, have you had a chance to take another look at this PR? It would be great to get your feedback so we can move forward with it. Thanks!

    zyn0217 zyn0217 commented on Aug 27, 2026 09:04 UTC
    Contributor

    I wonder if you or your AI has ever read https://llvm.org/docs/Contributing.html#how-to-submit-a-patch

    If you have received no comments on your patch for a week, you can request a review by ‘ping’ing the GitHub PR with “Ping” in a comment. The common courtesy ‘ping’ rate is once a week. Please remember that you are asking for valuable time from other professional developers.

    Thanks.

    akash-manna-sky akash-manna-sky commented on Sep 10, 2026 11:07 UTC
    Author

    I wonder if you or your AI has ever read https://llvm.org/docs/Contributing.html#how-to-submit-a-patch

    > > If you have received no comments on your patch for a week, you can request a review by ‘ping’ing the GitHub PR with “Ping” in a comment. The common courtesy ‘ping’ rate is once a week. Please remember that you are asking for valuable time from other professional developers.

    > Thanks.

    Ping

    akash-manna-sky akash-manna-sky commented on Sep 18, 2026 18:36 UTC
    Author

    @cor3ntin Please take a look.

    zwuis zwuis commented on Nov 27, 2026 13:49 UTC
    Contributor

    Superseded by #237843.

    akash-manna-sky akash-manna-sky commented on Nov 27, 2026 14:27 UTC
    Author

    Superseded by #237843.

    Ok.. in that case I will add targeted tests and ask you for review .

    cor3ntin cor3ntin approved these changes on Nov 30, 2026 14:48 UTC
    Approved Reviewer

    Approved these changes.

    github-actions[bot] github-actions[bot] commented on Nov 30, 2026 16:55 UTC
    Bot

    <!--LLVM BUILDBOT INFORMATION COMMENT-->

    @akash-manna-sky Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

    Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

    Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

    How to do this, and the rest of the post-merge process, is covered in detail here.

    If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

    If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

    Reviewers
    Assignees
    akash-manna-sky akash-manna-sky
    Labels
    risk: low confidence: 74.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 35.7% (MEDIUM) · Higher = larger blast radius
    35.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 74.3% · Lower = rushed or shallow review
    74.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.2% · Safe to merge
    9.2%