← Back to Pull requests

[clang] Prevent stack overflow on deeply nested template arguments #224393

Merged
daniel-petrovic merged 2 files (9 lines) on Nov 20, 2026 10:15 UTC
View on GitHub
daniel-petrovic daniel-petrovic commented on Sep 17, 2026 19:46 UTC
Author

Limit template argument nesting and diagnose before exhausting the parser stack.

Fixes #224114

Assisted by: Gemini

Diff: 9 lines (+8 / -1) across 2 files Reviewer: zyn0217 Review duration: 91588m
All Vouch review confidence checks passed
Residual risk 0.06 = Change Risk (0.23) × (1 − Review Confidence (0.75)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.23 · 9 lines diff across 2 files
0.23
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.50 · 5 substantive comment(s)
0.50
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
75%
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.138
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
33 items
github-actions[bot] github-actions[bot] commented on Sep 17, 2026 19:47 UTC
Bot

<!--LLVM NEW CONTRIBUTOR COMMENT-->

Hello @daniel-petrovic :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

    daniel-petrovic daniel-petrovic commented on Sep 17, 2026 19:52 UTC
    Author

    Hello @daniel-petrovic 👋

    > 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

    I have read the contribution policies, including the LLVM AI Tool Use Policy, and have disclosed any AI tool usage in the PR description.

    llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Sep 18, 2026 04:27 UTC
    Bot

    <!--LLVM PR SUMMARY COMMENT-->

    @llvm/pr-subscribers-clang

    Author: Daniel Petrovic (daniel-petrovic)

    <details>
    <summary>Changes</summary>

    Limit template argument nesting and diagnose before exhausting the parser stack.

    Fixes #<!-- -->224114

    Assisted by: Gemini

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

    6 Files Affected:

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

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

  • (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+6)

  • (modified) clang/include/clang/Parse/Parser.h (+8)

  • (modified) clang/lib/Parse/ParseTemplate.cpp (+39)

  • (added) clang/test/Parser/template-argument-depth.cpp (+27)
  • ``````

    diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
    index 18d2895531ea6..acd0b6158e64a 100644
    --- a/clang/docs/ReleaseNotes.md
    +++ b/clang/docs/ReleaseNotes.md
    @@ -600,6 +600,10 @@ features cannot lower the translation-unit ABI level;
     - Fixed a crash when a using-declaration naming an unresolvable member of a
       dependent base was shadowed by an invalid using-declaration. (#GH209427)
     
    +- Fixed a stack overflow (segfault) when parsing deeply nested template
    +  arguments such as ``S<S<S<...>>>``. The parser now rejects nesting deeper
    +  than ``-ftemplate-depth`` with a diagnostic. (#GH224114)
    +
     - Fixed a CTAD bug when combining with concepts. (#GH124715)
     
     - Fixed a regression where an internal-linkage function (e.g. a `static` or
    diff --git a/clang/docs/UsersManual.md b/clang/docs/UsersManual.md
    index 3bec20612c048..4b21d1137c83b 100644
    --- a/clang/docs/UsersManual.md
    +++ b/clang/docs/UsersManual.md
    @@ -4446,6 +4446,11 @@ The default is 1048576, and the limit can be disabled with `-fconstexpr-steps=0`
     
     Sets the limit for recursively nested template instantiations to N.  The
     default is 1024.
    +
    +This option also limits how deeply template arguments may be nested in the
    +source (e.g. the number of levels in ``S<S<S<...>>>``).  Nesting deeper than
    +the limit is rejected with a diagnostic instead of overflowing the parser's
    +stack.
     :::
     
     :::{option} -foperator-arrow-depth=N
    diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
    index 594d158d25e92..bc5c58363a36a 100644
    --- a/clang/include/clang/Basic/DiagnosticParseKinds.td
    +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
    @@ -675,6 +675,12 @@ def err_bracket_depth_exceeded : Error<
       "bracket nesting level exceeded maximum of %0">, DefaultFatal;
     def note_bracket_depth : Note<
       "use -fbracket-depth=N to increase maximum nesting level">;
    +def err_template_argument_depth_exceeded : Error<
    +  "template argument nesting depth exceeded maximum of %0">, DefaultFatal;
    +def err_template_argument_stack_exhausted : Error<
    +  "stack nearly exhausted while parsing nested template arguments">, DefaultFatal;
    +def note_template_argument_depth : Note<
    +  "use -ftemplate-depth=N to increase maximum template argument nesting depth">;
     def err_misplaced_ellipsis_in_declaration : Error<
       "'...' must %select{immediately precede declared identifier|"
       "be innermost component of anonymous pack declaration}0">;
    diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h
    index 6913c42884a36..27fe45f013841 100644
    --- a/clang/include/clang/Parse/Parser.h
    +++ b/clang/include/clang/Parse/Parser.h
    @@ -7922,6 +7922,14 @@ class Parser : public CodeCompletionHandler {
       /// The "depth" of the template parameters currently being parsed.
       unsigned TemplateParameterDepth;
     
    +  /// The current nesting depth of template argument lists being parsed. Each
    +  /// level of nested template-ids (e.g. `A<B<C<...>>>`) recurses through the
    +  /// parser's type/template disambiguation machinery, so without a limit the
    +  /// parser's stack would overflow on deeply nested template arguments. This
    +  /// is used to enforce a maximum nesting depth analogous to -ftemplate-depth
    +  /// (see https://github.com/llvm/llvm-project/issues/224114).
    +  unsigned TemplateArgumentDepth = 0;
    +
       /// RAII class that manages the template parameter depth.
       class TemplateParameterDepthRAII {
         unsigned &Depth;
    diff --git a/clang/lib/Parse/ParseTemplate.cpp b/clang/lib/Parse/ParseTemplate.cpp
    index 1e5aa55338309..5d0949128eb63 100644
    --- a/clang/lib/Parse/ParseTemplate.cpp
    +++ b/clang/lib/Parse/ParseTemplate.cpp
    @@ -14,6 +14,7 @@
     #include "clang/AST/DeclTemplate.h"
     #include "clang/AST/ExprCXX.h"
     #include "clang/Basic/DiagnosticParse.h"
    +#include "clang/Basic/Stack.h"
     #include "clang/Parse/Parser.h"
     #include "clang/Parse/RAIIObjectsForParser.h"
     #include "clang/Sema/DeclSpec.h"
    @@ -22,6 +23,23 @@
     #include "clang/Sema/Scope.h"
     using namespace clang;
     
    +namespace {
    +/// RAII class that manages the template argument nesting depth. Recursing into
    +/// a nested template-id (e.g. the inner `S<...>` of `S<S<...>>`) dips through
    +/// the parser's type/template disambiguation machinery, so deeply nested
    +/// template arguments could overflow the parser's stack. The depth is tracked
    +/// so that `Parser::ParseTemplateArgumentList` can enforce a maximum.
    +class TemplateArgumentDepthRAII {
    +  unsigned &Depth;
    +
    +public:
    +  explicit TemplateArgumentDepthRAII(unsigned &Depth) : Depth(Depth) {
    +    ++Depth;
    +  }
    +  ~TemplateArgumentDepthRAII() { --Depth; }
    +};
    +} // namespace
    +
     unsigned Parser::ReenterTemplateScopes(MultiParseScope &S, Decl *D) {
       return Actions.ActOnReenterTemplateScope(D, [&] {
         S.Enter(Scope::TemplateParamScope);
    @@ -1384,6 +1402,27 @@ bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
     
       ColonProtectionRAIIObject ColonProtection(*this, false);
     
    +  // Nested template-ids (e.g. `S<S<S<...>>>`) recurse through the parser's
    +  // type/template disambiguation machinery, which is deeply recursive. Bound
    +  // the nesting depth to avoid overflowing the parser's stack (see
    +  // https://github.com/llvm/llvm-project/issues/224114). The bounds follow
    +  // -ftemplate-depth when available, and additionally bail out if we're
    +  // genuinely low on stack space (which keeps even huge -ftemplate-depth
    +  // overrides from overflowing the stack).
    +  TemplateArgumentDepthRAII Depth(TemplateArgumentDepth);
    +  bool DepthLimitExceeded =
    +      TemplateArgumentDepth > getLangOpts().InstantiationDepth;
    +  if (DepthLimitExceeded || isStackNearlyExhausted()) {
    +    if (DepthLimitExceeded) {
    +      Diag(OpenLoc, diag::err_template_argument_depth_exceeded)
    +          << getLangOpts().InstantiationDepth;
    +      Diag(OpenLoc, diag::note_template_argument_depth);
    +    } else {
    +      Diag(OpenLoc, diag::err_template_argument_stack_exhausted);
    +    }
    +    return true;
    +  }
    +
       auto RunSignatureHelp = [&] {
         if (!Template)
           return QualType();
    diff --git a/clang/test/Parser/template-argument-depth.cpp b/clang/test/Parser/template-argument-depth.cpp
    new file mode 100644
    index 0000000000000..a8eabf15dcde6
    --- /dev/null
    +++ b/clang/test/Parser/template-argument-depth.cpp
    @@ -0,0 +1,27 @@
    +// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
    +// RUN: %clang_cc1 -fsyntax-only -std=c++20 -ftemplate-depth=64 -DRAISED %s
    +// RUN: not %clang_cc1 -fsyntax-only -std=c++20 -ftemplate-depth=16 -DFAIL %s 2>&1 | FileCheck %s
    +//
    +// Parsing deeply nested template argument lists such as S<S<S<...>>> used to
    +// overflow the parser's stack and crash (see
    +// https://github.com/llvm/llvm-project/issues/224114). The parser now enforces
    +// a maximum template argument nesting depth controlled by -ftemplate-depth.
    +//
    +// CHECK: fatal error: template argument nesting depth exceeded maximum of 16
    +// CHECK-NOT: stack nearly exhausted
    +// expected-no-diagnostics
    +
    +template <typename T> struct S {};
    +
    +// This nesting is well within the default -ftemplate-depth limit.
    +using NoError = S<S<S<S<S<int>>>>>;
    +
    +#ifdef FAIL
    +// Nesting deeper than -ftemplate-depth=16 must be rejected, not crash.
    +using Trigger = S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>;
    +#endif
    +
    +#ifdef RAISED
    +// Raising -ftemplate-depth increases the parser's allowance.
    +using Raised = S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>;
    +#endif
    
    
    ``````

    </details>

    zyn0217 zyn0217 requested changes on Sep 18, 2026 05:56 UTC
    Changes Requested Reviewer

    I think this isn't the behavior what we expect, we do have a stack guard that prevents from deep instantiation and one should investigate why that didn't work for this case.

    daniel-petrovic daniel-petrovic commented on Sep 18, 2026 07:13 UTC
    Author

    I think this isn't the behavior what we expect, we do have a stack guard that prevents from deep instantiation and one should investigate why that didn't work for this case.

    thanks for the hint

    daniel-petrovic daniel-petrovic commented on Sep 18, 2026 12:44 UTC
    Author

    @zyn0217
    according to bt:
    <img width="1870" height="662" alt="bt_parse_template_argument_list_recursion" src="https://github.com/user-attachments/assets/9e818b90-912e-434b-8813-92de5ee243ed" />

    stack guard check was missing on the recursive path in Parser::ParseTemplateArgumentList. Tried to add the (existing) stack guard here. could you please check if this is going in the right direction ? thx

    zwuis zwuis commented on code on Sep 18, 2026 16:45 UTC
    Code Review
    clang/lib/Parse/ParseTemplate.cpp:1

    The runWithSufficientStackSpace covers too much code.

    Currently:

    runWithSufficientStackSpace(... {
      // unrelated code
    
      // code causing stack overflow
    
      // unrelated code
    })
    

    Expected:

    // unrelated code
    
    runWithSufficientStackSpace(... {
      // code causing stack overflow
    })
    
    // unrelated code
    

    zwuis zwuis commented on code on Sep 18, 2026 16:47 UTC
    Code Review
    clang/test/Parser/template-argument-depth.cpp:1

    If I remember correctly we don't add tests for this kind of bugs generally.

    zwuis zwuis commented on Sep 18, 2026 16:49 UTC
    Reviewer

    Looks better to me.

    daniel-petrovic daniel-petrovic commented on code on Sep 18, 2026 17:36 UTC
    Code Review
    clang/lib/Parse/ParseTemplate.cpp:1

    thanks @zwuis . good point. will check it.

    daniel-petrovic daniel-petrovic commented on code on Sep 18, 2026 18:07 UTC
    Code Review
    clang/test/Parser/template-argument-depth.cpp:1

    hmm... you sure about this one ?
    e.g. there is also clang/test/SemaTemplate/stack-exhaustion.cpp (where I copied some comments from)

    what I also found, e.g. clang/test/Parser/gh110231.cpp and clang/test/Parser/dep_template_spec_type.cpp (testing stack overflow)

    daniel-petrovic daniel-petrovic commented on code on Sep 18, 2026 18:45 UTC
    Code Review
    clang/lib/Parse/ParseTemplate.cpp:1

    done

    zwuis zwuis commented on code on Sep 19, 2026 02:30 UTC
    Code Review
    clang/test/Parser/template-argument-depth.cpp:1

    If I remember correctly we don't add tests for this kind of bugs generally.

    Oh I didn't make it clear. I meant bugs that missing runWithSufficientStackSpace in parser, not other kinds of stack overflow.

    daniel-petrovic daniel-petrovic commented on code on Sep 19, 2026 06:10 UTC
    Code Review
    clang/test/Parser/template-argument-depth.cpp:1

    > If I remember correctly we don't add tests for this kind of bugs generally.

    > Oh I didn't make it clear. I meant bugs that missing runWithSufficientStackSpace in parser, not other kinds of stack overflow.

    ah ok, got it. Removed.

    zyn0217 zyn0217 commented on Sep 20, 2026 11:01 UTC
    Reviewer

    I'm reluctant to accept the patch as-is, though the latest approach makes sense.

    I want to question if people would write such paranoid recursive template arguments in real world codebase - the issue was fuzzer generated.

    I'm not saying this is not a bug, I wonder if doing so would also require us to revisit every recursive calls and add guards here and there?

    daniel-petrovic daniel-petrovic commented on Sep 20, 2026 12:46 UTC
    Author

    I'm reluctant to accept the patch as-is, though the latest approach makes sense.

    > I want to question if people would write such paranoid recursive template arguments in real world codebase - the issue was fuzzer generated.

    > I'm not saying this is not a bug, I wonder if doing so would also require us to revisit every recursive calls and add guards here and there?

    Thanks for the feedback.

    IMO Parser should be robust against all syntactically valid inputs, including those from code generators or fuzzers. Currently this specific path lacks the standard stack guard used elsewhere.

    Regarding your concern about scope: I don't believe fixing missing guard that caused this specific issue implies auditing every other recursive call, without evidence that they fail.

    zyn0217 zyn0217 commented on Sep 20, 2026 13:56 UTC
    Contributor

    We already have stack guards protecting instantiation from stack overflows like this, which makes sense given that recursive instantiation chains are common in metaprogramming world.

    However a stack guard also adds overhead to a function call, and with this we have to pay a little more when parsing a template argument and the add-up could be huge when running in a template heavy codebase where the template argument lists are often long rather than deep.

    Indeed this could be seen as a Parser bug, but I think this is more like a trade-off that we don't want pay much for unusual code patterns that cannot be written by human.

    zwuis zwuis commented on Sep 20, 2026 14:01 UTC
    Contributor

    I wonder whether we should reconsider all runWithSufficientStackSpaces in parser if we reject this PR. Most (I didn't check all) runWithSufficientStackSpaces in parser are used to handle code generated by scripts.

    daniel-petrovic daniel-petrovic commented on Sep 20, 2026 15:03 UTC
    Author

    I wonder whether we should reconsider all runWithSufficientStackSpaces in parser if we reject this PR. Most (I didn't check all) runWithSufficientStackSpaces in parser are used to handle code generated by scripts.

    I like this point.
    Having consistency in mind regarding runWithSufficientStackSpace: IMO it should be : all XOR none XOR according to some measure or at least some convention (is there maybe one ?)

    daniel-petrovic daniel-petrovic commented on Sep 20, 2026 17:08 UTC
    Author

    hey guys, just for supporting discussion, I've run some small benchmark with hyperfine between main and patched branch for different template depths (due to time constraints only tested debug build):

    The command used:

     hyperfine --warmup 5 --runs 30 \
        --export-markdown "$TEST_DIR/results_depth_${DEPTH}.md" \
        "$CLANG_ROOT/bin/clang -std=c++20 -fsyntax-only -xc++ $FILE" \
        "$CLANG_ROOT/bin_main/clang -std=c++20 -fsyntax-only -xc++ $FILE"
    
    

    Files look like: template<typename T> struct S {};
    using Trigger = S<S<S<S<S<S<S<S<S<S<int>>>>>>>>>>;

    with different template depths (1 2 4 8 10, 100, 500, 1000)

    The output (times are ms):
    | Template Depth | Build | Mean | Min | Max | Relative |
    | :--- | :--- | :--- | :--- | :--- | :--- |
    | 1 | patch | 24.9 ± 4.4 | 19.6 | 32.8 | 1.17 ± 0.23 |
    | 1 | main | 21.3 ± 1.7 | 19.6 | 25.5 | 1.00 |
    | 2 | patch | 21.4 ± 1.7 | 20.0 | 25.7 | 1.00 |
    | 2 | main | 22.6 ± 2.0 | 20.2 | 25.7 | 1.06 ± 0.13 |
    | 4 | patch | 24.0 ± 1.8 | 19.9 | 26.5 | 1.07 ± 0.11 |
    | 4 | main | 22.5 ± 1.7 | 19.9 | 25.5 | 1.00 |
    | 8 | patch | 24.3 ± 1.8 | 20.9 | 26.8 | 1.10 ± 0.13 |
    | 8 | main | 22.0 ± 2.1 | 20.0 | 26.9 | 1.00 |
    | 10 | patch | 22.0 ± 1.7 | 20.5 | 26.1 | 1.00 |
    | 10 | main | 22.2 ± 2.1 | 20.3 | 27.5 | 1.01 ± 0.13 |
    | 100 | patch | 27.4 ± 2.2 | 25.4 | 33.7 | 1.00 |
    | 100 | main | 28.5 ± 1.9 | 25.4 | 31.8 | 1.04 ± 0.11 |
    | 500 | patch | 53.2 ± 2.2 | 51.0 | 58.7 | 1.02 ± 0.06 |
    | 500 | main | 52.3 ± 2.0 | 50.1 | 56.6 | 1.00 |
    | 1000 | patch | 83.3 ± 3.0 | 80.9 | 90.3 | 1.00 ± 0.04 |
    | 1000 | main | 83.2 ± 2.2 | 80.0 | 87.7 | 1.00 |

    Hope this helps a bit getting some better feeling regarding timing implications.

    AaronBallman AaronBallman commented on Sep 21, 2026 14:25 UTC
    Contributor

    I wonder whether we should reconsider all runWithSufficientStackSpaces in parser if we reject this PR. Most (I didn't check all) runWithSufficientStackSpaces in parser are used to handle code generated by scripts.

    Historically, that interface was more of a last resort. We used to spend a lot of effort ensuring the parser would tail call in situations that could likely hit deep nesting limits. However, that code almost always bit rot (quickly) and so we fell out of the habit because of the maintenance problems. But now that we can use musttail to catch situations where we break tail calls, it might be that we should begin pushing for tail calls more aggressively. But that only catches when Clang cannot tail call, so it may still not be a workable solution.

    I don't have strong opinions about the approach taken here, but it seems like we're punishing the simple case of a single level of templates in order to better diagnose more pathological cases. On the one hand, a diagnostic is always better than a crash. On the other hand, fixing a crash ~nobody hits on real code but slows down common cases seems like a poor tradeoff. CC @erichkeane for other opinions or ideas

    I too am concerned this is the wrong trade-off.

    daniel-petrovic daniel-petrovic commented on Sep 21, 2026 20:52 UTC
    Author

    I don't have strong opinions about the approach taken here, but it seems like we're punishing the simple case of a single level of templates in order to better diagnose more pathological cases.

    Just a short brain-storming:

    As I understand, the current StackHandler.runWithSufficientStackSpace() does not differentiate the recursion level at the moment : the same checks are done for 1 as well as for 1000 levels of recursion.
    What if the StackHandler would track the recursion level and do something like:

    if (recursion_level < threshold_level) [[ likely ]] {
      F(); // just recurse normaly
    } else {
      // the current logic
      // if (isStackNearlyExhausted()) [[ unlikely ]]  {...} else {...}
    }
    

    What we want to achieve with this:

  • up to some small (threshold) number of recursions just recurse normally ( by assuming we will never exceed stack limit on this recursion level)

  • for deeper recursions start doing more checks.

  • different functions may have different thresholds
  • Some rough idea: https://godbolt.org/z/ovvMY46zT

    Of course, measurements would have to confirm benefits of such an approach, if any at all.

    But for the case it's positive, it would cover all scenarios: cheap for small recursion depth and robust otherwise.

    Or formulated differently: Is there a way to make this robust but cheap for the normal usage (zero-cost principle) ?

    Just an idea.

    shafik shafik commented on Sep 22, 2026 03:19 UTC
    Contributor

    I am also concerned this is the wrong trade-off for a case that feels unrealistic.

    zyn0217 zyn0217 commented on Sep 22, 2026 10:21 UTC
    Contributor

    FYI this shows little impact on our compile time tracker: https://llvm-compile-time-tracker.com/compare.php?from=82b9a76acb072b5ee6dc5dd123d30b883fcc4222&to=90119a8e8bec2f685d5cc044ad94b78a755d417b&stat=instructions

    Though we probably need to test template heavy codebases further.

    AaronBallman AaronBallman commented on Sep 22, 2026 15:51 UTC
    Contributor

    > I don't have strong opinions about the approach taken here, but it seems like we're punishing the simple case of a single level of templates in order to better diagnose more pathological cases.

    > Just a short brain-storming:

    > As I understand, the current StackHandler.runWithSufficientStackSpace() does not differentiate the recursion level at the moment : the same checks are done for 1 as well as for 1000 levels of recursion.

    Correct.

    What if the StackHandler would track the recursion level and do something like:

    >
    > if (recursion_level < threshold_level) [[ likely ]] {
    >   F(); // just recurse normaly
    > } else {
    >   // the current logic
    >   // if (isStackNearlyExhausted()) [[ unlikely ]]  {...} else {...}
    > }
    > 

    > What we want to achieve with this:

    > up to some small (threshold) number of recursions just recurse normally ( by assuming we will never exceed stack limit on this recursion level)

    > for deeper recursions start doing more checks.

    > different functions may have different thresholds

    >

    Some rough idea: https://godbolt.org/z/ovvMY46zT

    > Of course, measurements would have to confirm benefits of such an approach, if any at all.

    > But for the case it's positive, it would cover all scenarios: cheap for small recursion depth and robust otherwise.

    > Or formulated differently: Is there a way to make this robust but cheap for the normal usage (zero-cost principle) ?

    > Just an idea.

    That's an interesting idea and might be a workable general solution. I think eliminating the recursion via tail calls is likely still a better approach when we can achieve it though. We have other problems beyond just stack resource limits; for example, the more memory pressure we apply the fewer recursive templates we can instantiate due to running into out of memory scenarios. By reducing stack usage, we also help with that kind of thing. However, I think there's even more low-hanging fruit for that situation like paying attention to stack frame sizes (I've seen some gigantic* stack frames when I was last poking around with this issue). But for the times when we just can't get tail calls to work, having a smarter runWithSufficientStackSpace() is attractive enough to be worth exploring.

    Now, whether we need to do that as part of this PR or not is a whole different question. Given the performance behavior @zyn0217 posted about, maybe it's fine to move forward with this as-is. I think Clang two-stage uses enough templates to be a reasonable proxy for the scenario I was worried we'd be slowing down.

    daniel-petrovic daniel-petrovic commented on Nov 20, 2026 09:13 UTC
    Author

    This PR has been stalled for a while.

    Since there doesn't seem to be a clear consensus on the review direction, I'm not sure how best to proceed. At the same time, I don't want to leave this PR open indefinitely.

    There seem to be concerns about downsides of this rather unrealistic case. On the other hand, the measurements don't seem to support those concerns either.
    I could also revisit the tail-recursion approach. However, I'm not sure whether it's feasible in this particular case (I couldn't find a workable solution the last time I looked into it). I'm happy to invest more time exploring this option, but it would likely result in a considerably larger change.

    I think we should either agree on a direction and move forward, or close this PR.

    I'm willing to invest my time in this, but not to waste it without clear direction.

    Thx

    zyn0217 zyn0217 approved these changes on Nov 20, 2026 09:34 UTC
    Approved Reviewer

    I think I'm fine with it now, thanks for working on it.

    github-actions[bot] github-actions[bot] commented on Nov 20, 2026 10:15 UTC
    Bot

    <!--LLVM BUILDBOT INFORMATION COMMENT-->

    @daniel-petrovic 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!

    llvm-ci llvm-ci commented on Nov 20, 2026 10:51 UTC
    Contributor

    LLVM Buildbot has detected a new failure on builder clang-aarch64-sve2-vla running on linaro-g4-02 while building clang at step 5 "cmake stage 1".

    Full details are available at: https://lab.llvm.org/buildbot/#/builders/198/builds/16780

    <details>
    <summary>Here is the relevant piece of the build log for the reference</summary>

    Step 5 (cmake stage 1) failure: 'cmake -G ...' (failure)
    CMake Error at CMakeLists.txt:2 (cmake_minimum_required):
      CMake 3.31.0 or higher is required.  You are running version 3.28.6
    
    
    -- Configuring incomplete, errors occurred!
    
    

    </details>

    llvm-ci llvm-ci commented on Nov 20, 2026 11:10 UTC
    Contributor

    LLVM Buildbot has detected a new failure on builder clang-aarch64-sve2-vla-2stage running on linaro-g4-02 while building clang at step 5 "cmake stage 1".

    Full details are available at: https://lab.llvm.org/buildbot/#/builders/199/builds/12269

    <details>
    <summary>Here is the relevant piece of the build log for the reference</summary>

    Step 5 (cmake stage 1) failure: 'cmake -G ...' (failure)
    CMake Error at CMakeLists.txt:2 (cmake_minimum_required):
      CMake 3.31.0 or higher is required.  You are running version 3.28.6
    
    
    -- Configuring incomplete, errors occurred!
    
    

    </details>

    AaronBallman AaronBallman commented on Nov 20, 2026 11:16 UTC
    Contributor

    Hey all! I think it was fine to merge this so I'm not asking for a revert, but two points. 1) @zyn0217, when there is more than one reviewer involved in a PR who have expressed concerns with the approach, it's better to wait to land changes to ensure they also feel their concerns are addressed. I'd recommend pinging other reviewers in a case like this. 2) @daniel-petrovic (and others), in general, I think sprinkling runWithSufficientStackSpace in the code base is a band-aid which accrues tech debt for us long-term. I don't think this should be precedent for doing this in more places. It's more palatable on code constructs which users may reasonably hit, but this was fixing a pathological case found by a fuzzer which is less compelling when it comes to accruing this kind of tech debt.

    All this said, I did post-commit review and poked a few other maintainers to quickly give an opinion on the same, and while we had the above concerns to share, none of those concerns are of the "we need to revert this" variety.

    daniel-petrovic daniel-petrovic commented on Nov 20, 2026 11:50 UTC
    Author

    @AaronBallman Thanks for the feedback!

    Regarding:

    in general, I think sprinkling runWithSufficientStackSpace in the code base is a band-aid which accrues tech debt for us long-term

    I think we all agree on this (myself included in the meanwhile). I actually tried using it as a first-aid in a couple of other places too, though thanks to @zyn0217 's review hints, I was able to find better alternatives there.

    In this case, I couldn't find a simple alternative, and the argument that this scenario is too unrealistic to warrant a fix sounds completely reasonable to me. Reverting this is definitely an option.

    I mainly commented today to either move this stalled PR forward or close it out, to help reduce the PR backlog.

    Reviewers
    Assignees
    daniel-petrovic daniel-petrovic
    Labels
    risk: low confidence: 75% 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: 23.2% (LOW) · Higher = larger blast radius
    23.2%
    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: 75% · Lower = rushed or shallow review
    75%
    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: 5.8% · Safe to merge
    5.8%