summarylogtreecommitdiffstats
path: root/resolve-depend-type.patch
blob: 8b9641c513870bba82125ad6764a177dea80c96a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28..4ea1177c4b6c 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -16,12 +16,14 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/DeclVisitor.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/AST/TemplateBase.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/Builtins.h"
@@ -636,7 +638,7 @@ static NamedDecl *getOnlyInstantiationImpl(TemplateDeclTy *TD) {
   return Only;
 }
 
-NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl) {
+NamedDecl *getOnlyInstantiation(const NamedDecl *TemplatedDecl) {
   if (TemplateDecl *TD = TemplatedDecl->getDescribedTemplate()) {
     if (auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(TD))
       return getOnlyInstantiationImpl(CTD);
@@ -648,6 +650,197 @@ NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl) {
   return nullptr;
 }
 
+NamedDecl *getOnlyInstantiatedDecls(const NamedDecl *DependentDecl) {
+  if (auto *Instantiation = getOnlyInstantiation(DependentDecl))
+    return Instantiation;
+  NamedDecl *OuterTemplate = nullptr;
+  for (auto *DC = DependentDecl->getDeclContext(); isa<CXXRecordDecl>(DC);
+       DC = DC->getParent()) {
+    auto *RD = cast<CXXRecordDecl>(DC);
+    if (auto *I = getOnlyInstantiation(RD)) {
+      OuterTemplate = I;
+      break;
+    }
+  }
+
+  if (!OuterTemplate)
+    return nullptr;
+
+  struct Visitor : DeclVisitor<Visitor, NamedDecl *> {
+    const NamedDecl *TemplatedDecl;
+    Visitor(const NamedDecl *TemplatedDecl) : TemplatedDecl(TemplatedDecl) {}
+
+    NamedDecl *VisitCXXRecordDecl(CXXRecordDecl *RD) {
+      if (RD->getTemplateInstantiationPattern() == TemplatedDecl)
+        return RD;
+      for (auto *F : RD->decls()) {
+        if (auto *Injected = llvm::dyn_cast<CXXRecordDecl>(F);
+            Injected && Injected->isInjectedClassName())
+          continue;
+        if (NamedDecl *ND = Visit(F))
+          return ND;
+      }
+      return nullptr;
+    }
+
+    NamedDecl *VisitClassTemplateDecl(ClassTemplateDecl *CTD) {
+      unsigned Size = llvm::range_size(CTD->specializations());
+      if (Size != 1)
+        return nullptr;
+      return Visit(*CTD->spec_begin());
+    }
+
+    NamedDecl *VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD) {
+      unsigned Size = llvm::range_size(FTD->specializations());
+      if (Size != 1)
+        return nullptr;
+      return Visit(*FTD->spec_begin());
+    }
+
+    NamedDecl *VisitFunctionDecl(FunctionDecl *FD) {
+      if (FD->getTemplateInstantiationPattern() == TemplatedDecl)
+        return FD;
+      return nullptr;
+    }
+
+    NamedDecl *VisitVarDecl(VarDecl *VD) {
+      if (VD->getCanonicalDecl()->getSourceRange() ==
+          TemplatedDecl->getCanonicalDecl()->getSourceRange())
+        return VD;
+      return nullptr;
+    }
+
+    NamedDecl *VisitFieldDecl(FieldDecl *FD) {
+      if (FD->getCanonicalDecl()->getSourceRange() ==
+          TemplatedDecl->getCanonicalDecl()->getSourceRange())
+        return FD;
+      return nullptr;
+    }
+  };
+  return Visitor(DependentDecl).Visit(OuterTemplate);
+}
+
+std::optional<DynTypedNode>
+getOnlyInstantiatedNode(const DeclContext *StartingPoint,
+                        const DynTypedNode &DependentNode) {
+  if (auto *CTD = DependentNode.get<ClassTemplateDecl>())
+    return getOnlyInstantiatedNode(
+        StartingPoint, DynTypedNode::create(*CTD->getTemplatedDecl()));
+  if (auto *FTD = DependentNode.get<FunctionTemplateDecl>())
+    return getOnlyInstantiatedNode(
+        StartingPoint, DynTypedNode::create(*FTD->getTemplatedDecl()));
+
+  if (auto *FD = DependentNode.get<FunctionDecl>()) {
+    auto *ID = getOnlyInstantiatedDecls(FD);
+    if (!ID)
+      return std::nullopt;
+    return DynTypedNode::create(*ID);
+  }
+  if (auto *RD = DependentNode.get<CXXRecordDecl>()) {
+    auto *ID = getOnlyInstantiatedDecls(RD);
+    if (!ID)
+      return std::nullopt;
+    return DynTypedNode::create(*ID);
+  }
+
+  NamedDecl *InstantiatedEnclosingDecl = nullptr;
+  for (auto *DC = StartingPoint; DC;
+       DC = DC->getParent()) {
+    auto *ND = llvm::dyn_cast<NamedDecl>(DC);
+    if (!ND)
+      continue;
+    InstantiatedEnclosingDecl = getOnlyInstantiatedDecls(ND);
+    if (InstantiatedEnclosingDecl)
+      break;
+  }
+
+  if (!InstantiatedEnclosingDecl)
+    return std::nullopt;
+
+  auto *InstantiatedFunctionDecl =
+      llvm::dyn_cast<FunctionDecl>(InstantiatedEnclosingDecl);
+  if (!InstantiatedFunctionDecl)
+    return std::nullopt;
+
+  struct FullExprVisitor : RecursiveASTVisitor<FullExprVisitor> {
+    const DynTypedNode &DependentNode;
+    Stmt *Result;
+    FullExprVisitor(const DynTypedNode &DependentNode)
+        : DependentNode(DependentNode), Result(nullptr) {}
+
+    bool shouldVisitTemplateInstantiations() const { return true; }
+
+    bool shouldVisitImplicitCode() const { return true; }
+
+    bool VisitStmt(Stmt *S) {
+      if (S->getSourceRange() == DependentNode.getSourceRange()) {
+        Result = S;
+        return false;
+      }
+      return true;
+    }
+  };
+
+  FullExprVisitor Visitor(DependentNode);
+  Visitor.TraverseFunctionDecl(InstantiatedFunctionDecl);
+  if (Visitor.Result)
+    return DynTypedNode::create(*Visitor.Result);
+  return std::nullopt;
+}
+
+NamedDecl *
+getOnlyInstantiationForMemberFunction(const CXXMethodDecl *TemplatedDecl) {
+  if (auto *MemberInstantiation = getOnlyInstantiation(TemplatedDecl))
+    return MemberInstantiation;
+  NamedDecl *OuterTemplate = nullptr;
+  for (auto *DC = TemplatedDecl->getDeclContext(); isa<CXXRecordDecl>(DC);
+       DC = DC->getParent()) {
+    auto *RD = cast<CXXRecordDecl>(DC);
+    if (auto *I = getOnlyInstantiation(RD)) {
+      OuterTemplate = I;
+      break;
+    }
+  }
+  if (!OuterTemplate)
+    return nullptr;
+  struct Visitor : DeclVisitor<Visitor, NamedDecl *> {
+    const CXXMethodDecl *TD;
+    Visitor(const CXXMethodDecl *TemplatedDecl) : TD(TemplatedDecl) {}
+    NamedDecl *VisitCXXRecordDecl(CXXRecordDecl *RD) {
+      for (auto *F : RD->decls()) {
+        if (!isa<NamedDecl>(F))
+          continue;
+        if (NamedDecl *ND = Visit(F))
+          return ND;
+      }
+      return nullptr;
+    }
+
+    NamedDecl *VisitClassTemplateDecl(ClassTemplateDecl *CTD) {
+      unsigned Size = llvm::range_size(CTD->specializations());
+      if (Size != 1)
+        return nullptr;
+      return Visit(*CTD->spec_begin());
+    }
+
+    NamedDecl *VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD) {
+      unsigned Size = llvm::range_size(FTD->specializations());
+      if (Size != 1)
+        return nullptr;
+      return Visit(*FTD->spec_begin());
+    }
+
+    NamedDecl *VisitCXXMethodDecl(CXXMethodDecl *MD) {
+      auto *Pattern = MD->getTemplateInstantiationPattern();
+      if (Pattern == TD)
+        return MD;
+      return nullptr;
+    }
+
+  };
+  return Visitor(TemplatedDecl).Visit(OuterTemplate);
+}
+
 std::vector<const Attr *> getAttributes(const DynTypedNode &N) {
   std::vector<const Attr *> Result;
   if (const auto *TL = N.get<TypeLoc>()) {
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd..74a43fdce269 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -177,7 +177,14 @@ TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL);
 
 // If TemplatedDecl is the generic body of a template, and the template has
 // exactly one visible instantiation, return the instantiated body.
-NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl);
+NamedDecl *getOnlyInstantiation(const NamedDecl *TemplatedDecl);
+
+NamedDecl *
+getOnlyInstantiationForMemberFunction(const CXXMethodDecl *TemplatedDecl);
+
+std::optional<DynTypedNode>
+getOnlyInstantiatedNode(const DeclContext *StartingPoint,
+                        const DynTypedNode &DependentNode);
 
 /// Return attributes attached directly to a node.
 std::vector<const Attr *> getAttributes(const DynTypedNode &);
