CXXInheritance.cpp 27 KB

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