1 //===------ CXXInheritance.cpp - C++ Inheritance ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides routines that help analyzing C++ inheritance hierarchies.
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/CXXInheritance.h"
14 #include "clang/AST/DeclCXX.h"
18 using namespace clang;
20 /// \brief Computes the set of declarations referenced by these base
22 void CXXBasePaths::ComputeDeclsFound() {
23 assert(NumDeclsFound == 0 && !DeclsFound &&
24 "Already computed the set of declarations");
26 std::set<NamedDecl *> Decls;
27 for (CXXBasePaths::paths_iterator Path = begin(), PathEnd = end();
28 Path != PathEnd; ++Path)
29 Decls.insert(*Path->Decls.first);
31 NumDeclsFound = Decls.size();
32 DeclsFound = new NamedDecl * [NumDeclsFound];
33 std::copy(Decls.begin(), Decls.end(), DeclsFound);
36 CXXBasePaths::decl_iterator CXXBasePaths::found_decls_begin() {
37 if (NumDeclsFound == 0)
42 CXXBasePaths::decl_iterator CXXBasePaths::found_decls_end() {
43 if (NumDeclsFound == 0)
45 return DeclsFound + NumDeclsFound;
48 /// isAmbiguous - Determines whether the set of paths provided is
49 /// ambiguous, i.e., there are two or more paths that refer to
50 /// different base class subobjects of the same type. BaseType must be
51 /// an unqualified, canonical class type.
52 bool CXXBasePaths::isAmbiguous(QualType BaseType) {
53 assert(BaseType.isCanonical() && "Base type must be the canonical type");
54 assert(BaseType.hasQualifiers() == 0 && "Base type must be unqualified");
55 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
56 return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
59 /// clear - Clear out all prior path information.
60 void CXXBasePaths::clear() {
62 ClassSubobjects.clear();
67 /// @brief Swaps the contents of this CXXBasePaths structure with the
68 /// contents of Other.
69 void CXXBasePaths::swap(CXXBasePaths &Other) {
70 std::swap(Origin, Other.Origin);
71 Paths.swap(Other.Paths);
72 ClassSubobjects.swap(Other.ClassSubobjects);
73 std::swap(FindAmbiguities, Other.FindAmbiguities);
74 std::swap(RecordPaths, Other.RecordPaths);
75 std::swap(DetectVirtual, Other.DetectVirtual);
76 std::swap(DetectedVirtual, Other.DetectedVirtual);
79 bool CXXRecordDecl::isDerivedFrom(CXXRecordDecl *Base) const {
80 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
81 /*DetectVirtual=*/false);
82 return isDerivedFrom(Base, Paths);
85 bool CXXRecordDecl::isDerivedFrom(CXXRecordDecl *Base, CXXBasePaths &Paths) const {
86 if (getCanonicalDecl() == Base->getCanonicalDecl())
89 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
90 return lookupInBases(&FindBaseClass, Base->getCanonicalDecl(), Paths);
93 bool CXXRecordDecl::isVirtuallyDerivedFrom(CXXRecordDecl *Base) const {
94 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
95 /*DetectVirtual=*/false);
97 if (getCanonicalDecl() == Base->getCanonicalDecl())
100 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
101 return lookupInBases(&FindVirtualBaseClass, Base->getCanonicalDecl(), Paths);
104 static bool BaseIsNot(const CXXRecordDecl *Base, void *OpaqueTarget) {
105 // OpaqueTarget is a CXXRecordDecl*.
106 return Base->getCanonicalDecl() != (const CXXRecordDecl*) OpaqueTarget;
109 bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
110 return forallBases(BaseIsNot, (void*) Base->getCanonicalDecl());
113 bool CXXRecordDecl::forallBases(ForallBasesCallback *BaseMatches,
115 bool AllowShortCircuit) const {
116 llvm::SmallVector<const CXXRecordDecl*, 8> Queue;
118 const CXXRecordDecl *Record = this;
119 bool AllMatches = true;
121 for (CXXRecordDecl::base_class_const_iterator
122 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
123 const RecordType *Ty = I->getType()->getAs<RecordType>();
125 if (AllowShortCircuit) return false;
130 CXXRecordDecl *Base =
131 cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
133 if (AllowShortCircuit) return false;
138 Queue.push_back(Base);
139 if (!BaseMatches(Base, OpaqueData)) {
140 if (AllowShortCircuit) return false;
146 if (Queue.empty()) break;
147 Record = Queue.back(); // not actually a queue.
154 bool CXXBasePaths::lookupInBases(ASTContext &Context,
155 const CXXRecordDecl *Record,
156 CXXRecordDecl::BaseMatchesCallback *BaseMatches,
158 bool FoundPath = false;
160 // The access of the path down to this record.
161 AccessSpecifier AccessToHere = ScratchPath.Access;
162 bool IsFirstStep = ScratchPath.empty();
164 for (CXXRecordDecl::base_class_const_iterator BaseSpec = Record->bases_begin(),
165 BaseSpecEnd = Record->bases_end();
166 BaseSpec != BaseSpecEnd;
168 // Find the record of the base class subobjects for this type.
169 QualType BaseType = Context.getCanonicalType(BaseSpec->getType())
170 .getUnqualifiedType();
173 // In the definition of a class template or a member of a class template,
174 // if a base class of the class template depends on a template-parameter,
175 // the base class scope is not examined during unqualified name lookup
176 // either at the point of definition of the class template or member or
177 // during an instantiation of the class tem- plate or member.
178 if (BaseType->isDependentType())
181 // Determine whether we need to visit this base class at all,
182 // updating the count of subobjects appropriately.
183 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
184 bool VisitBase = true;
185 bool SetVirtual = false;
186 if (BaseSpec->isVirtual()) {
187 VisitBase = !Subobjects.first;
188 Subobjects.first = true;
189 if (isDetectingVirtual() && DetectedVirtual == 0) {
190 // If this is the first virtual we find, remember it. If it turns out
191 // there is no base path here, we'll reset it later.
192 DetectedVirtual = BaseType->getAs<RecordType>();
198 if (isRecordingPaths()) {
199 // Add this base specifier to the current path.
200 CXXBasePathElement Element;
201 Element.Base = &*BaseSpec;
202 Element.Class = Record;
203 if (BaseSpec->isVirtual())
204 Element.SubobjectNumber = 0;
206 Element.SubobjectNumber = Subobjects.second;
207 ScratchPath.push_back(Element);
209 // Calculate the "top-down" access to this base class.
210 // The spec actually describes this bottom-up, but top-down is
211 // equivalent because the definition works out as follows:
212 // 1. Write down the access along each step in the inheritance
213 // chain, followed by the access of the decl itself.
215 // class A { public: int foo; };
216 // class B : protected A {};
217 // class C : public B {};
218 // class D : private C {};
220 // private public protected public
221 // 2. If 'private' appears anywhere except far-left, access is denied.
222 // 3. Otherwise, overall access is determined by the most restrictive
223 // access in the sequence.
225 ScratchPath.Access = BaseSpec->getAccessSpecifier();
227 ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
228 BaseSpec->getAccessSpecifier());
231 // Track whether there's a path involving this specific base.
232 bool FoundPathThroughBase = false;
234 if (BaseMatches(BaseSpec, ScratchPath, UserData)) {
235 // We've found a path that terminates at this base.
236 FoundPath = FoundPathThroughBase = true;
237 if (isRecordingPaths()) {
238 // We have a path. Make a copy of it before moving on.
239 Paths.push_back(ScratchPath);
240 } else if (!isFindingAmbiguities()) {
241 // We found a path and we don't care about ambiguities;
242 // return immediately.
245 } else if (VisitBase) {
246 CXXRecordDecl *BaseRecord
247 = cast<CXXRecordDecl>(BaseSpec->getType()->getAs<RecordType>()
249 if (lookupInBases(Context, BaseRecord, BaseMatches, UserData)) {
250 // C++ [class.member.lookup]p2:
251 // A member name f in one sub-object B hides a member name f in
252 // a sub-object A if A is a base class sub-object of B. Any
253 // declarations that are so hidden are eliminated from
256 // There is a path to a base class that meets the criteria. If we're
257 // not collecting paths or finding ambiguities, we're done.
258 FoundPath = FoundPathThroughBase = true;
259 if (!isFindingAmbiguities())
264 // Pop this base specifier off the current path (if we're
265 // collecting paths).
266 if (isRecordingPaths()) {
267 ScratchPath.pop_back();
270 // If we set a virtual earlier, and this isn't a path, forget it again.
271 if (SetVirtual && !FoundPathThroughBase) {
276 // Reset the scratch path access.
277 ScratchPath.Access = AccessToHere;
282 bool CXXRecordDecl::lookupInBases(BaseMatchesCallback *BaseMatches,
284 CXXBasePaths &Paths) const {
285 // If we didn't find anything, report that.
286 if (!Paths.lookupInBases(getASTContext(), this, BaseMatches, UserData))
289 // If we're not recording paths or we won't ever find ambiguities,
291 if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
294 // C++ [class.member.lookup]p6:
295 // When virtual base classes are used, a hidden declaration can be
296 // reached along a path through the sub-object lattice that does
297 // not pass through the hiding declaration. This is not an
298 // ambiguity. The identical use with nonvirtual base classes is an
299 // ambiguity; in that case there is no unique instance of the name
300 // that hides all the others.
302 // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
303 // way to make it any faster.
304 for (CXXBasePaths::paths_iterator P = Paths.begin(), PEnd = Paths.end();
305 P != PEnd; /* increment in loop */) {
308 for (CXXBasePath::iterator PE = P->begin(), PEEnd = P->end();
309 PE != PEEnd && !Hidden; ++PE) {
310 if (PE->Base->isVirtual()) {
311 CXXRecordDecl *VBase = 0;
312 if (const RecordType *Record = PE->Base->getType()->getAs<RecordType>())
313 VBase = cast<CXXRecordDecl>(Record->getDecl());
317 // The declaration(s) we found along this path were found in a
318 // subobject of a virtual base. Check whether this virtual
319 // base is a subobject of any other path; if so, then the
320 // declaration in this path are hidden by that patch.
321 for (CXXBasePaths::paths_iterator HidingP = Paths.begin(),
322 HidingPEnd = Paths.end();
323 HidingP != HidingPEnd;
325 CXXRecordDecl *HidingClass = 0;
326 if (const RecordType *Record
327 = HidingP->back().Base->getType()->getAs<RecordType>())
328 HidingClass = cast<CXXRecordDecl>(Record->getDecl());
332 if (HidingClass->isVirtuallyDerivedFrom(VBase)) {
341 P = Paths.Paths.erase(P);
349 bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier,
352 assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
353 "User data for FindBaseClass is not canonical!");
354 return Specifier->getType()->getAs<RecordType>()->getDecl()
355 ->getCanonicalDecl() == BaseRecord;
358 bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
361 assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
362 "User data for FindBaseClass is not canonical!");
363 return Specifier->isVirtual() &&
364 Specifier->getType()->getAs<RecordType>()->getDecl()
365 ->getCanonicalDecl() == BaseRecord;
368 bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier,
371 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
373 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
374 for (Path.Decls = BaseRecord->lookup(N);
375 Path.Decls.first != Path.Decls.second;
376 ++Path.Decls.first) {
377 if ((*Path.Decls.first)->isInIdentifierNamespace(IDNS_Tag))
384 bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
387 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
389 const unsigned IDNS = IDNS_Ordinary | IDNS_Tag | IDNS_Member;
390 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
391 for (Path.Decls = BaseRecord->lookup(N);
392 Path.Decls.first != Path.Decls.second;
393 ++Path.Decls.first) {
394 if ((*Path.Decls.first)->isInIdentifierNamespace(IDNS))
402 FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
405 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
407 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
408 for (Path.Decls = BaseRecord->lookup(N);
409 Path.Decls.first != Path.Decls.second;
410 ++Path.Decls.first) {
411 // FIXME: Refactor the "is it a nested-name-specifier?" check
412 if (isa<TypedefDecl>(*Path.Decls.first) ||
413 (*Path.Decls.first)->isInIdentifierNamespace(IDNS_Tag))