diff --git a/clang-tools-extra/clangd/FindTarget.cpp b/clang-tools-extra/clangd/FindTarget.cpp
index e702c6b3537a..26142097a1bc 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -133,7 +133,7 @@ struct TargetFinder {
   using Rel = DeclRelation;
 
 private:
-  const HeuristicResolver *Resolver;
+  const HeuristicResolver &Resolver;
   llvm::SmallDenseMap<const NamedDecl *,
                       std::pair<RelSet, /*InsertionOrder*/ size_t>>
       Decls;
@@ -153,7 +153,7 @@ private:
   }
 
 public:
-  TargetFinder(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
+  TargetFinder(const HeuristicResolver &Resolver) : Resolver(Resolver) {}
 
   llvm::SmallVector<std::pair<const NamedDecl *, RelSet>, 1> takeDecls() const {
     using ValTy = std::pair<const NamedDecl *, RelSet>;
@@ -197,10 +197,8 @@ public:
       Flags |= Rel::Alias; // continue with the alias
     } else if (const UnresolvedUsingValueDecl *UUVD =
                    dyn_cast<UnresolvedUsingValueDecl>(D)) {
-      if (Resolver) {
-        for (const NamedDecl *Target : Resolver->resolveUsingValueDecl(UUVD)) {
-          add(Target, Flags); // no Underlying as this is a non-renaming alias
-        }
+      for (const NamedDecl *Target : Resolver.resolveUsingValueDecl(UUVD)) {
+        add(Target, Flags); // no Underlying as this is a non-renaming alias
       }
       Flags |= Rel::Alias; // continue with the alias
     } else if (isa<UnresolvedUsingTypenameDecl>(D)) {
@@ -304,17 +302,13 @@ public:
       }
       void
       VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
-        if (Outer.Resolver) {
-          for (const NamedDecl *D : Outer.Resolver->resolveMemberExpr(E)) {
-            Outer.add(D, Flags);
-          }
+        for (const NamedDecl *D : Outer.Resolver.resolveMemberExpr(E)) {
+          Outer.add(D, Flags);
         }
       }
       void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
-        if (Outer.Resolver) {
-          for (const NamedDecl *D : Outer.Resolver->resolveDeclRefExpr(E)) {
-            Outer.add(D, Flags);
-          }
+        for (const NamedDecl *D : Outer.Resolver.resolveDeclRefExpr(E)) {
+          Outer.add(D, Flags);
         }
       }
       void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
@@ -407,20 +401,16 @@ public:
           Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
       }
       void VisitDependentNameType(const DependentNameType *DNT) {
-        if (Outer.Resolver) {
-          for (const NamedDecl *ND :
-               Outer.Resolver->resolveDependentNameType(DNT)) {
-            Outer.add(ND, Flags);
-          }
+        for (const NamedDecl *ND :
+             Outer.Resolver.resolveDependentNameType(DNT)) {
+          Outer.add(ND, Flags);
         }
       }
       void VisitDependentTemplateSpecializationType(
           const DependentTemplateSpecializationType *DTST) {
-        if (Outer.Resolver) {
-          for (const NamedDecl *ND :
-               Outer.Resolver->resolveTemplateSpecializationType(DTST)) {
-            Outer.add(ND, Flags);
-          }
+        for (const NamedDecl *ND :
+             Outer.Resolver.resolveTemplateSpecializationType(DTST)) {
+          Outer.add(ND, Flags);
         }
       }
       void VisitTypedefType(const TypedefType *TT) {
@@ -495,10 +485,7 @@ public:
       add(NNS->getAsNamespaceAlias(), Flags);
       return;
     case NestedNameSpecifier::Identifier:
-      if (Resolver) {
-        add(QualType(Resolver->resolveNestedNameSpecifierToType(NNS), 0),
-            Flags);
-      }
+      add(QualType(Resolver.resolveNestedNameSpecifierToType(NNS), 0), Flags);
       return;
     case NestedNameSpecifier::TypeSpec:
     case NestedNameSpecifier::TypeSpecWithTemplate:
@@ -549,7 +536,7 @@ public:
 } // namespace
 
 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
-allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver) {
+allTargetDecls(const DynTypedNode &N, const HeuristicResolver &Resolver) {
   dlog("allTargetDecls({0})", nodeToString(N));
   TargetFinder Finder(Resolver);
   DeclRelationSet Flags;
@@ -580,7 +567,7 @@ allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver) {
 
 llvm::SmallVector<const NamedDecl *, 1>
 targetDecl(const DynTypedNode &N, DeclRelationSet Mask,
-           const HeuristicResolver *Resolver) {
+           const HeuristicResolver &Resolver) {
   llvm::SmallVector<const NamedDecl *, 1> Result;
   for (const auto &Entry : allTargetDecls(N, Resolver)) {
     if (!(Entry.second & ~Mask))
@@ -591,7 +578,7 @@ targetDecl(const DynTypedNode &N, DeclRelationSet Mask,
 
 llvm::SmallVector<const NamedDecl *, 1>
 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask,
-                         const HeuristicResolver *Resolver) {
+                         const HeuristicResolver &Resolver) {
   assert(!(Mask & (DeclRelation::TemplatePattern |
                    DeclRelation::TemplateInstantiation)) &&
          "explicitReferenceTargets handles templates on its own");
@@ -623,11 +610,11 @@ explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask,
 
 namespace {
 llvm::SmallVector<ReferenceLoc> refInDecl(const Decl *D,
-                                          const HeuristicResolver *Resolver) {
+                                          const HeuristicResolver &Resolver) {
   struct Visitor : ConstDeclVisitor<Visitor> {
-    Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
+    Visitor(const HeuristicResolver &Resolver) : Resolver(Resolver) {}
 
-    const HeuristicResolver *Resolver;
+    const HeuristicResolver &Resolver;
     llvm::SmallVector<ReferenceLoc> Refs;
 
     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
@@ -748,11 +735,11 @@ llvm::SmallVector<ReferenceLoc> refInDecl(const Decl *D,
 }
 
 llvm::SmallVector<ReferenceLoc> refInStmt(const Stmt *S,
-                                          const HeuristicResolver *Resolver) {
+                                          const HeuristicResolver &Resolver) {
   struct Visitor : ConstStmtVisitor<Visitor> {
-    Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
+    Visitor(const HeuristicResolver &Resolver) : Resolver(Resolver) {}
 
-    const HeuristicResolver *Resolver;
+    const HeuristicResolver &Resolver;
     // FIXME: handle more complicated cases: more ObjC, designated initializers.
     llvm::SmallVector<ReferenceLoc> Refs;
 
@@ -859,11 +846,11 @@ llvm::SmallVector<ReferenceLoc> refInStmt(const Stmt *S,
 }
 
 llvm::SmallVector<ReferenceLoc>
-refInTypeLoc(TypeLoc L, const HeuristicResolver *Resolver) {
+refInTypeLoc(TypeLoc L, const HeuristicResolver &Resolver) {
   struct Visitor : TypeLocVisitor<Visitor> {
-    Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
+    Visitor(const HeuristicResolver &Resolver) : Resolver(Resolver) {}
 
-    const HeuristicResolver *Resolver;
+    const HeuristicResolver &Resolver;
     llvm::SmallVector<ReferenceLoc> Refs;
 
     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
@@ -973,7 +960,7 @@ class ExplicitReferenceCollector
     : public RecursiveASTVisitor<ExplicitReferenceCollector> {
 public:
   ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out,
-                             const HeuristicResolver *Resolver)
+                             const HeuristicResolver &Resolver)
       : Out(Out), Resolver(Resolver) {
     assert(Out);
   }
@@ -1152,7 +1139,7 @@ private:
   }
 
   llvm::function_ref<void(ReferenceLoc)> Out;
-  const HeuristicResolver *Resolver;
+  const HeuristicResolver &Resolver;
   /// TypeLocs starting at these locations must be skipped, see
   /// TraverseElaboratedTypeSpecifierLoc for details.
   llvm::DenseSet<SourceLocation> TypeLocsToSkip;
@@ -1161,19 +1148,19 @@ private:
 
 void findExplicitReferences(const Stmt *S,
                             llvm::function_ref<void(ReferenceLoc)> Out,
-                            const HeuristicResolver *Resolver) {
+                            const HeuristicResolver &Resolver) {
   assert(S);
   ExplicitReferenceCollector(Out, Resolver).TraverseStmt(const_cast<Stmt *>(S));
 }
 void findExplicitReferences(const Decl *D,
                             llvm::function_ref<void(ReferenceLoc)> Out,
-                            const HeuristicResolver *Resolver) {
+                            const HeuristicResolver &Resolver) {
   assert(D);
   ExplicitReferenceCollector(Out, Resolver).TraverseDecl(const_cast<Decl *>(D));
 }
 void findExplicitReferences(const ASTContext &AST,
                             llvm::function_ref<void(ReferenceLoc)> Out,
-                            const HeuristicResolver *Resolver) {
+                            const HeuristicResolver &Resolver) {
   ExplicitReferenceCollector(Out, Resolver)
       .TraverseAST(const_cast<ASTContext &>(AST));
 }
diff --git a/clang-tools-extra/clangd/FindTarget.h b/clang-tools-extra/clangd/FindTarget.h
index b41c54709510..b5d10ea8be18 100644
--- a/clang-tools-extra/clangd/FindTarget.h
+++ b/clang-tools-extra/clangd/FindTarget.h
@@ -81,14 +81,14 @@ class DeclRelationSet;
 /// FIXME: some AST nodes cannot be DynTypedNodes, these cannot be specified.
 llvm::SmallVector<const NamedDecl *, 1>
 targetDecl(const DynTypedNode &, DeclRelationSet Mask,
-           const HeuristicResolver *Resolver);
+           const HeuristicResolver &Resolver);
 
 /// Similar to targetDecl(), however instead of applying a filter, all possible
 /// decls are returned along with their DeclRelationSets.
 /// This is suitable for indexing, where everything is recorded and filtering
 /// is applied later.
 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
-allTargetDecls(const DynTypedNode &, const HeuristicResolver *);
+allTargetDecls(const DynTypedNode &, const HeuristicResolver &);
 
 enum class DeclRelation : unsigned {
   // Template options apply when the declaration is an instantiated template.
@@ -147,13 +147,13 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R);
 /// FIXME: extend to report location information about declaration names too.
 void findExplicitReferences(const Stmt *S,
                             llvm::function_ref<void(ReferenceLoc)> Out,
-                            const HeuristicResolver *Resolver);
+                            const HeuristicResolver &Resolver);
 void findExplicitReferences(const Decl *D,
                             llvm::function_ref<void(ReferenceLoc)> Out,
-                            const HeuristicResolver *Resolver);
+                            const HeuristicResolver &Resolver);
 void findExplicitReferences(const ASTContext &AST,
                             llvm::function_ref<void(ReferenceLoc)> Out,
-                            const HeuristicResolver *Resolver);
+                            const HeuristicResolver &Resolver);
 
 /// Find declarations explicitly referenced in the source code defined by \p N.
 /// For templates, will prefer to return a template instantiation whenever
@@ -166,7 +166,7 @@ void findExplicitReferences(const ASTContext &AST,
 /// \p Mask should not contain TemplatePattern or TemplateInstantiation.
 llvm::SmallVector<const NamedDecl *, 1>
 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask,
-                         const HeuristicResolver *Resolver);
+                         const HeuristicResolver &Resolver);
 
 // Boring implementation details of bitfield.
 
diff --git a/clang-tools-extra/clangd/HeuristicResolver.cpp b/clang-tools-extra/clangd/HeuristicResolver.cpp
index 26d54200eeff..f51337acc722 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.cpp
+++ b/clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -7,10 +7,15 @@
 //===----------------------------------------------------------------------===//
 
 #include "HeuristicResolver.h"
+#include "AST.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/CXXInheritance.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 
 namespace clang {
@@ -27,7 +32,9 @@ namespace {
 // nodes that have already been seen to avoid infinite recursion.
 class HeuristicResolverImpl {
 public:
-  HeuristicResolverImpl(ASTContext &Ctx) : Ctx(Ctx) {}
+  HeuristicResolverImpl(const ASTContext &Ctx,
+                        const DeclContext *EnclosingDecl = nullptr)
+      : Ctx(Ctx), EnclosingDecl(EnclosingDecl) {}
 
   // These functions match the public interface of HeuristicResolver
   // (but aren't const since they may modify the recursion protection sets).
@@ -47,7 +54,8 @@ public:
   const Type *getPointeeType(const Type *T);
 
 private:
-  ASTContext &Ctx;
+  const ASTContext &Ctx;
+  const DeclContext *EnclosingDecl;
 
   // Recursion protection sets
   llvm::SmallSet<const DependentNameType *, 4> SeenDependentNameTypes;
@@ -106,7 +114,7 @@ const auto TemplateFilter = [](const NamedDecl *D) {
 };
 
 const Type *resolveDeclsToType(const std::vector<const NamedDecl *> &Decls,
-                               ASTContext &Ctx) {
+                               const ASTContext &Ctx) {
   if (Decls.size() != 1) // Names an overload set -- just bail.
     return nullptr;
   if (const auto *TD = dyn_cast<TypeDecl>(Decls[0])) {
@@ -118,6 +126,108 @@ const Type *resolveDeclsToType(const std::vector<const NamedDecl *> &Decls,
   return nullptr;
 }
 
+// Visitor that helps to extract deduced type from instantiated entities.
+// This merely performs the source location comparison against each Decl
+// until it finds a Decl with the same location as the
+// dependent one. Its associated type will then be extracted.
+struct InstantiatedDeclVisitor : RecursiveASTVisitor<InstantiatedDeclVisitor> {
+
+  InstantiatedDeclVisitor(NamedDecl *DependentDecl)
+      : DependentDecl(DependentDecl) {}
+
+  bool shouldVisitTemplateInstantiations() const { return true; }
+
+  bool shouldVisitLambdaBody() const { return true; }
+
+  bool shouldVisitImplicitCode() const { return true; }
+
+  template <typename D> bool onDeclVisited(D *MaybeInstantiated) {
+    if (MaybeInstantiated->getDeclContext()->isDependentContext())
+      return true;
+    auto *Dependent = dyn_cast<D>(DependentDecl);
+    if (!Dependent)
+      return true;
+    auto LHS = MaybeInstantiated->getTypeSourceInfo(),
+         RHS = Dependent->getTypeSourceInfo();
+    if (!LHS || !RHS)
+      return true;
+    if (LHS->getTypeLoc().getSourceRange() !=
+        RHS->getTypeLoc().getSourceRange())
+      return true;
+    DeducedType = MaybeInstantiated->getType();
+    return false;
+  }
+
+  bool VisitFieldDecl(FieldDecl *FD) { return onDeclVisited(FD); }
+
+  bool VisitVarDecl(VarDecl *VD) { return onDeclVisited(VD); }
+
+  NamedDecl *DependentDecl;
+  QualType DeducedType;
+};
+
+/// Attempt to resolve the dependent type from the surrounding context for which
+/// a single instantiation is available.
+const Type *
+resolveTypeFromInstantiatedTemplate(const DeclContext *DC,
+                                    const CXXDependentScopeMemberExpr *Expr) {
+
+  std::optional<DynTypedNode> Node =
+      getOnlyInstantiatedNode(DC, DynTypedNode::create(*Expr));
+  if (!Node)
+    return nullptr;
+
+  if (auto *ME = Node->get<MemberExpr>())
+    return ME->getBase()->getType().getTypePtrOrNull();
+
+  return nullptr;
+
+  if (Expr->isImplicitAccess())
+    return nullptr;
+
+  auto *Base = Expr->getBase();
+  NamedDecl *ND = nullptr;
+  if (auto *CXXMember = dyn_cast<MemberExpr>(Base))
+    ND = CXXMember->getMemberDecl();
+
+  if (auto *DRExpr = dyn_cast<DeclRefExpr>(Base))
+    ND = DRExpr->getFoundDecl();
+
+  // FIXME: Handle CXXUnresolvedConstructExpr. This kind of type doesn't have
+  // available Decls to be matched against. Which inhibits the current heuristic
+  // from resolving expressions such as `T().fo^o()`, where T is a
+  // single-instantiated template parameter.
+  if (!ND)
+    return nullptr;
+
+  NamedDecl *Instantiation = nullptr;
+
+  // Find out a single instantiation that we can start with. The enclosing
+  // context for the current Decl might not be a templated entity (e.g. a member
+  // function inside a class template), hence we shall walk up the decl
+  // contexts first.
+  for (auto *EnclosingContext = ND->getDeclContext(); EnclosingContext;
+       EnclosingContext = EnclosingContext->getParent()) {
+    if (auto *ND = dyn_cast<NamedDecl>(EnclosingContext)) {
+      Instantiation = getOnlyInstantiation(ND);
+      if (Instantiation)
+        break;
+    }
+  }
+
+  if (!Instantiation)
+    return nullptr;
+
+  // This will traverse down the instantiation entity, visit each Decl, and
+  // extract the deduced type for the undetermined Decl `ND`.
+  InstantiatedDeclVisitor Visitor(ND);
+  Visitor.TraverseDecl(Instantiation);
+
+  return Visitor.DeducedType.getTypePtrOrNull();
+}
+
+} // namespace
+
 // Helper function for HeuristicResolver::resolveDependentMember()
 // which takes a possibly-dependent type `T` and heuristically
 // resolves it to a CXXRecordDecl in which we can try name lookup.
@@ -220,8 +330,14 @@ std::vector<const NamedDecl *> HeuristicResolverImpl::resolveMemberExpr(
   if (ME->isArrow()) {
     BaseType = getPointeeType(BaseType);
   }
+
   if (!BaseType)
     return {};
+
+  if (BaseType->isDependentType())
+    if (auto *MaybeResolved = resolveTypeFromInstantiatedTemplate(EnclosingDecl, ME))
+      BaseType = MaybeResolved;
+
   if (const auto *BT = BaseType->getAs<BuiltinType>()) {
     // If BaseType is the type of a dependent expression, it's just
     // represented as BuiltinType::Dependent which gives us no information. We
@@ -417,43 +533,45 @@ std::vector<const NamedDecl *> HeuristicResolverImpl::resolveDependentMember(
   }
   return {};
 }
-} // namespace
 
 std::vector<const NamedDecl *> HeuristicResolver::resolveMemberExpr(
     const CXXDependentScopeMemberExpr *ME) const {
-  return HeuristicResolverImpl(Ctx).resolveMemberExpr(ME);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl).resolveMemberExpr(ME);
 }
 std::vector<const NamedDecl *> HeuristicResolver::resolveDeclRefExpr(
     const DependentScopeDeclRefExpr *RE) const {
-  return HeuristicResolverImpl(Ctx).resolveDeclRefExpr(RE);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl).resolveDeclRefExpr(RE);
 }
 std::vector<const NamedDecl *>
 HeuristicResolver::resolveTypeOfCallExpr(const CallExpr *CE) const {
-  return HeuristicResolverImpl(Ctx).resolveTypeOfCallExpr(CE);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl).resolveTypeOfCallExpr(CE);
 }
 std::vector<const NamedDecl *>
 HeuristicResolver::resolveCalleeOfCallExpr(const CallExpr *CE) const {
-  return HeuristicResolverImpl(Ctx).resolveCalleeOfCallExpr(CE);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl).resolveCalleeOfCallExpr(CE);
 }
 std::vector<const NamedDecl *> HeuristicResolver::resolveUsingValueDecl(
     const UnresolvedUsingValueDecl *UUVD) const {
-  return HeuristicResolverImpl(Ctx).resolveUsingValueDecl(UUVD);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl).resolveUsingValueDecl(UUVD);
 }
 std::vector<const NamedDecl *> HeuristicResolver::resolveDependentNameType(
     const DependentNameType *DNT) const {
-  return HeuristicResolverImpl(Ctx).resolveDependentNameType(DNT);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl)
+      .resolveDependentNameType(DNT);
 }
 std::vector<const NamedDecl *>
 HeuristicResolver::resolveTemplateSpecializationType(
     const DependentTemplateSpecializationType *DTST) const {
-  return HeuristicResolverImpl(Ctx).resolveTemplateSpecializationType(DTST);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl)
+      .resolveTemplateSpecializationType(DTST);
 }
 const Type *HeuristicResolver::resolveNestedNameSpecifierToType(
     const NestedNameSpecifier *NNS) const {
-  return HeuristicResolverImpl(Ctx).resolveNestedNameSpecifierToType(NNS);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl)
+      .resolveNestedNameSpecifierToType(NNS);
 }
 const Type *HeuristicResolver::getPointeeType(const Type *T) const {
-  return HeuristicResolverImpl(Ctx).getPointeeType(T);
+  return HeuristicResolverImpl(Ctx, EnclosingDecl).getPointeeType(T);
 }
 
 } // namespace clangd
diff --git a/clang-tools-extra/clangd/HeuristicResolver.h b/clang-tools-extra/clangd/HeuristicResolver.h
index dcc063bbc4ad..261dcff13856 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.h
+++ b/clang-tools-extra/clangd/HeuristicResolver.h
@@ -45,7 +45,9 @@ namespace clangd {
 // not a specialization. More advanced heuristics may be added in the future.
 class HeuristicResolver {
 public:
-  HeuristicResolver(ASTContext &Ctx) : Ctx(Ctx) {}
+  HeuristicResolver(const ASTContext &Ctx,
+                    const DeclContext *EnclosingDecl = nullptr)
+      : Ctx(Ctx), EnclosingDecl(EnclosingDecl) {}
 
   // Try to heuristically resolve certain types of expressions, declarations, or
   // types to one or more likely-referenced declarations.
@@ -76,7 +78,45 @@ public:
   const Type *getPointeeType(const Type *T) const;
 
 private:
-  ASTContext &Ctx;
+  const ASTContext &Ctx;
+  const DeclContext *EnclosingDecl;
+
+  // Given a tag-decl type and a member name, heuristically resolve the
+  // name to one or more declarations.
+  // The current heuristic is simply to look up the name in the primary
+  // template. This is a heuristic because the template could potentially
+  // have specializations that declare different members.
+  // Multiple declarations could be returned if the name is overloaded
+  // (e.g. an overloaded method in the primary template).
+  // This heuristic will give the desired answer in many cases, e.g.
+  // for a call to vector<T>::size().
+  std::vector<const NamedDecl *> resolveDependentMember(
+      const Type *T, DeclarationName Name,
+      llvm::function_ref<bool(const NamedDecl *ND)> Filter) const;
+
+  // Try to heuristically resolve the type of a possibly-dependent expression
+  // `E`.
+  const Type *resolveExprToType(const Expr *E) const;
+  std::vector<const NamedDecl *> resolveExprToDecls(const Expr *E) const;
+
+  // Helper function for HeuristicResolver::resolveDependentMember()
+  // which takes a possibly-dependent type `T` and heuristically
+  // resolves it to a CXXRecordDecl in which we can try name lookup.
+  CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) const;
+
+  // This is a reimplementation of CXXRecordDecl::lookupDependentName()
+  // so that the implementation can call into other HeuristicResolver helpers.
+  // FIXME: Once HeuristicResolver is upstreamed to the clang libraries
+  // (https://github.com/clangd/clangd/discussions/1662),
+  // CXXRecordDecl::lookupDepenedentName() can be removed, and its call sites
+  // can be modified to benefit from the more comprehensive heuristics offered
+  // by HeuristicResolver instead.
+  std::vector<const NamedDecl *> lookupDependentName(
+      CXXRecordDecl *RD, DeclarationName Name,
+      llvm::function_ref<bool(const NamedDecl *ND)> Filter) const;
+  bool findOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
+                                            CXXBasePath &Path,
+                                            DeclarationName Name) const;
 };
 
 } // namespace clangd
diff --git a/clang-tools-extra/clangd/Hover.cpp b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b..2232cd81af87 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -1358,8 +1358,9 @@ std::optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
         SelectionTree::createRight(AST.getASTContext(), TB, Offset, Offset);
     if (const SelectionTree::Node *N = ST.commonAncestor()) {
       // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
-      auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias,
-                                            AST.getHeuristicResolver());
+      auto Decls = explicitReferenceTargets(
+          N->ASTNode, DeclRelation::Alias,
+          AST.getHeuristicResolver(&N->getDeclContext()));
       if (const auto *DeclToUse = pickDeclToUse(Decls)) {
         HoverCountMetric.record(1, "decl");
         HI = getHoverContents(DeclToUse, PP, Index, TB);
diff --git a/clang-tools-extra/clangd/InlayHints.cpp b/clang-tools-extra/clangd/InlayHints.cpp
index a0ebc631ef82..7cfcfe0c9629 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -464,7 +464,7 @@ public:
         isa<UserDefinedLiteral>(E))
       return true;
 
-    auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
+    auto CalleeDecls = Resolver.resolveCalleeOfCallExpr(E);
     if (CalleeDecls.size() != 1)
       return true;
 
@@ -1108,7 +1108,7 @@ private:
   std::optional<Range> RestrictRange;
   FileID MainFileID;
   StringRef MainFileBuf;
-  const HeuristicResolver *Resolver;
+  HeuristicResolver Resolver;
   PrintingPolicy TypeHintPolicy;
 };
 
