1 //===------ CXXInheritance.cpp - C++ Inheritance ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides routines that help analyzing C++ inheritance hierarchies.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/CXXInheritance.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "llvm/ADT/SetVector.h"
19 #include <algorithm>
20 
21 using namespace clang;
22 
23 /// \brief Computes the set of declarations referenced by these base
24 /// paths.
25 void CXXBasePaths::ComputeDeclsFound() {
26   assert(NumDeclsFound == 0 && !DeclsFound &&
27          "Already computed the set of declarations");
28 
29   llvm::SetVector<NamedDecl *, SmallVector<NamedDecl *, 8> > Decls;
30   for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
31     Decls.insert(Path->Decls.front());
32 
33   NumDeclsFound = Decls.size();
34   DeclsFound = llvm::make_unique<NamedDecl *[]>(NumDeclsFound);
35   std::copy(Decls.begin(), Decls.end(), DeclsFound.get());
36 }
37 
38 CXXBasePaths::decl_range CXXBasePaths::found_decls() {
39   if (NumDeclsFound == 0)
40     ComputeDeclsFound();
41 
42   return decl_range(decl_iterator(DeclsFound.get()),
43                     decl_iterator(DeclsFound.get() + NumDeclsFound));
44 }
45 
46 /// isAmbiguous - Determines whether the set of paths provided is
47 /// ambiguous, i.e., there are two or more paths that refer to
48 /// different base class subobjects of the same type. BaseType must be
49 /// an unqualified, canonical class type.
50 bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
51   BaseType = BaseType.getUnqualifiedType();
52   std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
53   return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
54 }
55 
56 /// clear - Clear out all prior path information.
57 void CXXBasePaths::clear() {
58   Paths.clear();
59   ClassSubobjects.clear();
60   ScratchPath.clear();
61   DetectedVirtual = nullptr;
62 }
63 
64 /// @brief Swaps the contents of this CXXBasePaths structure with the
65 /// contents of Other.
66 void CXXBasePaths::swap(CXXBasePaths &Other) {
67   std::swap(Origin, Other.Origin);
68   Paths.swap(Other.Paths);
69   ClassSubobjects.swap(Other.ClassSubobjects);
70   std::swap(FindAmbiguities, Other.FindAmbiguities);
71   std::swap(RecordPaths, Other.RecordPaths);
72   std::swap(DetectVirtual, Other.DetectVirtual);
73   std::swap(DetectedVirtual, Other.DetectedVirtual);
74 }
75 
76 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
77   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
78                      /*DetectVirtual=*/false);
79   return isDerivedFrom(Base, Paths);
80 }
81 
82 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
83                                   CXXBasePaths &Paths) const {
84   if (getCanonicalDecl() == Base->getCanonicalDecl())
85     return false;
86 
87   Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
88 
89   const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
90   // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
91   return lookupInBases(
92       [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
93         return FindBaseClass(Specifier, Path, BaseDecl);
94       },
95       Paths);
96 }
97 
98 bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const {
99   if (!getNumVBases())
100     return false;
101 
102   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
103                      /*DetectVirtual=*/false);
104 
105   if (getCanonicalDecl() == Base->getCanonicalDecl())
106     return false;
107 
108   Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
109 
110   const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
111   // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
112   return lookupInBases(
113       [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
114         return FindVirtualBaseClass(Specifier, Path, BaseDecl);
115       },
116       Paths);
117 }
118 
119 bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
120   const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl();
121   return forallBases([TargetDecl](const CXXRecordDecl *Base) {
122     return Base->getCanonicalDecl() != TargetDecl;
123   });
124 }
125 
126 bool
127 CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const {
128   assert(isDependentContext());
129 
130   for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
131     if (CurContext->Equals(this))
132       return true;
133 
134   return false;
135 }
136 
137 bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches,
138                                 bool AllowShortCircuit) const {
139   SmallVector<const CXXRecordDecl*, 8> Queue;
140 
141   const CXXRecordDecl *Record = this;
142   bool AllMatches = true;
143   while (true) {
144     for (const auto &I : Record->bases()) {
145       const RecordType *Ty = I.getType()->getAs<RecordType>();
146       if (!Ty) {
147         if (AllowShortCircuit) return false;
148         AllMatches = false;
149         continue;
150       }
151 
152       CXXRecordDecl *Base =
153             cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
154       if (!Base ||
155           (Base->isDependentContext() &&
156            !Base->isCurrentInstantiation(Record))) {
157         if (AllowShortCircuit) return false;
158         AllMatches = false;
159         continue;
160       }
161 
162       Queue.push_back(Base);
163       if (!BaseMatches(Base)) {
164         if (AllowShortCircuit) return false;
165         AllMatches = false;
166         continue;
167       }
168     }
169 
170     if (Queue.empty())
171       break;
172     Record = Queue.pop_back_val(); // not actually a queue.
173   }
174 
175   return AllMatches;
176 }
177 
178 bool CXXBasePaths::lookupInBases(ASTContext &Context,
179                                  const CXXRecordDecl *Record,
180                                  CXXRecordDecl::BaseMatchesCallback BaseMatches,
181                                  bool LookupInDependent) {
182   bool FoundPath = false;
183 
184   // The access of the path down to this record.
185   AccessSpecifier AccessToHere = ScratchPath.Access;
186   bool IsFirstStep = ScratchPath.empty();
187 
188   for (const auto &BaseSpec : Record->bases()) {
189     // Find the record of the base class subobjects for this type.
190     QualType BaseType =
191         Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType();
192 
193     // C++ [temp.dep]p3:
194     //   In the definition of a class template or a member of a class template,
195     //   if a base class of the class template depends on a template-parameter,
196     //   the base class scope is not examined during unqualified name lookup
197     //   either at the point of definition of the class template or member or
198     //   during an instantiation of the class tem- plate or member.
199     if (!LookupInDependent && BaseType->isDependentType())
200       continue;
201 
202     // Determine whether we need to visit this base class at all,
203     // updating the count of subobjects appropriately.
204     std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
205     bool VisitBase = true;
206     bool SetVirtual = false;
207     if (BaseSpec.isVirtual()) {
208       VisitBase = !Subobjects.first;
209       Subobjects.first = true;
210       if (isDetectingVirtual() && DetectedVirtual == nullptr) {
211         // If this is the first virtual we find, remember it. If it turns out
212         // there is no base path here, we'll reset it later.
213         DetectedVirtual = BaseType->getAs<RecordType>();
214         SetVirtual = true;
215       }
216     } else
217       ++Subobjects.second;
218 
219     if (isRecordingPaths()) {
220       // Add this base specifier to the current path.
221       CXXBasePathElement Element;
222       Element.Base = &BaseSpec;
223       Element.Class = Record;
224       if (BaseSpec.isVirtual())
225         Element.SubobjectNumber = 0;
226       else
227         Element.SubobjectNumber = Subobjects.second;
228       ScratchPath.push_back(Element);
229 
230       // Calculate the "top-down" access to this base class.
231       // The spec actually describes this bottom-up, but top-down is
232       // equivalent because the definition works out as follows:
233       // 1. Write down the access along each step in the inheritance
234       //    chain, followed by the access of the decl itself.
235       //    For example, in
236       //      class A { public: int foo; };
237       //      class B : protected A {};
238       //      class C : public B {};
239       //      class D : private C {};
240       //    we would write:
241       //      private public protected public
242       // 2. If 'private' appears anywhere except far-left, access is denied.
243       // 3. Otherwise, overall access is determined by the most restrictive
244       //    access in the sequence.
245       if (IsFirstStep)
246         ScratchPath.Access = BaseSpec.getAccessSpecifier();
247       else
248         ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
249                                                  BaseSpec.getAccessSpecifier());
250     }
251 
252     // Track whether there's a path involving this specific base.
253     bool FoundPathThroughBase = false;
254 
255     if (BaseMatches(&BaseSpec, ScratchPath)) {
256       // We've found a path that terminates at this base.
257       FoundPath = FoundPathThroughBase = true;
258       if (isRecordingPaths()) {
259         // We have a path. Make a copy of it before moving on.
260         Paths.push_back(ScratchPath);
261       } else if (!isFindingAmbiguities()) {
262         // We found a path and we don't care about ambiguities;
263         // return immediately.
264         return FoundPath;
265       }
266     } else if (VisitBase) {
267       CXXRecordDecl *BaseRecord;
268       if (LookupInDependent) {
269         BaseRecord = nullptr;
270         const TemplateSpecializationType *TST =
271             BaseSpec.getType()->getAs<TemplateSpecializationType>();
272         if (!TST) {
273           if (auto *RT = BaseSpec.getType()->getAs<RecordType>())
274             BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
275         } else {
276           TemplateName TN = TST->getTemplateName();
277           if (auto *TD =
278                   dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()))
279             BaseRecord = TD->getTemplatedDecl();
280         }
281         if (BaseRecord && !BaseRecord->hasDefinition())
282           BaseRecord = nullptr;
283       } else {
284         BaseRecord = cast<CXXRecordDecl>(
285             BaseSpec.getType()->castAs<RecordType>()->getDecl());
286       }
287       if (BaseRecord &&
288           lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) {
289         // C++ [class.member.lookup]p2:
290         //   A member name f in one sub-object B hides a member name f in
291         //   a sub-object A if A is a base class sub-object of B. Any
292         //   declarations that are so hidden are eliminated from
293         //   consideration.
294 
295         // There is a path to a base class that meets the criteria. If we're
296         // not collecting paths or finding ambiguities, we're done.
297         FoundPath = FoundPathThroughBase = true;
298         if (!isFindingAmbiguities())
299           return FoundPath;
300       }
301     }
302 
303     // Pop this base specifier off the current path (if we're
304     // collecting paths).
305     if (isRecordingPaths()) {
306       ScratchPath.pop_back();
307     }
308 
309     // If we set a virtual earlier, and this isn't a path, forget it again.
310     if (SetVirtual && !FoundPathThroughBase) {
311       DetectedVirtual = nullptr;
312     }
313   }
314 
315   // Reset the scratch path access.
316   ScratchPath.Access = AccessToHere;
317 
318   return FoundPath;
319 }
320 
321 bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches,
322                                   CXXBasePaths &Paths,
323                                   bool LookupInDependent) const {
324   // If we didn't find anything, report that.
325   if (!Paths.lookupInBases(getASTContext(), this, BaseMatches,
326                            LookupInDependent))
327     return false;
328 
329   // If we're not recording paths or we won't ever find ambiguities,
330   // we're done.
331   if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
332     return true;
333 
334   // C++ [class.member.lookup]p6:
335   //   When virtual base classes are used, a hidden declaration can be
336   //   reached along a path through the sub-object lattice that does
337   //   not pass through the hiding declaration. This is not an
338   //   ambiguity. The identical use with nonvirtual base classes is an
339   //   ambiguity; in that case there is no unique instance of the name
340   //   that hides all the others.
341   //
342   // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
343   // way to make it any faster.
344   Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) {
345     for (const CXXBasePathElement &PE : Path) {
346       if (!PE.Base->isVirtual())
347         continue;
348 
349       CXXRecordDecl *VBase = nullptr;
350       if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>())
351         VBase = cast<CXXRecordDecl>(Record->getDecl());
352       if (!VBase)
353         break;
354 
355       // The declaration(s) we found along this path were found in a
356       // subobject of a virtual base. Check whether this virtual
357       // base is a subobject of any other path; if so, then the
358       // declaration in this path are hidden by that patch.
359       for (const CXXBasePath &HidingP : Paths) {
360         CXXRecordDecl *HidingClass = nullptr;
361         if (const RecordType *Record =
362                 HidingP.back().Base->getType()->getAs<RecordType>())
363           HidingClass = cast<CXXRecordDecl>(Record->getDecl());
364         if (!HidingClass)
365           break;
366 
367         if (HidingClass->isVirtuallyDerivedFrom(VBase))
368           return true;
369       }
370     }
371     return false;
372   });
373 
374   return true;
375 }
376 
377 bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier,
378                                   CXXBasePath &Path,
379                                   const CXXRecordDecl *BaseRecord) {
380   assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
381          "User data for FindBaseClass is not canonical!");
382   return Specifier->getType()->castAs<RecordType>()->getDecl()
383             ->getCanonicalDecl() == BaseRecord;
384 }
385 
386 bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
387                                          CXXBasePath &Path,
388                                          const CXXRecordDecl *BaseRecord) {
389   assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
390          "User data for FindBaseClass is not canonical!");
391   return Specifier->isVirtual() &&
392          Specifier->getType()->castAs<RecordType>()->getDecl()
393             ->getCanonicalDecl() == BaseRecord;
394 }
395 
396 bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier,
397                                   CXXBasePath &Path,
398                                   DeclarationName Name) {
399   RecordDecl *BaseRecord =
400     Specifier->getType()->castAs<RecordType>()->getDecl();
401 
402   for (Path.Decls = BaseRecord->lookup(Name);
403        !Path.Decls.empty();
404        Path.Decls = Path.Decls.slice(1)) {
405     if (Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
406       return true;
407   }
408 
409   return false;
410 }
411 
412 static bool findOrdinaryMember(RecordDecl *BaseRecord, CXXBasePath &Path,
413                                DeclarationName Name) {
414   const unsigned IDNS = clang::Decl::IDNS_Ordinary | clang::Decl::IDNS_Tag |
415                         clang::Decl::IDNS_Member;
416   for (Path.Decls = BaseRecord->lookup(Name);
417        !Path.Decls.empty();
418        Path.Decls = Path.Decls.slice(1)) {
419     if (Path.Decls.front()->isInIdentifierNamespace(IDNS))
420       return true;
421   }
422 
423   return false;
424 }
425 
426 bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
427                                        CXXBasePath &Path,
428                                        DeclarationName Name) {
429   RecordDecl *BaseRecord =
430       Specifier->getType()->castAs<RecordType>()->getDecl();
431   return findOrdinaryMember(BaseRecord, Path, Name);
432 }
433 
434 bool CXXRecordDecl::FindOrdinaryMemberInDependentClasses(
435     const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
436     DeclarationName Name) {
437   const TemplateSpecializationType *TST =
438       Specifier->getType()->getAs<TemplateSpecializationType>();
439   if (!TST) {
440     auto *RT = Specifier->getType()->getAs<RecordType>();
441     if (!RT)
442       return false;
443     return findOrdinaryMember(RT->getDecl(), Path, Name);
444   }
445   TemplateName TN = TST->getTemplateName();
446   const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
447   if (!TD)
448     return false;
449   CXXRecordDecl *RD = TD->getTemplatedDecl();
450   if (!RD)
451     return false;
452   return findOrdinaryMember(RD, Path, Name);
453 }
454 
455 bool CXXRecordDecl::FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
456                                            CXXBasePath &Path,
457                                            DeclarationName Name) {
458   RecordDecl *BaseRecord =
459       Specifier->getType()->castAs<RecordType>()->getDecl();
460 
461   for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
462        Path.Decls = Path.Decls.slice(1)) {
463     if (Path.Decls.front()->isInIdentifierNamespace(IDNS_OMPReduction))
464       return true;
465   }
466 
467   return false;
468 }
469 
470 bool CXXRecordDecl::
471 FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
472                               CXXBasePath &Path,
473                               DeclarationName Name) {
474   RecordDecl *BaseRecord =
475     Specifier->getType()->castAs<RecordType>()->getDecl();
476 
477   for (Path.Decls = BaseRecord->lookup(Name);
478        !Path.Decls.empty();
479        Path.Decls = Path.Decls.slice(1)) {
480     // FIXME: Refactor the "is it a nested-name-specifier?" check
481     if (isa<TypedefNameDecl>(Path.Decls.front()) ||
482         Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
483       return true;
484   }
485 
486   return false;
487 }
488 
489 std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName(
490     const DeclarationName &Name,
491     llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
492   std::vector<const NamedDecl *> Results;
493   // Lookup in the class.
494   DeclContext::lookup_result DirectResult = lookup(Name);
495   if (!DirectResult.empty()) {
496     for (const NamedDecl *ND : DirectResult) {
497       if (Filter(ND))
498         Results.push_back(ND);
499     }
500     return Results;
501   }
502   // Perform lookup into our base classes.
503   CXXBasePaths Paths;
504   Paths.setOrigin(this);
505   if (!lookupInBases(
506           [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
507             return CXXRecordDecl::FindOrdinaryMemberInDependentClasses(
508                 Specifier, Path, Name);
509           },
510           Paths, /*LookupInDependent=*/true))
511     return Results;
512   for (const NamedDecl *ND : Paths.front().Decls) {
513     if (Filter(ND))
514       Results.push_back(ND);
515   }
516   return Results;
517 }
518 
519 void OverridingMethods::add(unsigned OverriddenSubobject,
520                             UniqueVirtualMethod Overriding) {
521   SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides
522     = Overrides[OverriddenSubobject];
523   if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(),
524                 Overriding) == SubobjectOverrides.end())
525     SubobjectOverrides.push_back(Overriding);
526 }
527 
528 void OverridingMethods::add(const OverridingMethods &Other) {
529   for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
530     for (overriding_const_iterator M = I->second.begin(),
531                                 MEnd = I->second.end();
532          M != MEnd;
533          ++M)
534       add(I->first, *M);
535   }
536 }
537 
538 void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
539   for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
540     I->second.clear();
541     I->second.push_back(Overriding);
542   }
543 }
544 
545 
546 namespace {
547   class FinalOverriderCollector {
548     /// \brief The number of subobjects of a given class type that
549     /// occur within the class hierarchy.
550     llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
551 
552     /// \brief Overriders for each virtual base subobject.
553     llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
554 
555     CXXFinalOverriderMap FinalOverriders;
556 
557   public:
558     ~FinalOverriderCollector();
559 
560     void Collect(const CXXRecordDecl *RD, bool VirtualBase,
561                  const CXXRecordDecl *InVirtualSubobject,
562                  CXXFinalOverriderMap &Overriders);
563   };
564 }
565 
566 void FinalOverriderCollector::Collect(const CXXRecordDecl *RD,
567                                       bool VirtualBase,
568                                       const CXXRecordDecl *InVirtualSubobject,
569                                       CXXFinalOverriderMap &Overriders) {
570   unsigned SubobjectNumber = 0;
571   if (!VirtualBase)
572     SubobjectNumber
573       = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
574 
575   for (const auto &Base : RD->bases()) {
576     if (const RecordType *RT = Base.getType()->getAs<RecordType>()) {
577       const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
578       if (!BaseDecl->isPolymorphic())
579         continue;
580 
581       if (Overriders.empty() && !Base.isVirtual()) {
582         // There are no other overriders of virtual member functions,
583         // so let the base class fill in our overriders for us.
584         Collect(BaseDecl, false, InVirtualSubobject, Overriders);
585         continue;
586       }
587 
588       // Collect all of the overridders from the base class subobject
589       // and merge them into the set of overridders for this class.
590       // For virtual base classes, populate or use the cached virtual
591       // overrides so that we do not walk the virtual base class (and
592       // its base classes) more than once.
593       CXXFinalOverriderMap ComputedBaseOverriders;
594       CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
595       if (Base.isVirtual()) {
596         CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
597         BaseOverriders = MyVirtualOverriders;
598         if (!MyVirtualOverriders) {
599           MyVirtualOverriders = new CXXFinalOverriderMap;
600 
601           // Collect may cause VirtualOverriders to reallocate, invalidating the
602           // MyVirtualOverriders reference. Set BaseOverriders to the right
603           // value now.
604           BaseOverriders = MyVirtualOverriders;
605 
606           Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
607         }
608       } else
609         Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
610 
611       // Merge the overriders from this base class into our own set of
612       // overriders.
613       for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(),
614                                OMEnd = BaseOverriders->end();
615            OM != OMEnd;
616            ++OM) {
617         const CXXMethodDecl *CanonOM
618           = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
619         Overriders[CanonOM].add(OM->second);
620       }
621     }
622   }
623 
624   for (auto *M : RD->methods()) {
625     // We only care about virtual methods.
626     if (!M->isVirtual())
627       continue;
628 
629     CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
630 
631     if (CanonM->begin_overridden_methods()
632                                        == CanonM->end_overridden_methods()) {
633       // This is a new virtual function that does not override any
634       // other virtual function. Add it to the map of virtual
635       // functions for which we are tracking overridders.
636 
637       // C++ [class.virtual]p2:
638       //   For convenience we say that any virtual function overrides itself.
639       Overriders[CanonM].add(SubobjectNumber,
640                              UniqueVirtualMethod(CanonM, SubobjectNumber,
641                                                  InVirtualSubobject));
642       continue;
643     }
644 
645     // This virtual method overrides other virtual methods, so it does
646     // not add any new slots into the set of overriders. Instead, we
647     // replace entries in the set of overriders with the new
648     // overrider. To do so, we dig down to the original virtual
649     // functions using data recursion and update all of the methods it
650     // overrides.
651     typedef llvm::iterator_range<CXXMethodDecl::method_iterator>
652         OverriddenMethods;
653     SmallVector<OverriddenMethods, 4> Stack;
654     Stack.push_back(llvm::make_range(CanonM->begin_overridden_methods(),
655                                      CanonM->end_overridden_methods()));
656     while (!Stack.empty()) {
657       for (const CXXMethodDecl *OM : Stack.pop_back_val()) {
658         const CXXMethodDecl *CanonOM = OM->getCanonicalDecl();
659 
660         // C++ [class.virtual]p2:
661         //   A virtual member function C::vf of a class object S is
662         //   a final overrider unless the most derived class (1.8)
663         //   of which S is a base class subobject (if any) declares
664         //   or inherits another member function that overrides vf.
665         //
666         // Treating this object like the most derived class, we
667         // replace any overrides from base classes with this
668         // overriding virtual function.
669         Overriders[CanonOM].replaceAll(
670                                UniqueVirtualMethod(CanonM, SubobjectNumber,
671                                                    InVirtualSubobject));
672 
673         if (CanonOM->begin_overridden_methods()
674                                        == CanonOM->end_overridden_methods())
675           continue;
676 
677         // Continue recursion to the methods that this virtual method
678         // overrides.
679         Stack.push_back(llvm::make_range(CanonOM->begin_overridden_methods(),
680                                          CanonOM->end_overridden_methods()));
681       }
682     }
683 
684     // C++ [class.virtual]p2:
685     //   For convenience we say that any virtual function overrides itself.
686     Overriders[CanonM].add(SubobjectNumber,
687                            UniqueVirtualMethod(CanonM, SubobjectNumber,
688                                                InVirtualSubobject));
689   }
690 }
691 
692 FinalOverriderCollector::~FinalOverriderCollector() {
693   for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
694          VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
695        VO != VOEnd;
696        ++VO)
697     delete VO->second;
698 }
699 
700 void
701 CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
702   FinalOverriderCollector Collector;
703   Collector.Collect(this, false, nullptr, FinalOverriders);
704 
705   // Weed out any final overriders that come from virtual base class
706   // subobjects that were hidden by other subobjects along any path.
707   // This is the final-overrider variant of C++ [class.member.lookup]p10.
708   for (auto &OM : FinalOverriders) {
709     for (auto &SO : OM.second) {
710       SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second;
711       if (Overriding.size() < 2)
712         continue;
713 
714       auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) {
715         if (!M.InVirtualSubobject)
716           return false;
717 
718         // We have an overriding method in a virtual base class
719         // subobject (or non-virtual base class subobject thereof);
720         // determine whether there exists an other overriding method
721         // in a base class subobject that hides the virtual base class
722         // subobject.
723         for (const UniqueVirtualMethod &OP : Overriding)
724           if (&M != &OP &&
725               OP.Method->getParent()->isVirtuallyDerivedFrom(
726                   M.InVirtualSubobject))
727             return true;
728         return false;
729       };
730 
731       Overriding.erase(
732           std::remove_if(Overriding.begin(), Overriding.end(), IsHidden),
733           Overriding.end());
734     }
735   }
736 }
737 
738 static void
739 AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
740                         CXXIndirectPrimaryBaseSet& Bases) {
741   // If the record has a virtual primary base class, add it to our set.
742   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
743   if (Layout.isPrimaryBaseVirtual())
744     Bases.insert(Layout.getPrimaryBase());
745 
746   for (const auto &I : RD->bases()) {
747     assert(!I.getType()->isDependentType() &&
748            "Cannot get indirect primary bases for class with dependent bases.");
749 
750     const CXXRecordDecl *BaseDecl =
751       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
752 
753     // Only bases with virtual bases participate in computing the
754     // indirect primary virtual base classes.
755     if (BaseDecl->getNumVBases())
756       AddIndirectPrimaryBases(BaseDecl, Context, Bases);
757   }
758 
759 }
760 
761 void
762 CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
763   ASTContext &Context = getASTContext();
764 
765   if (!getNumVBases())
766     return;
767 
768   for (const auto &I : bases()) {
769     assert(!I.getType()->isDependentType() &&
770            "Cannot get indirect primary bases for class with dependent bases.");
771 
772     const CXXRecordDecl *BaseDecl =
773       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
774 
775     // Only bases with virtual bases participate in computing the
776     // indirect primary virtual base classes.
777     if (BaseDecl->getNumVBases())
778       AddIndirectPrimaryBases(BaseDecl, Context, Bases);
779   }
780 }
781