CXXInheritance.cpp 25 KB

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