diff --git a/clang-tools-extra/clangd/ParsedAST.cpp b/clang-tools-extra/clangd/ParsedAST.cpp
index 862f06196a71..a6c51bb6f58e 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -841,8 +841,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version,
       Tokens(std::move(Tokens)), Macros(std::move(Macros)),
       Marks(std::move(Marks)), Diags(std::move(Diags)),
       LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
-      Includes(std::move(Includes)), PI(std::move(PI)),
-      Resolver(std::make_unique<HeuristicResolver>(getASTContext())) {
+      Includes(std::move(Includes)), PI(std::move(PI)) {
   assert(this->Clang);
   assert(this->Action);
 }
diff --git a/clang-tools-extra/clangd/ParsedAST.h b/clang-tools-extra/clangd/ParsedAST.h
index 63e564bd68a7..31fb885e34c8 100644
--- a/clang-tools-extra/clangd/ParsedAST.h
+++ b/clang-tools-extra/clangd/ParsedAST.h
@@ -24,6 +24,7 @@
 #include "Compiler.h"
 #include "Diagnostics.h"
 #include "Headers.h"
+#include "HeuristicResolver.h"
 #include "Preamble.h"
 #include "clang-include-cleaner/Record.h"
 #include "support/Path.h"
@@ -116,8 +117,9 @@ public:
   /// AST. Might be std::nullopt if no Preamble is used.
   std::optional<llvm::StringRef> preambleVersion() const;
 
-  const HeuristicResolver *getHeuristicResolver() const {
-    return Resolver.get();
+  HeuristicResolver
+  getHeuristicResolver(const DeclContext *EnclosingDecl = nullptr) const {
+    return HeuristicResolver(getASTContext(), EnclosingDecl);
   }
 
 private:
@@ -158,7 +160,6 @@ private:
   std::vector<Decl *> LocalTopLevelDecls;
   IncludeStructure Includes;
   include_cleaner::PragmaIncludes PI;
-  std::unique_ptr<HeuristicResolver> Resolver;
 };
 
 } // namespace clangd
diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 08f99e11ac9b..28aeb50a7edf 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -95,9 +95,9 @@ bool isUniqueDefinition(const NamedDecl *Decl) {
 }
 
 std::optional<HighlightingKind> kindForType(const Type *TP,
-                                            const HeuristicResolver *Resolver);
+                                            const HeuristicResolver &Resolver);
 std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
-                                            const HeuristicResolver *Resolver) {
+                                            const HeuristicResolver &Resolver) {
   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
     if (auto *Target = USD->getTargetDecl())
       D = Target;
@@ -147,10 +147,9 @@ std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
   if (auto *VD = dyn_cast<VarDecl>(D)) {
     if (isa<ImplicitParamDecl>(VD)) // e.g. ObjC Self
       return std::nullopt;
-    return VD->isStaticDataMember()
-               ? HighlightingKind::StaticField
-               : VD->isLocalVarDecl() ? HighlightingKind::LocalVariable
-                                      : HighlightingKind::Variable;
+    return VD->isStaticDataMember() ? HighlightingKind::StaticField
+           : VD->isLocalVarDecl()   ? HighlightingKind::LocalVariable
+                                    : HighlightingKind::Variable;
   }
   if (const auto *BD = dyn_cast<BindingDecl>(D))
     return BD->getDeclContext()->isFunctionOrMethod()
@@ -169,7 +168,7 @@ std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
   if (isa<LabelDecl>(D))
     return HighlightingKind::Label;
   if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
-    auto Targets = Resolver->resolveUsingValueDecl(UUVD);
+    auto Targets = Resolver.resolveUsingValueDecl(UUVD);
     if (!Targets.empty() && Targets[0] != UUVD) {
       return kindForDecl(Targets[0], Resolver);
     }
@@ -178,7 +177,7 @@ std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
   return std::nullopt;
 }
 std::optional<HighlightingKind> kindForType(const Type *TP,
-                                            const HeuristicResolver *Resolver) {
+                                            const HeuristicResolver &Resolver) {
   if (!TP)
     return std::nullopt;
   if (TP->isBuiltinType()) // Builtins are special, they do not have decls.
@@ -416,10 +415,10 @@ private:
 /// Consumes source locations and maps them to text ranges for highlightings.
 class HighlightingsBuilder {
 public:
-  HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter)
+  HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter,
+                       const HeuristicResolver &Resolver)
       : TB(AST.getTokens()), SourceMgr(AST.getSourceManager()),
