https://github.com/timon-ul updated 
https://github.com/llvm/llvm-project/pull/177273

>From ebfa26a48524782eea663d36f155b64b2dde3161 Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Sat, 17 Jan 2026 03:16:06 +0100
Subject: [PATCH 01/18] First step towards indexing template instantiations

---
 .../clangd/index/SymbolCollector.cpp          | 13 ++++++--
 .../clangd/unittests/XRefsTests.cpp           | 20 +++++++++++
 clang/include/clang/Index/IndexingOptions.h   |  2 +-
 clang/lib/Index/IndexDecl.cpp                 | 33 ++++++++++++++++++-
 clang/lib/Index/IndexTypeSourceInfo.cpp       |  9 +++++
 clang/lib/Index/IndexingContext.cpp           |  4 +--
 6 files changed, 74 insertions(+), 7 deletions(-)

diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 388aa0a5340755..41a1b3662789a3 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -589,6 +589,12 @@ bool SymbolCollector::handleDeclOccurrence(
   assert(ASTCtx && PP && HeaderFileURIs);
   assert(CompletionAllocator && CompletionTUInfo);
   assert(ASTNode.OrigD);
+  const NamedDecl *NOD = dyn_cast<NamedDecl>(ASTNode.OrigD);
+  std::string NameOD = "";
+  if (NOD){
+    NameOD = printName(*ASTCtx, *NOD);
+    NameOD += printTemplateSpecializationArgs(*NOD);
+  }
   // Indexing API puts canonical decl into D, which might not have a valid
   // source location for implicit/built-in decls. Fallback to original decl in
   // such cases.
@@ -882,9 +888,12 @@ void SymbolCollector::processRelations(
     //       in the index and find nothing, but that's a situation they
     //       probably need to handle for other reasons anyways.
     // We currently do (B) because it's simpler.
-    if (*RKind == RelationKind::BaseOf)
+    if (*RKind == RelationKind::BaseOf) {
+      std::string SubjectName = printName(*ASTCtx, ND) + 
printTemplateSpecializationArgs(ND);
+      const auto *Sym = Symbols.find(ObjectID);
+      std::string ObjectName = (Sym->Scope + Sym->Name + 
Sym->TemplateSpecializationArgs).str();
       this->Relations.insert({ID, *RKind, ObjectID});
-    else if (*RKind == RelationKind::OverriddenBy)
+    } else if (*RKind == RelationKind::OverriddenBy)
       this->Relations.insert({ObjectID, *RKind, ID});
   }
 }
diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 9d1a34f23955c1..67adbad83ed0df 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2094,6 +2094,26 @@ TEST(FindImplementations, InheritanceObjC) {
                                        Code.range("protocolDef"))));
 }
 
