CXXInheritance.cpp 26 KB

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