-        LangOpts(AST.getLangOpts()), Filter(Filter),
-        Resolver(AST.getHeuristicResolver()) {}
+        LangOpts(AST.getLangOpts()), Filter(Filter), Resolver(Resolver) {}
 
   HighlightingToken &addToken(SourceLocation Loc, HighlightingKind Kind) {
     auto Range = getRangeForSourceLocation(Loc);
@@ -568,7 +567,7 @@ public:
     return WithInactiveLines;
   }
 
-  const HeuristicResolver *getResolver() const { return Resolver; }
+  const HeuristicResolver &getResolver() const { return Resolver; }
 
 private:
   std::optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
@@ -590,7 +589,7 @@ private:
   HighlightingFilter Filter;
   std::vector<HighlightingToken> Tokens;
   std::map<Range, llvm::SmallVector<HighlightingModifier, 1>> ExtraModifiers;
-  const HeuristicResolver *Resolver;
+  const HeuristicResolver &Resolver;
   // returned from addToken(InvalidLoc)
   HighlightingToken InvalidHighlightingToken;
 };
@@ -1151,7 +1150,7 @@ getSemanticHighlightings(ParsedAST &AST, bool IncludeInactiveRegionTokens) {
   if (!IncludeInactiveRegionTokens)
     Filter.disableKind(HighlightingKind::InactiveCode);
   // Add highlightings for AST nodes.
-  HighlightingsBuilder Builder(AST, Filter);
+  HighlightingsBuilder Builder(AST, Filter, AST.getHeuristicResolver());
   // Highlight 'decltype' and 'auto' as their underlying types.
   CollectExtraHighlightings(Builder).TraverseAST(C);
   // Highlight all decls and references coming from the AST.
@@ -1517,9 +1516,8 @@ llvm::StringRef toSemanticTokenModifier(HighlightingModifier Modifier) {
   llvm_unreachable("unhandled HighlightingModifier");
 }
 
-std::vector<SemanticTokensEdit>
-diffTokens(llvm::ArrayRef<SemanticToken> Old,
-           llvm::ArrayRef<SemanticToken> New) {
+std::vector<SemanticTokensEdit> diffTokens(llvm::ArrayRef<SemanticToken> Old,
+                                           llvm::ArrayRef<SemanticToken> New) {
   // For now, just replace everything from the first-last modification.
   // FIXME: use a real diff instead, this is bad with include-insertion.
 
diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp
index cd909266489a..dea06fca2f82 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -188,7 +188,8 @@ getDeclAtPositionWithRelations(ParsedAST &AST, SourceLocation Pos,
       // This makes the `override` hack work.
       if (N->ASTNode.get<Attr>() && N->Parent)
         N = N->Parent;
-      llvm::copy_if(allTargetDecls(N->ASTNode, AST.getHeuristicResolver()),
+      llvm::copy_if(allTargetDecls(N->ASTNode, AST.getHeuristicResolver(
+                                                   &N->getDeclContext())),
                     std::back_inserter(Result),
                     [&](auto &Entry) { return !(Entry.second & ~Relations); });
     }
@@ -1243,7 +1244,8 @@ std::vector<DocumentHighlight> findDocumentHighlights(ParsedAST &AST,
       DeclRelationSet Relations =
           DeclRelation::TemplatePattern | DeclRelation::Alias;
       auto TargetDecls =
-          targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
+          targetDecl(N->ASTNode, Relations,
+                     AST.getHeuristicResolver(&N->getDeclContext()));
       if (!TargetDecls.empty()) {
         // FIXME: we may get multiple DocumentHighlights with the same location
         // and different kinds, deduplicate them.
@@ -2014,8 +2016,8 @@ static QualType typeForNode(const SelectionTree::Node *N) {
 
 // Given a type targeted by the cursor, return one or more types that are more interesting
 // to target.
-static void unwrapFindType(
-    QualType T, const HeuristicResolver* H, llvm::SmallVector<QualType>& Out) {
+static void unwrapFindType(QualType T, const HeuristicResolver &H,
+                           llvm::SmallVector<QualType> &Out) {
   if (T.isNull())
     return;
 
@@ -2043,18 +2045,18 @@ static void unwrapFindType(
   }
 
   // For smart pointer types, add the underlying type
-  if (H)
-    if (const auto* PointeeType = H->getPointeeType(T.getNonReferenceType().getTypePtr())) {
-        unwrapFindType(QualType(PointeeType, 0), H, Out);
-        return Out.push_back(T);
-    }
+  if (const auto *PointeeType =
+          H.getPointeeType(T.getNonReferenceType().getTypePtr())) {
+    unwrapFindType(QualType(PointeeType, 0), H, Out);
+    return Out.push_back(T);
+  }
 
   return Out.push_back(T);
 }
 
 // Convenience overload, to allow calling this without the out-parameter
-static llvm::SmallVector<QualType> unwrapFindType(
-    QualType T, const HeuristicResolver* H) {
+static llvm::SmallVector<QualType> unwrapFindType(QualType T,
+                                                  const HeuristicResolver &H) {
   llvm::SmallVector<QualType> Result;
   unwrapFindType(T, H, Result);
   return Result;
@@ -2076,10 +2078,11 @@ std::vector<LocatedSymbol> findType(ParsedAST &AST, Position Pos,
     std::vector<LocatedSymbol> LocatedSymbols;
 
     // NOTE: unwrapFindType might return duplicates for something like
-    // unique_ptr<unique_ptr<T>>. Let's *not* remove them, because it gives you some
-    // information about the type you may have not known before
-    // (since unique_ptr<unique_ptr<T>> != unique_ptr<T>).
-    for (const QualType& Type : unwrapFindType(typeForNode(N), AST.getHeuristicResolver()))
+    // unique_ptr<unique_ptr<T>>. Let's *not* remove them, because it gives you
+    // some information about the type you may have not known before (since
+    // unique_ptr<unique_ptr<T>> != unique_ptr<T>).
+    for (const QualType &Type : unwrapFindType(
+             typeForNode(N), AST.getHeuristicResolver(&N->getDeclContext())))
       llvm::copy(locateSymbolForType(AST, Type, Index),
                  std::back_inserter(LocatedSymbols));
 
diff --git a/clang-tools-extra/clangd/refactor/Rename.cpp b/clang-tools-extra/clangd/refactor/Rename.cpp
index 75b30e66d637..2e6d006a48fe 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -168,7 +168,7 @@ llvm::DenseSet<const NamedDecl *> locateDeclAt(ParsedAST &AST,
   for (const NamedDecl *D :
        targetDecl(SelectedNode->ASTNode,
                   DeclRelation::Alias | DeclRelation::TemplatePattern,
-                  AST.getHeuristicResolver())) {
+                  AST.getHeuristicResolver(&SelectedNode->getDeclContext()))) {
     D = pickInterestingTarget(D);
     Result.insert(canonicalRenameDecl(D));
   }
diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
index d6556bba1472..7dc4053c401a 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
@@ -123,7 +123,7 @@ bool checkDeclsAreVisible(const llvm::DenseSet<const Decl *> &DeclRefs,
 // still valid in context of Target.
 llvm::Expected<std::string> qualifyAllDecls(const FunctionDecl *FD,
                                             const FunctionDecl *Target,
-                                            const HeuristicResolver *Resolver) {
+                                            const HeuristicResolver &Resolver) {
   // There are three types of spellings that needs to be qualified in a function
   // body:
   // - Types:       Foo                 -> ns::Foo
@@ -221,7 +221,7 @@ llvm::Expected<std::string> qualifyAllDecls(const FunctionDecl *FD,
 /// \p Dest to be the same as in \p Source.
 llvm::Expected<tooling::Replacements>
 renameParameters(const FunctionDecl *Dest, const FunctionDecl *Source,
-                 const HeuristicResolver *Resolver) {
+                 const HeuristicResolver &Resolver) {
   llvm::DenseMap<const Decl *, std::string> ParamToNewName;
   llvm::DenseMap<const NamedDecl *, std::vector<SourceLocation>> RefLocs;
   auto HandleParam = [&](const NamedDecl *DestParam,
diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index fef827a801c3..47e86ce8dd1d 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -181,7 +181,7 @@ deleteTokensWithKind(const syntax::TokenBuffer &TokBuf, tok::TokenKind Kind,
 llvm::Expected<std::string>
 getFunctionSourceCode(const FunctionDecl *FD, llvm::StringRef TargetNamespace,
                       const syntax::TokenBuffer &TokBuf,
-                      const HeuristicResolver *Resolver) {
+                      const HeuristicResolver &Resolver) {
   auto &AST = FD->getASTContext();
   auto &SM = AST.getSourceManager();
   auto TargetContext = findContextForNS(TargetNamespace, FD->getDeclContext());
diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index 0302839c5825..28c19e097ec9 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -176,7 +176,7 @@ struct ExtractionZone {
   // This performs a partial AST traversal proportional to the size of the
   // enclosing function, so it is possibly expensive.
   bool requiresHoisting(const SourceManager &SM,
-                        const HeuristicResolver *Resolver) const {
+                        const HeuristicResolver &Resolver) const {
     // First find all the declarations that happened inside extraction zone.
     llvm::SmallSet<const Decl *, 1> DeclsInExtZone;
     for (auto *RootStmt : RootStmts) {
diff --git a/clang-tools-extra/clangd/unittests/ASTTests.cpp b/clang-tools-extra/clangd/unittests/ASTTests.cpp
index 3101bf34acd7..229c7aa6681c 100644
--- a/clang-tools-extra/clangd/unittests/ASTTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ASTTests.cpp
@@ -16,6 +16,7 @@
 #include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/Basic/AttrKinds.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/StringRef.h"
@@ -320,6 +321,90 @@ TEST(ClangdAST, GetOnlyInstantiation) {
   }
 }
 
+TEST(ClangdAST, DISABLED_GetOnlyInstantiationForMemberFunction) {
+  struct {
+    const char *Code;
+    const char *MemberTemplate;
+    const char *ExpectedInstantiation;
+  } Cases[] = {
+      {
+          R"cpp(
+      template <class T> struct Foo {
+        template <class U> struct Bar {
+          U Baz(T);
+        };
+      };
+      double X = Foo<int>::Bar<double>().Baz(3);
+      )cpp",
+          "Baz",
+          "double Baz(int)",
+      },
+      {
+          R"cpp(
+      template <class T> struct Foo {
+        struct Bar {
+          template <class U> U Baz(T);
+        };
+      };
+      double X = Foo<int>::Bar().Baz<double>(3);
+      )cpp",
+          "Baz",
+          "template<> double Baz<double>(int)",
+      },
+      {
+          R"cpp(
+      struct Foo {
+        struct Bar {
+          template <class T> T Baz(T);
+        };
+      };
+      int X = Foo::Bar().Baz(3);
+      )cpp",
+          "Baz",
+          "template<> int Baz<int>(int)",
+      },
+      {
+          R"cpp(
+      struct Foo {
+        template <class T> struct Bar {
+          template <class U> static U Baz(T);
+        };
+      };
+      int X = Foo::Bar<int>::Baz<double>(3);
+      )cpp",
+          "Baz",
+          "template<> static double Baz<double>(int)",
+      },
+
+  };
+  for (const auto &Case : Cases) {
+    SCOPED_TRACE(Case.Code);
+    auto TU = TestTU::withCode(Case.Code);
+    TU.ExtraArgs.push_back("-std=c++20");
+    auto AST = TU.build();
+    PrintingPolicy PP = AST.getASTContext().getPrintingPolicy();
+    PP.TerseOutput = true;
+    std::string Name;
+    if (auto *Result = getOnlyInstantiationForMemberFunction(
+            dyn_cast_if_present<CXXMethodDecl>(
+                &findDecl(AST, [&](const NamedDecl &D) {
+                  auto *MD = dyn_cast<CXXMethodDecl>(&D);
+                  IdentifierInfo *Id = D.getIdentifier();
+                  if (!MD || !Id)
+                    return false;
+                  return MD->isDependentContext() &&
+                         Id->getName() == Case.MemberTemplate;
+                })))) {
+      llvm::raw_string_ostream OS(Name);
+      Result->print(OS, PP);
+    }
+    if (Case.ExpectedInstantiation)
+      EXPECT_EQ(Case.ExpectedInstantiation, Name);
+    else
+      EXPECT_THAT(Name, IsEmpty());
+  }
+}
+
 TEST(ClangdAST, GetContainedAutoParamType) {
   auto TU = TestTU::withCode(R"cpp(
     int withAuto(
diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 0af6036734ba..3e7da83a31c3 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -86,8 +86,8 @@ protected:
     EXPECT_EQ(N->kind(), NodeType) << Selection;
 
     std::vector<PrintedDecl> ActualDecls;
-    for (const auto &Entry :
-         allTargetDecls(N->ASTNode, AST.getHeuristicResolver()))
+    for (const auto &Entry : allTargetDecls(
+             N->ASTNode, AST.getHeuristicResolver(&N->getDeclContext())))
       ActualDecls.emplace_back(Entry.first, Entry.second);
     return ActualDecls;
   }
diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index f53cbf01b799..1c800ea79161 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1222,6 +1222,42 @@ TEST(LocateSymbol, TextualSmoke) {
                         hasID(getSymbolID(&findDecl(AST, "MyClass"))))));
 }
 
+TEST(LocateSymbol, DISABLED_DeduceDependentTypeFromSingleInstantiation) {
+  Annotations T(R"cpp(
+    struct Widget {
+      int $range_1[[method]](int);
+    };
+    template <class T> struct A {
+      template <class U> struct B {
+        template <class V> T foo(U, V arg) {
+          V copy;
+          int not_used = copy.$point_1^method(T{});
+          not_used = V().$point_2^method(T{});
+          auto lambda = [](auto w) {
+            return w.$point_3^method(T{});
+          };
+          lambda(copy);
+          arg.$point_4^method(T{});
+        }
+      };
+    };
+    int main() {
+      int X = A<int>::B<double>().foo(3.14, Widget{});
+    }
+  )cpp");
+
+  auto TU = TestTU::withCode(T.code());
+  auto AST = TU.build();
+  EXPECT_THAT(locateSymbolAt(AST, T.point("point_1")),
+              ElementsAre(sym("method", T.range("range_1"), std::nullopt)));
+  EXPECT_THAT(locateSymbolAt(AST, T.point("point_2")),
+              ElementsAre(sym("method", T.range("range_1"), std::nullopt)));
+  EXPECT_THAT(locateSymbolAt(AST, T.point("point_3")),
+              ElementsAre(sym("method", T.range("range_1"), std::nullopt)));
+  EXPECT_THAT(locateSymbolAt(AST, T.point("point_4")),
+              ElementsAre(sym("method", T.range("range_1"), std::nullopt)));
+}
+
 TEST(LocateSymbol, Textual) {
   const char *Tests[] = {
       R"cpp(// Comment