+TEST(FindImplementations, InheritanceRecursive) {
+  Annotations Main(R"cpp(
+    template <typename... T>
+    struct Inherit : T... {};
+
+    struct Al$Alpha^pha {};
+
+    struct $Impl1[[impl]]: Inherit<Alpha> {};
+  )cpp");
+
+  TestTU TU;
+  TU.Code = std::string(Main.code());
+  auto AST = TU.build();
+  auto Index = TU.index();
+
+  EXPECT_THAT(
+      findImplementations(AST, Main.point("Alpha"), Index.get()),
+      ElementsAre(sym("impl", Main.range("Impl1"), Main.range("Impl1"))));
+}
+
 TEST(FindImplementations, CaptureDefinition) {
   llvm::StringRef Test = R"cpp(
     struct Base {
diff --git a/clang/include/clang/Index/IndexingOptions.h 
b/clang/include/clang/Index/IndexingOptions.h
index c670797e9fa603..1094ec46dc9af6 100644
--- a/clang/include/clang/Index/IndexingOptions.h
+++ b/clang/include/clang/Index/IndexingOptions.h
@@ -27,7 +27,7 @@ struct IndexingOptions {
   SystemSymbolFilterKind SystemSymbolFilter =
       SystemSymbolFilterKind::DeclarationsOnly;
   bool IndexFunctionLocals = false;
-  bool IndexImplicitInstantiation = false;
+  bool IndexImplicitInstantiation = true;
   bool IndexMacros = true;
   // Whether to index macro definitions in the Preprocessor when preprocessor
   // callback is not available (e.g. after parsing has finished). Note that
diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index 8bcad4739c788b..c27080bd64a43e 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/DeclVisitor.h"
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/IndexSymbol.h"
+#include "llvm/Support/Casting.h"
 
 using namespace clang;
 using namespace index;
@@ -735,7 +736,37 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
       indexTemplateParameters(Params, Parent);
     }
 
-    return Visit(Parent);
+    bool shouldContinue = Visit(Parent);
+    if (!shouldContinue)
+      return false;
+
+    // TODO: cleanup maybe, so far copy paste from
+    // RecursiveASTVisitor::TraverseTemplateInstantiation, we have technically
+    // `shouldIndexImplicitInstantiation()` available here, but the logic is
+    // different and I am confused.
+    if (const auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(D))
+      for (auto *SD : CTD->specializations())
+        for (auto *RD : SD->redecls()) {
+          assert(!cast<CXXRecordDecl>(RD)->isInjectedClassName());
+          switch (cast<ClassTemplateSpecializationDecl>(RD)
+                      ->getSpecializationKind()) {
+          // Visit the implicit instantiations with the requested pattern.
+          case TSK_Undeclared:
+          case TSK_ImplicitInstantiation:
+            Visit(RD);
+            break;
+
+          // We don't need to do anything on an explicit instantiation
+          // or explicit specialization because there will be an explicit
+          // node for it elsewhere.
+          case TSK_ExplicitInstantiationDeclaration:
+          case TSK_ExplicitInstantiationDefinition:
+          case TSK_ExplicitSpecialization:
+            break;
+          }
+        }
+
+    return true;
   }
 
   bool VisitConceptDecl(const ConceptDecl *D) {
diff --git a/clang/lib/Index/IndexTypeSourceInfo.cpp 
b/clang/lib/Index/IndexTypeSourceInfo.cpp
index e704505a116783..6047014c372b16 100644
--- a/clang/lib/Index/IndexTypeSourceInfo.cpp
+++ b/clang/lib/Index/IndexTypeSourceInfo.cpp
@@ -10,6 +10,7 @@
 #include "clang/AST/ASTConcept.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/TypeBase.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Sema/HeuristicResolver.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -199,6 +200,14 @@ class TypeIndexer : public 
RecursiveASTVisitor<TypeIndexer> {
     return true;
   }
 
+  // bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
+  //                                           bool TraverseQualifier) {
+  //   auto Type = TL.getAs<TemplateSpecializationTypeLoc>();
+  //   if (!Type.isNull())
+  //     TraverseTemplateSpecializationTypeLoc(Type, TraverseQualifier);
+  //   return true;
+  // }
+
   bool 
VisitDeducedTemplateSpecializationTypeLoc(DeducedTemplateSpecializationTypeLoc 
TL) {
     auto *T = TL.getTypePtr();
     if (!T)
diff --git a/clang/lib/Index/IndexingContext.cpp 
b/clang/lib/Index/IndexingContext.cpp
index bdd6c5acf1d34f..c6843cf46cf8e9 100644
--- a/clang/lib/Index/IndexingContext.cpp
+++ b/clang/lib/Index/IndexingContext.cpp
@@ -402,9 +402,7 @@ bool IndexingContext::handleDeclOccurrence(const Decl *D, 
SourceLocation Loc,
   if (!OrigD)
     OrigD = D;
 
-  if (isTemplateImplicitInstantiation(D)) {
-    if (!IsRef)
-      return true;
+  if (isTemplateImplicitInstantiation(D) && IsRef) {
     D = adjustTemplateImplicitInstantiation(D);
     if (!D)
       return true;

>From 7c2fc82feef0fb943e6efc066b41cc38697203cf Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Sat, 17 Jan 2026 03:20:22 +0100
Subject: [PATCH 02/18] New methods for visiting SubstTemplateType

---
 clang/lib/Index/IndexTypeSourceInfo.cpp | 22 +++++++++++++++-------
 1 file changed, 15 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Index/IndexTypeSourceInfo.cpp 
b/clang/lib/Index/IndexTypeSourceInfo.cpp
index 6047014c372b16..a879fd027fac4e 100644
--- a/clang/lib/Index/IndexTypeSourceInfo.cpp
+++ b/clang/lib/Index/IndexTypeSourceInfo.cpp
@@ -200,13 +200,21 @@ class TypeIndexer : public 
RecursiveASTVisitor<TypeIndexer> {
     return true;
   }
 
-  // bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
-  //                                           bool TraverseQualifier) {
-  //   auto Type = TL.getAs<TemplateSpecializationTypeLoc>();
-  //   if (!Type.isNull())
-  //     TraverseTemplateSpecializationTypeLoc(Type, TraverseQualifier);
-  //   return true;
-  // }
+  bool VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL) {
+    auto QT = TL.getTypePtr()->getReplacementType();
+    auto *T = QT->getAsNonAliasTemplateSpecializationType();
+    if (!T)
+      return true;
+    HandleTemplateSpecializationTypeLoc(
+        T->getTemplateName(), TL.getTemplateNameLoc(), T->getAsCXXRecordDecl(),
+        T->isTypeAlias());
+    return true;
+  }
+
+  bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
+                                            bool TraverseQualifier) {
+    return true;
+  }
 
   bool 
VisitDeducedTemplateSpecializationTypeLoc(DeducedTemplateSpecializationTypeLoc 
TL) {
     auto *T = TL.getTypePtr();

>From ae78c8756e5e688bc19d84edef1de5f66a81ef15 Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Wed, 21 Jan 2026 23:20:57 +0100
Subject: [PATCH 03/18] Implemented template inheritance handling

---
 .../clangd/index/SymbolCollector.cpp          | 22 ++++++-------
 .../clangd/index/SymbolCollector.h            |  2 +-
 .../clangd/unittests/XRefsTests.cpp           | 32 ++++++++++++++----
 clang/include/clang/Index/IndexingOptions.h   |  2 +-
 clang/lib/Index/IndexDecl.cpp                 | 33 +++++++------------
 clang/lib/Index/IndexTypeSourceInfo.cpp       | 19 +++++------
 6 files changed, 59 insertions(+), 51 deletions(-)

diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 41a1b3662789a3..f981b4054d4ef2 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -589,12 +589,7 @@ bool SymbolCollector::handleDeclOccurrence(
   assert(ASTCtx && PP && HeaderFileURIs);
   assert(CompletionAllocator && CompletionTUInfo);
   assert(ASTNode.OrigD);
-  const NamedDecl *NOD = dyn_cast<NamedDecl>(ASTNode.OrigD);
-  std::string NameOD = "";
-  if (NOD){
-    NameOD = printName(*ASTCtx, *NOD);
-    NameOD += printTemplateSpecializationArgs(*NOD);
-  }
+
   // Indexing API puts canonical decl into D, which might not have a valid
   // source location for implicit/built-in decls. Fallback to original decl in
   // such cases.
@@ -665,7 +660,7 @@ bool SymbolCollector::handleDeclOccurrence(
   // refs, because the indexing code only populates relations for specific
   // occurrences. For example, RelationBaseOf is only populated for the
   // occurrence inside the base-specifier.
-  processRelations(*ND, ID, Relations);
+  processRelations(ID, *ASTNode.OrigD, Relations);
 
   bool CollectRef = static_cast<bool>(Opts.RefFilter & toRefKind(Roles));
   // Unlike other fields, e.g. Symbols (which use spelling locations), we use
@@ -867,7 +862,7 @@ bool SymbolCollector::handleMacroOccurrence(const 
IdentifierInfo *Name,
 }
 
 void SymbolCollector::processRelations(
-    const NamedDecl &ND, const SymbolID &ID,
+    const SymbolID &ID, const Decl &OrigD,
     ArrayRef<index::SymbolRelation> Relations) {
   for (const auto &R : Relations) {
     auto RKind = indexableRelation(R);
@@ -889,10 +884,15 @@ void SymbolCollector::processRelations(
     //       probably need to handle for other reasons anyways.
     // We currently do (B) because it's simpler.
     if (*RKind == RelationKind::BaseOf) {
-      std::string SubjectName = printName(*ASTCtx, ND) + 
printTemplateSpecializationArgs(ND);
-      const auto *Sym = Symbols.find(ObjectID);
-      std::string ObjectName = (Sym->Scope + Sym->Name + 
Sym->TemplateSpecializationArgs).str();
       this->Relations.insert({ID, *RKind, ObjectID});
+      // If the Subject is a template, we also want a relation to the
+      // template instantiation (OrigD) to record inheritance chains.
+      if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(&OrigD);
+          CTSD && !CTSD->isExplicitSpecialization()) {
+        auto OrigID = getSymbolIDCached(&OrigD);
+        if (OrigID)
+          this->Relations.insert({OrigID, *RKind, ObjectID});
+      }
     } else if (*RKind == RelationKind::OverriddenBy)
       this->Relations.insert({ObjectID, *RKind, ID});
   }
diff --git a/clang-tools-extra/clangd/index/SymbolCollector.h 
b/clang-tools-extra/clangd/index/SymbolCollector.h
index 8239aa7020c1ec..ee495036a2436c 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.h
+++ b/clang-tools-extra/clangd/index/SymbolCollector.h
@@ -169,7 +169,7 @@ class SymbolCollector : public index::IndexDataConsumer {
                                bool IsMainFileSymbol);
   void addDefinition(const NamedDecl &, const Symbol &DeclSymbol,
                      bool SkipDocCheck);
-  void processRelations(const NamedDecl &ND, const SymbolID &ID,
+  void processRelations(const SymbolID &ID, const Decl &OrigD,
                         ArrayRef<index::SymbolRelation> Relations);
 
   std::optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 67adbad83ed0df..35aba8902b8359 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2094,14 +2094,27 @@ TEST(FindImplementations, InheritanceObjC) {
                                        Code.range("protocolDef"))));
 }
 
-TEST(FindImplementations, InheritanceRecursive) {
+TEST(FindImplementations, InheritanceTemplate) {
   Annotations Main(R"cpp(
+    class Fi$First^rst {};
+
+    class Sec$Second^ond {};
+
+    class Th$Third^ird {};
+
     template <typename... T>
-    struct Inherit : T... {};
+    struct $Third[[Inherit]] : T... {};
+
+    template struct $First[[Inherit]]<First>;
+
+    template<>
+    struct $Second[[Inherit]]<Second> : Second {};
 
-    struct Al$Alpha^pha {};
+    class $First[[Battler]] : Inherit<First> {};
 
-    struct $Impl1[[impl]]: Inherit<Alpha> {};
+    class $Second[[Beatrice]] : Inherit<Second> {};
+
+    class $Third[[Maria]] : Inherit<Third> {};
   )cpp");
 
   TestTU TU;
@@ -2109,9 +2122,14 @@ TEST(FindImplementations, InheritanceRecursive) {
   auto AST = TU.build();
   auto Index = TU.index();
 
-  EXPECT_THAT(
-      findImplementations(AST, Main.point("Alpha"), Index.get()),
-      ElementsAre(sym("impl", Main.range("Impl1"), Main.range("Impl1"))));
+  EXPECT_THAT(findImplementations(AST, Main.point("First"), Index.get()),
+              UnorderedPointwise(declRange(), Main.ranges("First")));
+
+  EXPECT_THAT(findImplementations(AST, Main.point("Second"), Index.get()),
+              UnorderedPointwise(declRange(), Main.ranges("Second")));
+
+  EXPECT_THAT(findImplementations(AST, Main.point("Third"), Index.get()),
+              UnorderedPointwise(declRange(), Main.ranges("Third")));
 }
 
 TEST(FindImplementations, CaptureDefinition) {
diff --git a/clang/include/clang/Index/IndexingOptions.h 
b/clang/include/clang/Index/IndexingOptions.h
index 1094ec46dc9af6..c670797e9fa603 100644
--- a/clang/include/clang/Index/IndexingOptions.h
+++ b/clang/include/clang/Index/IndexingOptions.h
@@ -27,7 +27,7 @@ struct IndexingOptions {
   SystemSymbolFilterKind SystemSymbolFilter =
       SystemSymbolFilterKind::DeclarationsOnly;
   bool IndexFunctionLocals = false;
-  bool IndexImplicitInstantiation = true;
+  bool IndexImplicitInstantiation = false;
   bool IndexMacros = true;
   // Whether to index macro definitions in the Preprocessor when preprocessor
   // callback is not available (e.g. after parsing has finished). Note that
diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index c27080bd64a43e..ed81b44fcf94d0 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -740,30 +740,21 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
     if (!shouldContinue)
       return false;
 
-    // TODO: cleanup maybe, so far copy paste from
-    // RecursiveASTVisitor::TraverseTemplateInstantiation, we have technically
-    // `shouldIndexImplicitInstantiation()` available here, but the logic is
-    // different and I am confused.
+    // Only check instantiation if D is canonical to prevent infinite cycling
+    if (D != D->getCanonicalDecl())
+      return true;
+
     if (const auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(D))
       for (auto *SD : CTD->specializations())
         for (auto *RD : SD->redecls()) {
-          assert(!cast<CXXRecordDecl>(RD)->isInjectedClassName());
-          switch (cast<ClassTemplateSpecializationDecl>(RD)
-                      ->getSpecializationKind()) {
-          // Visit the implicit instantiations with the requested pattern.
-          case TSK_Undeclared:
-          case TSK_ImplicitInstantiation:
-            Visit(RD);
-            break;
-
-          // We don't need to do anything on an explicit instantiation
-          // or explicit specialization because there will be an explicit
-          // node for it elsewhere.
-          case TSK_ExplicitInstantiationDeclaration:
-          case TSK_ExplicitInstantiationDefinition:
-          case TSK_ExplicitSpecialization:
-            break;
-          }
+          auto *CTSD = cast<ClassTemplateSpecializationDecl>(RD);
+          // For now we are only interested in instantiations with inheritance.
+          if (!CTSD->hasDefinition() || CTSD->bases().empty())
+            continue;
+          // Explicit specialization is handled elsewhere
+          if (CTSD->isExplicitSpecialization())
+            continue;
+          Visit(RD);
         }
 
     return true;
diff --git a/clang/lib/Index/IndexTypeSourceInfo.cpp 
b/clang/lib/Index/IndexTypeSourceInfo.cpp
index a879fd027fac4e..4d35a71a25a820 100644
--- a/clang/lib/Index/IndexTypeSourceInfo.cpp
+++ b/clang/lib/Index/IndexTypeSourceInfo.cpp
@@ -200,19 +200,18 @@ class TypeIndexer : public 
RecursiveASTVisitor<TypeIndexer> {
     return true;
   }
 
-  bool VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL) {
-    auto QT = TL.getTypePtr()->getReplacementType();
-    auto *T = QT->getAsNonAliasTemplateSpecializationType();
+  bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
+                                            bool TraverseQualifier) {
+    const auto *T = TL.getTypePtr();
     if (!T)
       return true;
-    HandleTemplateSpecializationTypeLoc(
-        T->getTemplateName(), TL.getTemplateNameLoc(), T->getAsCXXRecordDecl(),
-        T->isTypeAlias());
-    return true;
-  }
+    auto QT = T->getReplacementType();
+    if (QT.isNull())
+      return true;
+
+    IndexCtx.handleReference(QT->getAsCXXRecordDecl(), TL.getNameLoc(), Parent,
+                             ParentDC, SymbolRoleSet(), Relations);
 
-  bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
-                                            bool TraverseQualifier) {
     return true;
   }
 

>From 6643156f26f3cabcf1267592f0279869d29fb7ed Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Thu, 22 Jan 2026 00:28:59 +0100
Subject: [PATCH 04/18] Preventing refs for implicit instantiations

---
 clang-tools-extra/clangd/index/SymbolCollector.cpp | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index f981b4054d4ef2..470a648d29c377 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -663,6 +663,13 @@ bool SymbolCollector::handleDeclOccurrence(
   processRelations(ID, *ASTNode.OrigD, Relations);
 
   bool CollectRef = static_cast<bool>(Opts.RefFilter & toRefKind(Roles));
+  // For now we only want the bare minimum of information for a class
+  // instantiation such that we have symbols for the `BaseOf` relation.
+  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D);
+      CTSD && CTSD->hasDefinition() && !CTSD->bases().empty() &&
+      !CTSD->isExplicitSpecialization()) {
+    CollectRef = false;
+  }
   // Unlike other fields, e.g. Symbols (which use spelling locations), we use
   // file locations for references (as it aligns the behavior of clangd's
   // AST-based xref).

>From 569f15445da1b3e838cba81b6acca200e2723054 Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Thu, 22 Jan 2026 11:05:50 +0100
Subject: [PATCH 05/18] More careful handling of casts

---
 clang/lib/Index/IndexDecl.cpp           | 5 ++---
 clang/lib/Index/IndexTypeSourceInfo.cpp | 9 +++++----
 2 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index ed81b44fcf94d0..6884225e9c206a 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -14,7 +14,6 @@
 #include "clang/AST/DeclVisitor.h"
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/IndexSymbol.h"
-#include "llvm/Support/Casting.h"
 
 using namespace clang;
 using namespace index;
@@ -747,9 +746,9 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
     if (const auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(D))
       for (auto *SD : CTD->specializations())
         for (auto *RD : SD->redecls()) {
-          auto *CTSD = cast<ClassTemplateSpecializationDecl>(RD);
+          auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
           // For now we are only interested in instantiations with inheritance.
-          if (!CTSD->hasDefinition() || CTSD->bases().empty())
+          if (!CTSD || !CTSD->hasDefinition() || CTSD->bases().empty())
             continue;
           // Explicit specialization is handled elsewhere
           if (CTSD->isExplicitSpecialization())
diff --git a/clang/lib/Index/IndexTypeSourceInfo.cpp 
b/clang/lib/Index/IndexTypeSourceInfo.cpp
index 4d35a71a25a820..a70a150f02b85c 100644
--- a/clang/lib/Index/IndexTypeSourceInfo.cpp
+++ b/clang/lib/Index/IndexTypeSourceInfo.cpp
@@ -208,11 +208,12 @@ class TypeIndexer : public 
RecursiveASTVisitor<TypeIndexer> {
     auto QT = T->getReplacementType();
     if (QT.isNull())
       return true;
+    auto *CXXRD = QT->getAsCXXRecordDecl();
+    if (!CXXRD)
+      return true;
 
-    IndexCtx.handleReference(QT->getAsCXXRecordDecl(), TL.getNameLoc(), Parent,
-                             ParentDC, SymbolRoleSet(), Relations);
-
-    return true;
+    return IndexCtx.handleReference(CXXRD, TL.getNameLoc(), Parent, ParentDC,
+                                    SymbolRoleSet(), Relations);
   }
 
   bool 
VisitDeducedTemplateSpecializationTypeLoc(DeducedTemplateSpecializationTypeLoc 
TL) {

>From 4faf56eb653e20f1c33e19d3cbdc721f4735181a Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Wed, 28 Jan 2026 18:06:45 +0100
Subject: [PATCH 06/18] Fixed InheritanceRecursion test for newly found
 instantiations

---
 clang-tools-extra/clangd/unittests/XRefsTests.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 35aba8902b8359..cd97a7c5d3688f 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2043,12 +2043,12 @@ TEST(FindImplementations, InheritanceRecursion) {
     };
 
     template <int I>
-    struct [[Even]] : Odd<I - 1> {};
+    struct [[[[Even]]]] : Odd<I - 1> {};
 
     template <int I>
     struct [[Odd]] : Even<I - 1> {};
 
-    constexpr bool Answer = Even<42>::value;
+    constexpr bool Answer = Even<2>::value;
   )cpp";
 
   Annotations Code(Test);

>From dc8478eef633900170ddc537fffac4213fffa71d Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Fri, 6 Mar 2026 14:30:20 +0100
Subject: [PATCH 07/18] Hide implicit template indexing behind indexing option

---
 clang-tools-extra/clangd/XRefs.cpp                          | 1 +
 clang-tools-extra/clangd/index/FileIndex.cpp                | 1 +
 clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp | 1 +
 clang/lib/Index/IndexDecl.cpp                               | 3 +++
 4 files changed, 6 insertions(+)

diff --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index e68e6a08adce5d..3014a7f1b587ad 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -1241,6 +1241,7 @@ findRefs(const llvm::ArrayRef<const NamedDecl *> 
TargetDecls, ParsedAST &AST,
   IndexOpts.SystemSymbolFilter =
       index::IndexingOptions::SystemSymbolFilterKind::All;
   IndexOpts.IndexFunctionLocals = true;
+  IndexOpts.IndexImplicitInstantiation = true;
   IndexOpts.IndexParametersInDeclarations = true;
   IndexOpts.IndexTemplateParameters = true;
   indexTopLevelDecls(AST.getASTContext(), AST.getPreprocessor(),
diff --git a/clang-tools-extra/clangd/index/FileIndex.cpp 
b/clang-tools-extra/clangd/index/FileIndex.cpp
index 2e005bfe3537e6..4234886ce8eaf5 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -65,6 +65,7 @@ SlabTuple indexSymbols(ASTContext &AST, Preprocessor &PP,
       index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly;
   // We index function-local classes and its member functions only.
   IndexOpts.IndexFunctionLocals = true;
+  IndexOpts.IndexImplicitInstantiation = true;
   if (IsIndexMainAST) {
     // We only collect refs when indexing main AST.
     CollectorOpts.RefFilter = RefKind::All;
diff --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp 
b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
index 00157a5d81abec..e266e5a9b84859 100644
--- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -310,6 +310,7 @@ class SymbolIndexActionFactory : public 
tooling::FrontendActionFactory {
     IndexOpts.SystemSymbolFilter =
         index::IndexingOptions::SystemSymbolFilterKind::All;
     IndexOpts.IndexFunctionLocals = true;
+    IndexOpts.IndexImplicitInstantiation = true;
     std::shared_ptr<include_cleaner::PragmaIncludes> PI =
         std::make_shared<include_cleaner::PragmaIncludes>();
     COpts.PragmaIncludes = PI.get();
diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index 6884225e9c206a..db64149b884245 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -739,6 +739,9 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
     if (!shouldContinue)
       return false;
 
+    if (!IndexCtx.shouldIndexImplicitInstantiation())
+      return true;
+
     // Only check instantiation if D is canonical to prevent infinite cycling
     if (D != D->getCanonicalDecl())
       return true;

>From 7910e1d0b09086b3411969675ed6ff7265b8e94c Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Mon, 9 Mar 2026 19:46:32 +0100
Subject: [PATCH 08/18] Adjusted behaviour for SymbolCollectorTest.Tempalte

---
 clang-tools-extra/clangd/AST.cpp                   |  7 +++++++
 clang-tools-extra/clangd/AST.h                     |  5 +++++
 clang-tools-extra/clangd/CodeComplete.cpp          |  4 ++--
 .../clangd/unittests/SymbolCollectorTests.cpp      | 14 ++++++++++----
 4 files changed, 24 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index acaca1cdc23816..13262381d0c0ce 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -180,6 +180,13 @@ std::string getQualification(ASTContext &Context,
 
 } // namespace
 
+bool isTemplateInstantiation(const NamedDecl *D) {
+  return isTemplateSpecializationKind(D,
+                                      TSK_ExplicitInstantiationDeclaration) ||
+         isTemplateSpecializationKind(D, TSK_ExplicitInstantiationDefinition) 
||
+         isTemplateSpecializationKind(D, TSK_ImplicitInstantiation);
+}
+
 bool isImplicitTemplateInstantiation(const NamedDecl *D) {
   return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation);
 }
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index ab03b117771d7f..8a8ba9148acfe1 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -141,6 +141,11 @@ std::string printType(const QualType QT, const DeclContext 
&CurContext,
                       llvm::StringRef Placeholder = "",
                       bool FullyQualify = false);
 
+/// Indicates if \p D is a template instantiation, implicit or explicit e.g.
+///     template <class T> struct vector {};
+///     template <> struct vector<bool>; // is an explicit instantiation.
+///     vector<int> v; // 'vector<int>' is an implicit instantiation.
+bool isTemplateInstantiation(const NamedDecl *D);
 /// Indicates if \p D is a template instantiation implicitly generated by the
 /// compiler, e.g.
 ///     template <class T> struct vector {};
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 87c7fa15101f73..86434931773da3 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -2427,8 +2427,8 @@ bool isIndexedForCodeCompletion(const NamedDecl &ND, 
ASTContext &ASTCtx) {
     return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
   };
   // We only complete symbol's name, which is the same as the name of the
-  // *primary* template in case of template specializations.
-  if (isExplicitTemplateSpecialization(&ND))
+  // *primary* template in case of template specializations or instantiation.
+  if (isExplicitTemplateSpecialization(&ND) || isTemplateInstantiation(&ND))
     return false;
 
   // Category decls are not useful on their own outside the interface or
diff --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp 
b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
index e266e5a9b84859..b23dbe4761cb06 100644
--- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -486,13 +486,11 @@ TEST_F(SymbolCollectorTest, FileLocal) {
 
 TEST_F(SymbolCollectorTest, Template) {
   Annotations Header(R"(
-    // Primary template and explicit specialization are indexed, instantiation
-    // is not.
     template <class T, class U> struct [[Tmpl]] {T $xdecl[[x]] = 0;};
     template <> struct $specdecl[[Tmpl]]<int, bool> {};
     template <class U> struct $partspecdecl[[Tmpl]]<bool, U> {};
-    extern template struct Tmpl<float, bool>;
-    template struct Tmpl<double, bool>;
+    extern template struct $extinst[[Tmpl]]<float, bool>;
+    template struct $inst[[Tmpl]]<double, bool>;
   )");
   runSymbolCollector(Header.code(), /*Main=*/"");
   EXPECT_THAT(Symbols,
@@ -503,7 +501,15 @@ TEST_F(SymbolCollectorTest, Template) {
                         forCodeCompletion(false)),
                   AllOf(qName("Tmpl"), declRange(Header.range("partspecdecl")),
                         forCodeCompletion(false)),
+                  AllOf(qName("Tmpl"), declRange(Header.range("extinst")),
+                        forCodeCompletion(false)),
+                  AllOf(qName("Tmpl"), declRange(Header.range("inst")),
+                        forCodeCompletion(false)),
                   AllOf(qName("Tmpl::x"), declRange(Header.range("xdecl")),
+                        forCodeCompletion(false)),
+                  AllOf(qName("Tmpl<float, bool>::x"), 
declRange(Header.range("xdecl")),
+                        forCodeCompletion(false)),
+                  AllOf(qName("Tmpl<double, bool>::x"), 
declRange(Header.range("xdecl")),
                         forCodeCompletion(false))));
 }
 

>From 2fbc3753a1dc426764eaf87a073c9d7e4a26171e Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Mon, 9 Mar 2026 21:46:05 +0100
Subject: [PATCH 09/18] Prevent doc creation for implicit instantiations

---
 clang-tools-extra/clangd/index/SymbolCollector.cpp | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 470a648d29c377..8d7550cddde7b0 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -1106,6 +1106,11 @@ const Symbol *SymbolCollector::addDeclaration(const 
NamedDecl &ND, SymbolID ID,
 
   S.Tags = computeSymbolTags(ND);
 
+  if (isImplicitTemplateInstantiation(&ND)) {
+    Symbols.insert(S);
+    return Symbols.find(S.ID);
+  }
+
   // Add completion info.
   // FIXME: we may want to choose a different redecl, or combine from several.
   assert(ASTCtx && PP && "ASTContext and Preprocessor must be set.");

>From f6294d175706a0b290b91f8422f47dcf06a3aacc Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Tue, 10 Mar 2026 18:44:43 +0100
Subject: [PATCH 10/18] Added test for libIndex new behaviour

---
 clang/unittests/Index/IndexTests.cpp | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/clang/unittests/Index/IndexTests.cpp 
b/clang/unittests/Index/IndexTests.cpp
index e20764e4fb9d9a..cc86c4424a17f6 100644
--- a/clang/unittests/Index/IndexTests.cpp
+++ b/clang/unittests/Index/IndexTests.cpp
@@ -20,6 +20,7 @@
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Index/IndexingOptions.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Tooling/Tooling.h"
 #include "clang/UnifiedSymbolResolution/USRGeneration.h"
@@ -264,6 +265,28 @@ TEST(IndexTest, IndexExplicitTemplateInstantiation) {
                                    DeclAt(Position(3, 12))))));
 }
 
+TEST(IndexTest, IndexImplicitTemplateInstantiation) {
+  std::string Code = R"cpp(
+    struct Seagulls {};
+    struct Cry {};
+
+    template <typename... T>
+    struct The : T... {};
+
+    struct When : The<Seagulls,Cry> {};
+  )cpp";
+  auto Index = std::make_shared<Indexer>();
+  IndexingOptions Opts;
+  Opts.IndexImplicitInstantiation = true;
+  tooling::runToolOnCode(std::make_unique<IndexAction>(Index, Opts), Code);
+  EXPECT_THAT(
+      Index->Symbols,
+      AllOf(Contains(AllOf(QName("Seagulls"), WrittenAt(Position(6, 18)),
+                           DeclAt(Position(2, 12)))),
+            Contains(AllOf(QName("Cry"), WrittenAt(Position(6, 18)),
+                           DeclAt(Position(3, 12))))));
+}
+
 TEST(IndexTest, IndexTemplateInstantiationPartial) {
   std::string Code = R"cpp(
     template <typename T1, typename T2>

>From b9c12a02d59070ea4d5203e43402b0d9fa13997d Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Tue, 10 Mar 2026 19:52:30 +0100
Subject: [PATCH 11/18] Formatted test

---
 .../clangd/unittests/SymbolCollectorTests.cpp | 37 ++++++++++---------
 1 file changed, 19 insertions(+), 18 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp 
b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
index b23dbe4761cb06..bf3d62d3fd2916 100644
--- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -493,24 +493,25 @@ TEST_F(SymbolCollectorTest, Template) {
     template struct $inst[[Tmpl]]<double, bool>;
   )");
   runSymbolCollector(Header.code(), /*Main=*/"");
-  EXPECT_THAT(Symbols,
-              UnorderedElementsAre(
-                  AllOf(qName("Tmpl"), declRange(Header.range()),
-                        forCodeCompletion(true)),
-                  AllOf(qName("Tmpl"), declRange(Header.range("specdecl")),
-                        forCodeCompletion(false)),
-                  AllOf(qName("Tmpl"), declRange(Header.range("partspecdecl")),
-                        forCodeCompletion(false)),
-                  AllOf(qName("Tmpl"), declRange(Header.range("extinst")),
-                        forCodeCompletion(false)),
-                  AllOf(qName("Tmpl"), declRange(Header.range("inst")),
-                        forCodeCompletion(false)),
-                  AllOf(qName("Tmpl::x"), declRange(Header.range("xdecl")),
-                        forCodeCompletion(false)),
-                  AllOf(qName("Tmpl<float, bool>::x"), 
declRange(Header.range("xdecl")),
-                        forCodeCompletion(false)),
-                  AllOf(qName("Tmpl<double, bool>::x"), 
declRange(Header.range("xdecl")),
-                        forCodeCompletion(false))));
+  EXPECT_THAT(
+      Symbols,
+      UnorderedElementsAre(
+          AllOf(qName("Tmpl"), declRange(Header.range()),
+                forCodeCompletion(true)),
+          AllOf(qName("Tmpl"), declRange(Header.range("specdecl")),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl"), declRange(Header.range("partspecdecl")),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl"), declRange(Header.range("extinst")),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl"), declRange(Header.range("inst")),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl::x"), declRange(Header.range("xdecl")),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl<float, bool>::x"), 
declRange(Header.range("xdecl")),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl<double, bool>::x"),
+                declRange(Header.range("xdecl")), forCodeCompletion(false))));
 }
 
 TEST_F(SymbolCollectorTest, templateArgs) {

>From 1bf7ae80365a8f6b0fdca98a8805d6fce60013f3 Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Wed, 11 Mar 2026 22:36:46 +0100
Subject: [PATCH 12/18] Cleanup

---
 .../clangd/index/IndexAction.cpp              |  1 +
 .../clangd/index/SymbolCollector.cpp          | 20 +++++++++----------
 clang/lib/Index/IndexDecl.cpp                 |  4 ++--
 clang/lib/Index/IndexTypeSourceInfo.cpp       |  3 +++
 4 files changed, 15 insertions(+), 13 deletions(-)

diff --git a/clang-tools-extra/clangd/index/IndexAction.cpp 
b/clang-tools-extra/clangd/index/IndexAction.cpp
index 21e055b82d7225..3ae70e03ebbb5c 100644
--- a/clang-tools-extra/clangd/index/IndexAction.cpp
+++ b/clang-tools-extra/clangd/index/IndexAction.cpp
@@ -212,6 +212,7 @@ std::unique_ptr<FrontendAction> createStaticIndexingAction(
       index::IndexingOptions::SystemSymbolFilterKind::All;
   // We index function-local classes and its member functions only.
   IndexOpts.IndexFunctionLocals = true;
+  IndexOpts.IndexImplicitInstantiation = true;
   // We need to delay indexing so instantiations of function bodies become
   // available, this is so we can find constructor calls through `make_unique`.
   IndexOpts.DeferIndexingToEndOfTranslationUnit = true;
diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 8d7550cddde7b0..956c942ae0901e 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -1106,7 +1106,10 @@ const Symbol *SymbolCollector::addDeclaration(const 
NamedDecl &ND, SymbolID ID,
 
   S.Tags = computeSymbolTags(ND);
 
-  if (isImplicitTemplateInstantiation(&ND)) {
+  // Computing doc comments is expensive, so if we can skip it we should do so.
+  if (isImplicitTemplateInstantiation(&ND) ||
+      (!(S.Flags & Symbol::IndexedForCodeCompletion) &&
+       !Opts.StoreAllDocumentation)) {
     Symbols.insert(S);
     return Symbols.find(S.ID);
   }
@@ -1127,21 +1130,16 @@ const Symbol *SymbolCollector::addDeclaration(const 
NamedDecl &ND, SymbolID ID,
     DocComment = getDocComment(Ctx, SymbolCompletion,
                                /*CommentsFromHeaders=*/true);
     Documentation = formatDocumentation(*CCS, DocComment);
+    if (!DocComment.empty())
+      S.Flags |= Symbol::HasDocComment;
+    S.Documentation = Documentation;
   }
-  const auto UpdateDoc = [&] {
-    if (!AlreadyHasDoc) {
-      if (!DocComment.empty())
-        S.Flags |= Symbol::HasDocComment;
-      S.Documentation = Documentation;
-    }
-  };
+
   if (!(S.Flags & Symbol::IndexedForCodeCompletion)) {
-    if (Opts.StoreAllDocumentation)
-      UpdateDoc();
     Symbols.insert(S);
     return Symbols.find(S.ID);
   }
-  UpdateDoc();
+
   std::string Signature;
   std::string SnippetSuffix;
   getSignature(*CCS, &Signature, &SnippetSuffix, SymbolCompletion.Kind,
diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index db64149b884245..a5f2300649c638 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -735,8 +735,8 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
       indexTemplateParameters(Params, Parent);
     }
 
-    bool shouldContinue = Visit(Parent);
-    if (!shouldContinue)
+    bool ShouldContinue = Visit(Parent);
+    if (!ShouldContinue)
       return false;
 
     if (!IndexCtx.shouldIndexImplicitInstantiation())
diff --git a/clang/lib/Index/IndexTypeSourceInfo.cpp 
b/clang/lib/Index/IndexTypeSourceInfo.cpp
index a70a150f02b85c..45a81c94cc047f 100644
--- a/clang/lib/Index/IndexTypeSourceInfo.cpp
+++ b/clang/lib/Index/IndexTypeSourceInfo.cpp
@@ -202,6 +202,9 @@ class TypeIndexer : public RecursiveASTVisitor<TypeIndexer> 
{
 
   bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
                                             bool TraverseQualifier) {
+    // TODO: For now if we are a templated field and the substituted type is of
+    // form `A<B>`, we will only record a reference to `A`, but it is 
reasonable
+    // to also expect a reference to `B` to be recorded.
     const auto *T = TL.getTypePtr();
     if (!T)
       return true;

>From dff3515f41922226e6133ae2c2a6d65f522fb4a0 Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Fri, 27 Mar 2026 03:38:15 +0100
Subject: [PATCH 13/18] Clean up and review comments

---
 clang-tools-extra/clangd/AST.cpp              | 10 ++++++-
 clang-tools-extra/clangd/AST.h                |  3 +-
 clang-tools-extra/clangd/CodeComplete.cpp     |  2 +-
 .../clangd/index/SymbolCollector.cpp          |  7 ++---
 .../clangd/unittests/SymbolCollectorTests.cpp | 30 +++++++++++++++----
 clang/lib/Index/IndexDecl.cpp                 |  4 +--
 clang/lib/Index/IndexTypeSourceInfo.cpp       |  6 ++--
 clang/lib/Index/IndexingContext.cpp           | 15 ++++++----
 8 files changed, 54 insertions(+), 23 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 13262381d0c0ce..e01db87638266c 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -180,7 +180,15 @@ std::string getQualification(ASTContext &Context,
 
 } // namespace
 
-bool isTemplateInstantiation(const NamedDecl *D) {
+bool isTemplateInstantiationScope(const NamedDecl *D) {
+  // Fields and Methods don't know about template instantiations, so we have to
+  // ask their parent.
+  if (auto *FD = dyn_cast<FieldDecl>(D))
+    if (auto *RD = FD->getParent())
+      D = RD;
+  if (auto *MD = dyn_cast<CXXMethodDecl>(D))
+    if (auto *RD = MD->getParent())
+      D = RD;
   return isTemplateSpecializationKind(D,
                                       TSK_ExplicitInstantiationDeclaration) ||
          isTemplateSpecializationKind(D, TSK_ExplicitInstantiationDefinition) 
||
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index 8a8ba9148acfe1..197a218e074e77 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -145,7 +145,8 @@ std::string printType(const QualType QT, const DeclContext 
&CurContext,
 ///     template <class T> struct vector {};
 ///     template <> struct vector<bool>; // is an explicit instantiation.
 ///     vector<int> v; // 'vector<int>' is an implicit instantiation.
-bool isTemplateInstantiation(const NamedDecl *D);
+/// Also returns true for methods and fields inside of an instantiation.
+bool isTemplateInstantiationScope(const NamedDecl *D);
 /// Indicates if \p D is a template instantiation implicitly generated by the
 /// compiler, e.g.
 ///     template <class T> struct vector {};
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 86434931773da3..e2b2da78f090ac 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -2428,7 +2428,7 @@ bool isIndexedForCodeCompletion(const NamedDecl &ND, 
ASTContext &ASTCtx) {
   };
   // We only complete symbol's name, which is the same as the name of the
   // *primary* template in case of template specializations or instantiation.
-  if (isExplicitTemplateSpecialization(&ND) || isTemplateInstantiation(&ND))
+  if (isExplicitTemplateSpecialization(&ND) || 
isTemplateInstantiationScope(&ND))
     return false;
 
   // Category decls are not useful on their own outside the interface or
diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 956c942ae0901e..89201c2facb4c4 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -35,6 +35,7 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/Token.h"
@@ -665,9 +666,7 @@ bool SymbolCollector::handleDeclOccurrence(
   bool CollectRef = static_cast<bool>(Opts.RefFilter & toRefKind(Roles));
   // For now we only want the bare minimum of information for a class
   // instantiation such that we have symbols for the `BaseOf` relation.
-  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D);
-      CTSD && CTSD->hasDefinition() && !CTSD->bases().empty() &&
-      !CTSD->isExplicitSpecialization()) {
+  if (isTemplateInstantiationScope(ND)) {
     CollectRef = false;
   }
   // Unlike other fields, e.g. Symbols (which use spelling locations), we use
@@ -1107,7 +1106,7 @@ const Symbol *SymbolCollector::addDeclaration(const 
NamedDecl &ND, SymbolID ID,
   S.Tags = computeSymbolTags(ND);
 
   // Computing doc comments is expensive, so if we can skip it we should do so.
-  if (isImplicitTemplateInstantiation(&ND) ||
+  if (isTemplateInstantiationScope(&ND) ||
       (!(S.Flags & Symbol::IndexedForCodeCompletion) &&
        !Opts.StoreAllDocumentation)) {
     Symbols.insert(S);
diff --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp 
b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
index bf3d62d3fd2916..cde13285540a07 100644
--- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -486,32 +486,50 @@ TEST_F(SymbolCollectorTest, FileLocal) {
 
 TEST_F(SymbolCollectorTest, Template) {
   Annotations Header(R"(
-    template <class T, class U> struct [[Tmpl]] {T $xdecl[[x]] = 0;};
+    template <class T, class U> struct [[Tmpl]] {
+      //doc only for primary x
+      T $xdecl[[x]] = 0;
+      //doc only for primary y
+      T $ydecl[[y]]();
+      //doc only for primary z
+      struct $zdecl[[z]] {};
+    };
     template <> struct $specdecl[[Tmpl]]<int, bool> {};
     template <class U> struct $partspecdecl[[Tmpl]]<bool, U> {};
     extern template struct $extinst[[Tmpl]]<float, bool>;
     template struct $inst[[Tmpl]]<double, bool>;
   )");
+  CollectorOpts.StoreAllDocumentation = true;
   runSymbolCollector(Header.code(), /*Main=*/"");
   EXPECT_THAT(
       Symbols,
       UnorderedElementsAre(
           AllOf(qName("Tmpl"), declRange(Header.range()),
                 forCodeCompletion(true)),
+          AllOf(qName("Tmpl::x"), declRange(Header.range("xdecl")),
+                doc("doc only for primary x"), forCodeCompletion(false)),
+          AllOf(qName("Tmpl::y"), declRange(Header.range("ydecl")),
+                doc("doc only for primary y"), forCodeCompletion(false)),
+          AllOf(qName("Tmpl::z"), declRange(Header.range("zdecl")),
+                doc("doc only for primary z"), forCodeCompletion(false)),
           AllOf(qName("Tmpl"), declRange(Header.range("specdecl")),
                 forCodeCompletion(false)),
           AllOf(qName("Tmpl"), declRange(Header.range("partspecdecl")),
                 forCodeCompletion(false)),
           AllOf(qName("Tmpl"), declRange(Header.range("extinst")),
                 forCodeCompletion(false)),
-          AllOf(qName("Tmpl"), declRange(Header.range("inst")),
-                forCodeCompletion(false)),
-          AllOf(qName("Tmpl::x"), declRange(Header.range("xdecl")),
-                forCodeCompletion(false)),
           AllOf(qName("Tmpl<float, bool>::x"), 
declRange(Header.range("xdecl")),
+                doc(""), forCodeCompletion(false)),
+          AllOf(qName("Tmpl<float, bool>::y"), 
declRange(Header.range("ydecl")),
+                doc(""), forCodeCompletion(false)),
+          AllOf(qName("Tmpl"), declRange(Header.range("inst")),
                 forCodeCompletion(false)),
           AllOf(qName("Tmpl<double, bool>::x"),
-                declRange(Header.range("xdecl")), forCodeCompletion(false))));
+                declRange(Header.range("xdecl")), doc(""),
+                forCodeCompletion(false)),
+          AllOf(qName("Tmpl<double, bool>::y"),
+                declRange(Header.range("ydecl")), doc(""),
+                forCodeCompletion(false))));
 }
 
 TEST_F(SymbolCollectorTest, templateArgs) {
diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index a5f2300649c638..2b3adde29f5077 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -753,8 +753,8 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
           // For now we are only interested in instantiations with inheritance.
           if (!CTSD || !CTSD->hasDefinition() || CTSD->bases().empty())
             continue;
-          // Explicit specialization is handled elsewhere
-          if (CTSD->isExplicitSpecialization())
+          // Explicit instantiations and specializations are handled elsewhere
+          if (CTSD->isExplicitInstantiationOrSpecialization())
             continue;
           Visit(RD);
         }
diff --git a/clang/lib/Index/IndexTypeSourceInfo.cpp 
b/clang/lib/Index/IndexTypeSourceInfo.cpp
index 45a81c94cc047f..8ab162a9147798 100644
--- a/clang/lib/Index/IndexTypeSourceInfo.cpp
+++ b/clang/lib/Index/IndexTypeSourceInfo.cpp
@@ -202,15 +202,15 @@ class TypeIndexer : public 
RecursiveASTVisitor<TypeIndexer> {
 
   bool TraverseSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL,
                                             bool TraverseQualifier) {
-    // TODO: For now if we are a templated field and the substituted type is of
-    // form `A<B>`, we will only record a reference to `A`, but it is 
reasonable
-    // to also expect a reference to `B` to be recorded.
     const auto *T = TL.getTypePtr();
     if (!T)
       return true;
     auto QT = T->getReplacementType();
     if (QT.isNull())
       return true;
+    // TODO: For now if we are a templated field and the substituted type is of
+    // form `A<B>`, we will only record a reference to `A`, but it is 
reasonable
+    // to also expect a reference to `B` to be recorded.
     auto *CXXRD = QT->getAsCXXRecordDecl();
     if (!CXXRD)
       return true;
diff --git a/clang/lib/Index/IndexingContext.cpp 
b/clang/lib/Index/IndexingContext.cpp
index c6843cf46cf8e9..fc2e3758fe0ac6 100644
--- a/clang/lib/Index/IndexingContext.cpp
+++ b/clang/lib/Index/IndexingContext.cpp
@@ -402,11 +402,16 @@ bool IndexingContext::handleDeclOccurrence(const Decl *D, 
SourceLocation Loc,
   if (!OrigD)
     OrigD = D;
 
-  if (isTemplateImplicitInstantiation(D) && IsRef) {
-    D = adjustTemplateImplicitInstantiation(D);
-    if (!D)
-      return true;
-    assert(!isTemplateImplicitInstantiation(D));
+  if (isTemplateImplicitInstantiation(D)) {
+    if (IsRef) {
+      D = adjustTemplateImplicitInstantiation(D);
+      if (!D)
+        return true;
+      assert(!isTemplateImplicitInstantiation(D));
+    } else {
+      if (!shouldIndexImplicitInstantiation())
+        return true;
+    }
   }
 
   if (IsRef)

>From 17c86a8f1704e0762ce04f08cac7009932ec1ed5 Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Fri, 27 Mar 2026 03:41:07 +0100
Subject: [PATCH 14/18] formatting

---
 clang-tools-extra/clangd/CodeComplete.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index e2b2da78f090ac..8c39adbdc31f87 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -2428,7 +2428,8 @@ bool isIndexedForCodeCompletion(const NamedDecl &ND, 
ASTContext &ASTCtx) {
   };
   // We only complete symbol's name, which is the same as the name of the
   // *primary* template in case of template specializations or instantiation.
-  if (isExplicitTemplateSpecialization(&ND) || 
isTemplateInstantiationScope(&ND))
+  if (isExplicitTemplateSpecialization(&ND) ||
+      isTemplateInstantiationScope(&ND))
     return false;
 
   // Category decls are not useful on their own outside the interface or

>From ea36f4ceb0db3c777dc4d3a61da2e290b7d4f6ae Mon Sep 17 00:00:00 2001
From: timon-ul <[email protected]>
Date: Fri, 27 Mar 2026 13:15:05 +0100
Subject: [PATCH 15/18] Fixed documentation error

---
 clang-tools-extra/clangd/AST.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index 197a218e074e77..b5a30ea3716131 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -143,8 +143,8 @@ std::string printType(const QualType QT, const DeclContext 
&CurContext,
 
 /// Indicates if \p D is a template instantiation, implicit or explicit e.g.
 ///     template <class T> struct vector {};
-///     template <> struct vector<bool>; // is an explicit instantiation.
-///     vector<int> v; // 'vector<int>' is an implicit instantiation.
+///     template struct vector<bool>; // is an explicit instantiation.
+///     vector<int> v; // is an implicit instantiation.
 /// Also returns true for methods and fields inside of an instantiation.
 bool isTemplateInstantiationScope(const NamedDecl *D);
 /// Indicates if \p D is a template instantiation implicitly generated by the

>From 61bb9bdaff129e5bcf7c504d40ba29c62a4c3939 Mon Sep 17 00:00:00 2001
From: Nathan Ridge <[email protected]>
Date: Sat, 14 Nov 2026 02:27:42 -0500
Subject: [PATCH 16/18] Testcase demonstrating a bug in the patch

For a class defined in a header, only instantiations made in the
first TU to include the header are retained in the index.
---
 .../clangd/unittests/BackgroundIndexTests.cpp | 66 +++++++++++++++++--
 1 file changed, 62 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp 
b/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
index 0eb4acf0469b79..91ddeb1a39c339 100644
--- a/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
+++ b/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
@@ -191,8 +191,7 @@ TEST_F(BackgroundIndexTest, IndexTwoFiles) {
   MemoryShardStorage MSS(Storage, CacheHits);
   OverlayCDB CDB(/*Base=*/nullptr);
   BackgroundIndex::Options Opts;
-  BackgroundIndex Idx(
-      FS, CDB, [&](llvm::StringRef) { return &MSS; }, Opts);
+  BackgroundIndex Idx(FS, CDB, [&](llvm::StringRef) { return &MSS; }, Opts);
 
   tooling::CompileCommand Cmd;
   Cmd.Filename = testPath("root/A.cc");
@@ -353,6 +352,66 @@ TEST_F(BackgroundIndexTest, 
ConstructorForwardingMultiFile) {
                        fileURI("unittest:///root/second.cpp")}));
 }
 
+TEST_F(BackgroundIndexTest, TemplateInstantiationBaseOfMultiFile) {
+  // The BaseOf chain First -> Inherit<First> -> Battler relies on the
+  // instantiation Inherit<First> being visited while traversing header.hpp.
+  // Declarations in header.hpp are only traversed by the first TU that indexes
+  // it, so instantiations that exist only in later TUs are never recorded.
+  MockFS FS;
+  FS.Files[testPath("root/header.hpp")] = R"cpp(
+    class First {};
+    template <typename T> struct Inherit : T {};
+  )cpp";
+  FS.Files[testPath("root/first.cpp")] = R"cpp(
+    #include "header.hpp"
+  )cpp";
+  FS.Files[testPath("root/second.cpp")] = R"cpp(
+    #include "header.hpp"
+    class Battler : Inherit<First> {};
+  )cpp";
+
+  llvm::StringMap<std::string> Storage;
+  size_t CacheHits = 0;
+  MemoryShardStorage MSS(Storage, CacheHits);
+  OverlayCDB CDB(/*Base=*/nullptr);
+  BackgroundIndex Idx(FS, CDB, [&](llvm::StringRef) { return &MSS; },
+                      /*Opts=*/{});
+
+  auto IndexTUsInOrder = [&](llvm::ArrayRef<llvm::StringRef> Files) {
+    for (llvm::StringRef File : Files) {
+      tooling::CompileCommand Cmd;
+      Cmd.Filename = testPath(File);
+      Cmd.Directory = testPath("root");
+      Cmd.CommandLine = {"clang++", testPath(File)};
+      CDB.setCompileCommand(testPath(File), Cmd);
+      // Finish each TU before starting the next, so the order is fixed.
+      EXPECT_TRUE(Idx.blockUntilIdleForTest());
+    }
+  };
+
+  auto FindImplementations = [&](llvm::StringRef BaseName) {
+    std::vector<std::string> Names;
+    RelationsRequest Req;
+    Req.Predicate = RelationKind::BaseOf;
+    Req.Subjects.insert(findSymbol(runFuzzyFind(Idx, BaseName), BaseName).ID);
+    llvm::DenseSet<SymbolID> Seen;
+    while (!Req.Subjects.empty()) {
+      llvm::DenseSet<SymbolID> Next;
+      Idx.relations(Req, [&](const SymbolID &, const Symbol &Object) {
+        if (Seen.insert(Object.ID).second) {
+          Next.insert(Object.ID);
+          Names.push_back(Object.Name.str());
+        }
+      });
+      Req.Subjects = std::move(Next);
+    }
+    return Names;
+  };
+
+  IndexTUsInOrder({"root/first.cpp", "root/second.cpp"});
+  EXPECT_THAT(FindImplementations("First"), Contains("Battler"));
+}
+
 TEST_F(BackgroundIndexTest, MainFileRefs) {
   MockFS FS;
   FS.Files[testPath("root/A.h")] = R"cpp(
@@ -366,8 +425,7 @@ TEST_F(BackgroundIndexTest, MainFileRefs) {
   MemoryShardStorage MSS(Storage, CacheHits);
   OverlayCDB CDB(/*Base=*/nullptr);
   BackgroundIndex::Options Opts;
-  BackgroundIndex Idx(
-      FS, CDB, [&](llvm::StringRef) { return &MSS; }, Opts);
+  BackgroundIndex Idx(FS, CDB, [&](llvm::StringRef) { return &MSS; }, Opts);
 
   tooling::CompileCommand Cmd;
   Cmd.Filename = testPath("root/A.cc");

>From 1f7d0773756b219e27ebb4cdf122a0afbf772b5e Mon Sep 17 00:00:00 2001
From: Nathan Ridge <[email protected]>
Date: Mon, 16 Nov 2026 00:20:16 -0500
Subject: [PATCH 17/18] A second testcase exercising two levels of template
 instantiation

A naive fix for the first testcase might fail to handle cases
where a class template instantiation's point of instantiation is
itself inside an instantiation.
---
 .../clangd/unittests/BackgroundIndexTests.cpp | 99 +++++++++++++------
 1 file changed, 68 insertions(+), 31 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp 
b/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
index 91ddeb1a39c339..bbcff51918365e 100644
--- a/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
+++ b/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
@@ -352,6 +352,41 @@ TEST_F(BackgroundIndexTest, 
ConstructorForwardingMultiFile) {
                        fileURI("unittest:///root/second.cpp")}));
 }
 
+// Indexes the files one TU at a time, so the order is fixed.
+static void indexTUsInOrder(BackgroundIndex &Idx, OverlayCDB &CDB,
+                            llvm::ArrayRef<llvm::StringRef> Files) {
+  for (llvm::StringRef File : Files) {
+    tooling::CompileCommand Cmd;
+    Cmd.Filename = testPath(File);
+    Cmd.Directory = testPath("root");
+    Cmd.CommandLine = {"clang++", testPath(File)};
+    CDB.setCompileCommand(testPath(File), Cmd);
+    EXPECT_TRUE(Idx.blockUntilIdleForTest());
+  }
+}
+
+// Returns the names of all transitive implementations of BaseName, walking
+// BaseOf relations the way findImplementors() does.
+static std::vector<std::string>
+transitiveImplementations(const SymbolIndex &Idx, llvm::StringRef BaseName) {
+  std::vector<std::string> Names;
+  RelationsRequest Req;
+  Req.Predicate = RelationKind::BaseOf;
+  Req.Subjects.insert(findSymbol(runFuzzyFind(Idx, BaseName), BaseName).ID);
+  llvm::DenseSet<SymbolID> Seen;
+  while (!Req.Subjects.empty()) {
+    llvm::DenseSet<SymbolID> Next;
+    Idx.relations(Req, [&](const SymbolID &, const Symbol &Object) {
+      if (Seen.insert(Object.ID).second) {
+        Next.insert(Object.ID);
+        Names.push_back(Object.Name.str());
+      }
+    });
+    Req.Subjects = std::move(Next);
+  }
+  return Names;
+}
+
 TEST_F(BackgroundIndexTest, TemplateInstantiationBaseOfMultiFile) {
   // The BaseOf chain First -> Inherit<First> -> Battler relies on the
   // instantiation Inherit<First> being visited while traversing header.hpp.
@@ -377,39 +412,41 @@ TEST_F(BackgroundIndexTest, 
TemplateInstantiationBaseOfMultiFile) {
   BackgroundIndex Idx(FS, CDB, [&](llvm::StringRef) { return &MSS; },
                       /*Opts=*/{});
 
-  auto IndexTUsInOrder = [&](llvm::ArrayRef<llvm::StringRef> Files) {
-    for (llvm::StringRef File : Files) {
-      tooling::CompileCommand Cmd;
-      Cmd.Filename = testPath(File);
-      Cmd.Directory = testPath("root");
-      Cmd.CommandLine = {"clang++", testPath(File)};
-      CDB.setCompileCommand(testPath(File), Cmd);
-      // Finish each TU before starting the next, so the order is fixed.
-      EXPECT_TRUE(Idx.blockUntilIdleForTest());
-    }
-  };
+  indexTUsInOrder(Idx, CDB, {"root/first.cpp", "root/second.cpp"});
+  EXPECT_THAT(transitiveImplementations(Idx, "First"), Contains("Battler"));
+}
 
-  auto FindImplementations = [&](llvm::StringRef BaseName) {
-    std::vector<std::string> Names;
-    RelationsRequest Req;
-    Req.Predicate = RelationKind::BaseOf;
-    Req.Subjects.insert(findSymbol(runFuzzyFind(Idx, BaseName), BaseName).ID);
-    llvm::DenseSet<SymbolID> Seen;
-    while (!Req.Subjects.empty()) {
-      llvm::DenseSet<SymbolID> Next;
-      Idx.relations(Req, [&](const SymbolID &, const Symbol &Object) {
-        if (Seen.insert(Object.ID).second) {
-          Next.insert(Object.ID);
-          Names.push_back(Object.Name.str());
-        }
-      });
-      Req.Subjects = std::move(Next);
-    }
-    return Names;
-  };
+TEST_F(BackgroundIndexTest, NestedTemplateInstantiationBaseOfMultiFile) {
+  // Like TemplateInstantiationBaseOfMultiFile, but the chain
+  // Bar -> A<Bar> -> B<Bar> -> Foo passes through two layers of instantiation.
+  // A<Bar> is instantiated from B<Bar>'s base-specifier in b.hpp, but it is
+  // foo.cpp that causes it to exist.
+  MockFS FS;
+  FS.Files[testPath("root/a.hpp")] = R"cpp(
+    template <typename T> struct A : T {};
+  )cpp";
+  FS.Files[testPath("root/b.hpp")] = R"cpp(
+    #include "a.hpp"
+    template <typename T> struct B : A<T> {};
+  )cpp";
+  FS.Files[testPath("root/first.cpp")] = R"cpp(
+    #include "b.hpp"
+  )cpp";
+  FS.Files[testPath("root/foo.cpp")] = R"cpp(
+    #include "b.hpp"
+    class Bar {};
+    class Foo : B<Bar> {};
+  )cpp";
+
+  llvm::StringMap<std::string> Storage;
+  size_t CacheHits = 0;
+  MemoryShardStorage MSS(Storage, CacheHits);
+  OverlayCDB CDB(/*Base=*/nullptr);
+  BackgroundIndex Idx(FS, CDB, [&](llvm::StringRef) { return &MSS; },
+                      /*Opts=*/{});
 
-  IndexTUsInOrder({"root/first.cpp", "root/second.cpp"});
-  EXPECT_THAT(FindImplementations("First"), Contains("Battler"));
+  indexTUsInOrder(Idx, CDB, {"root/first.cpp", "root/foo.cpp"});
+  EXPECT_THAT(transitiveImplementations(Idx, "Bar"), Contains("Foo"));
 }
 
 TEST_F(BackgroundIndexTest, MainFileRefs) {

>From 26d3e742f243f50bd364baa9df287ce22fb3a01f Mon Sep 17 00:00:00 2001
From: Timon Ulrich <[email protected]>
Date: Fri, 20 Nov 2026 22:49:23 +0100
Subject: [PATCH 18/18] Simpler approach first shot and debug test

---
 .../clangd/unittests/XRefsTests.cpp           | 19 ++++++++++++++
 clang/lib/Index/IndexDecl.cpp                 | 26 +------------------
 clang/lib/Index/IndexingContext.cpp           |  5 +---
 3 files changed, 21 insertions(+), 29 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index cd97a7c5d3688f..f355d23cb8ef82 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2132,6 +2132,25 @@ TEST(FindImplementations, InheritanceTemplate) {
               UnorderedPointwise(declRange(), Main.ranges("Third")));
 }
 
+TEST(FindImplementations, InheritanceTemplateDebug) {
+  Annotations Main(R"cpp(
+    class Th$Third^ird {};
+
+    template <typename... T>
+    struct $Third[[Inherit]] : T... {};
+
+    class $Third[[Maria]] : Inherit<Third> {};
+  )cpp");
+
+  TestTU TU;
+  TU.Code = std::string(Main.code());
+  auto AST = TU.build();
+  auto Index = TU.index();
+
+  EXPECT_THAT(findImplementations(AST, Main.point("Third"), Index.get()),
+              UnorderedPointwise(declRange(), Main.ranges("Third")));
+}
+
 TEST(FindImplementations, CaptureDefinition) {
   llvm::StringRef Test = R"cpp(
     struct Base {
diff --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index 2b3adde29f5077..8bcad4739c788b 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -735,31 +735,7 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor<IndexingDeclVisitor, bool> {
       indexTemplateParameters(Params, Parent);
     }
 
-    bool ShouldContinue = Visit(Parent);
-    if (!ShouldContinue)
-      return false;
-
-    if (!IndexCtx.shouldIndexImplicitInstantiation())
-      return true;
-
-    // Only check instantiation if D is canonical to prevent infinite cycling
-    if (D != D->getCanonicalDecl())
-      return true;
-
-    if (const auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(D))
-      for (auto *SD : CTD->specializations())
-        for (auto *RD : SD->redecls()) {
-          auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
-          // For now we are only interested in instantiations with inheritance.
-          if (!CTSD || !CTSD->hasDefinition() || CTSD->bases().empty())
-            continue;
-          // Explicit instantiations and specializations are handled elsewhere
-          if (CTSD->isExplicitInstantiationOrSpecialization())
-            continue;
-          Visit(RD);
-        }
-
-    return true;
+    return Visit(Parent);
   }
 
   bool VisitConceptDecl(const ConceptDecl *D) {
diff --git a/clang/lib/Index/IndexingContext.cpp 
b/clang/lib/Index/IndexingContext.cpp
index fc2e3758fe0ac6..1028bdd4c139d5 100644
--- a/clang/lib/Index/IndexingContext.cpp
+++ b/clang/lib/Index/IndexingContext.cpp
@@ -97,7 +97,7 @@ bool IndexingContext::handleReference(const NamedDecl *D, 
SourceLocation Loc,
        isa<TemplateTemplateParmDecl>(D))) {
     return true;
   }
-  return handleDeclOccurrence(D, Loc, /*IsRef=*/true, Parent, Roles, Relations,
+  return handleDeclOccurrence(D, Loc, /*IsRef=*/!D->isImplicit(), Parent, 
Roles, Relations,
                               RefE, nullptr, DC);
 }
 
@@ -408,9 +408,6 @@ bool IndexingContext::handleDeclOccurrence(const Decl *D, 
SourceLocation Loc,
       if (!D)
         return true;
       assert(!isTemplateImplicitInstantiation(D));
-    } else {
-      if (!shouldIndexImplicitInstantiation())
-        return true;
     }
   }
 

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to