blob: fc4d8b137337f38ff08798052be8f73968c8fe62 [file] [log] [blame]
Douglas Gregor36d1b142009-10-06 17:59:45 +00001//===------ 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"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000015#include "clang/AST/DeclCXX.h"
Alex Lorenz4e1377a2017-05-10 09:47:41 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/RecordLayout.h"
Douglas Gregor18e1b522012-09-11 07:19:42 +000018#include "llvm/ADT/SetVector.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include <algorithm>
Douglas Gregor36d1b142009-10-06 17:59:45 +000020
21using namespace clang;
22
23/// \brief Computes the set of declarations referenced by these base
24/// paths.
25void CXXBasePaths::ComputeDeclsFound() {
26 assert(NumDeclsFound == 0 && !DeclsFound &&
27 "Already computed the set of declarations");
Benjamin Kramer91c6b6a2012-02-23 15:18:31 +000028
Douglas Gregor18e1b522012-09-11 07:19:42 +000029 llvm::SetVector<NamedDecl *, SmallVector<NamedDecl *, 8> > Decls;
Benjamin Kramer91c6b6a2012-02-23 15:18:31 +000030 for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
David Blaikieff7d47a2012-12-19 00:45:41 +000031 Decls.insert(Path->Decls.front());
Benjamin Kramer91c6b6a2012-02-23 15:18:31 +000032
Douglas Gregor36d1b142009-10-06 17:59:45 +000033 NumDeclsFound = Decls.size();
David Blaikie8f2a7fe2015-08-18 23:56:00 +000034 DeclsFound = llvm::make_unique<NamedDecl *[]>(NumDeclsFound);
35 std::copy(Decls.begin(), Decls.end(), DeclsFound.get());
Douglas Gregor36d1b142009-10-06 17:59:45 +000036}
37
Aaron Ballmane6f465e2014-03-14 21:38:48 +000038CXXBasePaths::decl_range CXXBasePaths::found_decls() {
Douglas Gregor36d1b142009-10-06 17:59:45 +000039 if (NumDeclsFound == 0)
40 ComputeDeclsFound();
Douglas Gregor36d1b142009-10-06 17:59:45 +000041
David Blaikie8f2a7fe2015-08-18 23:56:00 +000042 return decl_range(decl_iterator(DeclsFound.get()),
43 decl_iterator(DeclsFound.get() + NumDeclsFound));
Douglas Gregor36d1b142009-10-06 17:59:45 +000044}
45
46/// isAmbiguous - Determines whether the set of paths provided is
47/// ambiguous, i.e., there are two or more paths that refer to
48/// different base class subobjects of the same type. BaseType must be
49/// an unqualified, canonical class type.
Douglas Gregor27ac4292010-05-21 20:29:55 +000050bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
51 BaseType = BaseType.getUnqualifiedType();
Douglas Gregor36d1b142009-10-06 17:59:45 +000052 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
53 return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
54}
55
56/// clear - Clear out all prior path information.
57void CXXBasePaths::clear() {
58 Paths.clear();
59 ClassSubobjects.clear();
Alex Lorenz6796c0b2017-05-18 18:06:07 +000060 VisitedDependentRecords.clear();
Douglas Gregor36d1b142009-10-06 17:59:45 +000061 ScratchPath.clear();
Craig Topper36250ad2014-05-12 05:36:57 +000062 DetectedVirtual = nullptr;
Douglas Gregor36d1b142009-10-06 17:59:45 +000063}
64
65/// @brief Swaps the contents of this CXXBasePaths structure with the
66/// contents of Other.
67void CXXBasePaths::swap(CXXBasePaths &Other) {
68 std::swap(Origin, Other.Origin);
69 Paths.swap(Other.Paths);
70 ClassSubobjects.swap(Other.ClassSubobjects);
Alex Lorenz6796c0b2017-05-18 18:06:07 +000071 VisitedDependentRecords.swap(Other.VisitedDependentRecords);
Douglas Gregor36d1b142009-10-06 17:59:45 +000072 std::swap(FindAmbiguities, Other.FindAmbiguities);
73 std::swap(RecordPaths, Other.RecordPaths);
74 std::swap(DetectVirtual, Other.DetectVirtual);
75 std::swap(DetectedVirtual, Other.DetectedVirtual);
76}
77
John McCall388ef532011-01-28 22:02:36 +000078bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
Douglas Gregor36d1b142009-10-06 17:59:45 +000079 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
80 /*DetectVirtual=*/false);
81 return isDerivedFrom(Base, Paths);
82}
83
John McCall388ef532011-01-28 22:02:36 +000084bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
85 CXXBasePaths &Paths) const {
Douglas Gregor36d1b142009-10-06 17:59:45 +000086 if (getCanonicalDecl() == Base->getCanonicalDecl())
87 return false;
88
John McCall84c16cf2009-11-12 03:15:40 +000089 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000090
91 const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
Benjamin Kramer1d38be92015-07-25 15:27:04 +000092 // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000093 return lookupInBases(
Malcolm Parsonsc6e45832017-01-13 18:55:32 +000094 [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000095 return FindBaseClass(Specifier, Path, BaseDecl);
96 },
97 Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +000098}
99
Jordan Rose55edf5ff2012-08-08 18:23:20 +0000100bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const {
Anders Carlsson15722da2010-06-04 01:40:08 +0000101 if (!getNumVBases())
102 return false;
103
Douglas Gregor3e637462010-03-03 04:38:46 +0000104 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
105 /*DetectVirtual=*/false);
106
107 if (getCanonicalDecl() == Base->getCanonicalDecl())
108 return false;
109
Jordan Rose55edf5ff2012-08-08 18:23:20 +0000110 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
111
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000112 const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
Benjamin Kramer1d38be92015-07-25 15:27:04 +0000113 // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000114 return lookupInBases(
Malcolm Parsonsc6e45832017-01-13 18:55:32 +0000115 [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000116 return FindVirtualBaseClass(Specifier, Path, BaseDecl);
117 },
118 Paths);
John McCallddabf1a2009-12-08 07:42:38 +0000119}
120
121bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000122 const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl();
123 return forallBases([TargetDecl](const CXXRecordDecl *Base) {
124 return Base->getCanonicalDecl() != TargetDecl;
125 });
John McCallddabf1a2009-12-08 07:42:38 +0000126}
127
Richard Smithd80b2d52012-11-22 00:24:47 +0000128bool
129CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const {
130 assert(isDependentContext());
131
132 for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
133 if (CurContext->Equals(this))
134 return true;
135
136 return false;
137}
138
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000139bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches,
Douglas Gregordc974572012-11-10 07:24:09 +0000140 bool AllowShortCircuit) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000141 SmallVector<const CXXRecordDecl*, 8> Queue;
John McCallddabf1a2009-12-08 07:42:38 +0000142
143 const CXXRecordDecl *Record = this;
144 bool AllMatches = true;
145 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000146 for (const auto &I : Record->bases()) {
147 const RecordType *Ty = I.getType()->getAs<RecordType>();
Douglas Gregordc974572012-11-10 07:24:09 +0000148 if (!Ty) {
John McCallddabf1a2009-12-08 07:42:38 +0000149 if (AllowShortCircuit) return false;
150 AllMatches = false;
151 continue;
152 }
153
Douglas Gregordc974572012-11-10 07:24:09 +0000154 CXXRecordDecl *Base =
155 cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
Richard Smithd80b2d52012-11-22 00:24:47 +0000156 if (!Base ||
157 (Base->isDependentContext() &&
158 !Base->isCurrentInstantiation(Record))) {
John McCallddabf1a2009-12-08 07:42:38 +0000159 if (AllowShortCircuit) return false;
160 AllMatches = false;
161 continue;
162 }
Faisal Vali683b0742016-05-19 02:28:21 +0000163
164 Queue.push_back(Base);
165 if (!BaseMatches(Base)) {
166 if (AllowShortCircuit) return false;
167 AllMatches = false;
168 continue;
John McCallddabf1a2009-12-08 07:42:38 +0000169 }
170 }
171
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000172 if (Queue.empty())
173 break;
174 Record = Queue.pop_back_val(); // not actually a queue.
John McCallddabf1a2009-12-08 07:42:38 +0000175 }
176
177 return AllMatches;
178}
179
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000180bool CXXBasePaths::lookupInBases(ASTContext &Context,
181 const CXXRecordDecl *Record,
182 CXXRecordDecl::BaseMatchesCallback BaseMatches,
183 bool LookupInDependent) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000184 bool FoundPath = false;
John McCall401982f2010-01-20 21:53:11 +0000185
John McCall553c0792010-01-23 00:46:32 +0000186 // The access of the path down to this record.
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000187 AccessSpecifier AccessToHere = ScratchPath.Access;
188 bool IsFirstStep = ScratchPath.empty();
John McCall553c0792010-01-23 00:46:32 +0000189
Aaron Ballman574705e2014-03-13 15:41:46 +0000190 for (const auto &BaseSpec : Record->bases()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000191 // Find the record of the base class subobjects for this type.
Aaron Ballman574705e2014-03-13 15:41:46 +0000192 QualType BaseType =
193 Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType();
194
Douglas Gregor36d1b142009-10-06 17:59:45 +0000195 // C++ [temp.dep]p3:
196 // In the definition of a class template or a member of a class template,
197 // if a base class of the class template depends on a template-parameter,
198 // the base class scope is not examined during unqualified name lookup
199 // either at the point of definition of the class template or member or
200 // during an instantiation of the class tem- plate or member.
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000201 if (!LookupInDependent && BaseType->isDependentType())
Douglas Gregor36d1b142009-10-06 17:59:45 +0000202 continue;
203
204 // Determine whether we need to visit this base class at all,
205 // updating the count of subobjects appropriately.
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000206 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
Douglas Gregor36d1b142009-10-06 17:59:45 +0000207 bool VisitBase = true;
208 bool SetVirtual = false;
Aaron Ballman574705e2014-03-13 15:41:46 +0000209 if (BaseSpec.isVirtual()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000210 VisitBase = !Subobjects.first;
211 Subobjects.first = true;
Craig Topper36250ad2014-05-12 05:36:57 +0000212 if (isDetectingVirtual() && DetectedVirtual == nullptr) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000213 // If this is the first virtual we find, remember it. If it turns out
214 // there is no base path here, we'll reset it later.
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000215 DetectedVirtual = BaseType->getAs<RecordType>();
Douglas Gregor36d1b142009-10-06 17:59:45 +0000216 SetVirtual = true;
217 }
218 } else
219 ++Subobjects.second;
220
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000221 if (isRecordingPaths()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000222 // Add this base specifier to the current path.
223 CXXBasePathElement Element;
Aaron Ballman574705e2014-03-13 15:41:46 +0000224 Element.Base = &BaseSpec;
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000225 Element.Class = Record;
Aaron Ballman574705e2014-03-13 15:41:46 +0000226 if (BaseSpec.isVirtual())
Douglas Gregor36d1b142009-10-06 17:59:45 +0000227 Element.SubobjectNumber = 0;
228 else
229 Element.SubobjectNumber = Subobjects.second;
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000230 ScratchPath.push_back(Element);
John McCall401982f2010-01-20 21:53:11 +0000231
John McCall553c0792010-01-23 00:46:32 +0000232 // Calculate the "top-down" access to this base class.
233 // The spec actually describes this bottom-up, but top-down is
234 // equivalent because the definition works out as follows:
235 // 1. Write down the access along each step in the inheritance
236 // chain, followed by the access of the decl itself.
237 // For example, in
238 // class A { public: int foo; };
239 // class B : protected A {};
240 // class C : public B {};
241 // class D : private C {};
242 // we would write:
243 // private public protected public
244 // 2. If 'private' appears anywhere except far-left, access is denied.
245 // 3. Otherwise, overall access is determined by the most restrictive
246 // access in the sequence.
247 if (IsFirstStep)
Aaron Ballman574705e2014-03-13 15:41:46 +0000248 ScratchPath.Access = BaseSpec.getAccessSpecifier();
John McCall553c0792010-01-23 00:46:32 +0000249 else
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000250 ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
Aaron Ballman574705e2014-03-13 15:41:46 +0000251 BaseSpec.getAccessSpecifier());
Douglas Gregor36d1b142009-10-06 17:59:45 +0000252 }
John McCall6f891402010-02-09 00:57:12 +0000253
254 // Track whether there's a path involving this specific base.
255 bool FoundPathThroughBase = false;
256
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000257 if (BaseMatches(&BaseSpec, ScratchPath)) {
John McCall553c0792010-01-23 00:46:32 +0000258 // We've found a path that terminates at this base.
John McCall6f891402010-02-09 00:57:12 +0000259 FoundPath = FoundPathThroughBase = true;
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000260 if (isRecordingPaths()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000261 // We have a path. Make a copy of it before moving on.
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000262 Paths.push_back(ScratchPath);
263 } else if (!isFindingAmbiguities()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000264 // We found a path and we don't care about ambiguities;
265 // return immediately.
266 return FoundPath;
267 }
268 } else if (VisitBase) {
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000269 CXXRecordDecl *BaseRecord;
270 if (LookupInDependent) {
271 BaseRecord = nullptr;
272 const TemplateSpecializationType *TST =
273 BaseSpec.getType()->getAs<TemplateSpecializationType>();
274 if (!TST) {
275 if (auto *RT = BaseSpec.getType()->getAs<RecordType>())
276 BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
277 } else {
278 TemplateName TN = TST->getTemplateName();
279 if (auto *TD =
280 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()))
281 BaseRecord = TD->getTemplatedDecl();
282 }
Alex Lorenz6796c0b2017-05-18 18:06:07 +0000283 if (BaseRecord) {
284 if (!BaseRecord->hasDefinition() ||
285 VisitedDependentRecords.count(BaseRecord)) {
286 BaseRecord = nullptr;
287 } else {
288 VisitedDependentRecords.insert(BaseRecord);
289 }
290 }
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000291 } else {
292 BaseRecord = cast<CXXRecordDecl>(
293 BaseSpec.getType()->castAs<RecordType>()->getDecl());
294 }
295 if (BaseRecord &&
296 lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000297 // C++ [class.member.lookup]p2:
298 // A member name f in one sub-object B hides a member name f in
299 // a sub-object A if A is a base class sub-object of B. Any
300 // declarations that are so hidden are eliminated from
301 // consideration.
302
303 // There is a path to a base class that meets the criteria. If we're
304 // not collecting paths or finding ambiguities, we're done.
John McCall6f891402010-02-09 00:57:12 +0000305 FoundPath = FoundPathThroughBase = true;
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000306 if (!isFindingAmbiguities())
Douglas Gregor36d1b142009-10-06 17:59:45 +0000307 return FoundPath;
308 }
309 }
310
311 // Pop this base specifier off the current path (if we're
312 // collecting paths).
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000313 if (isRecordingPaths()) {
314 ScratchPath.pop_back();
John McCall401982f2010-01-20 21:53:11 +0000315 }
316
Douglas Gregor36d1b142009-10-06 17:59:45 +0000317 // If we set a virtual earlier, and this isn't a path, forget it again.
John McCall6f891402010-02-09 00:57:12 +0000318 if (SetVirtual && !FoundPathThroughBase) {
Craig Topper36250ad2014-05-12 05:36:57 +0000319 DetectedVirtual = nullptr;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000320 }
321 }
John McCall553c0792010-01-23 00:46:32 +0000322
323 // Reset the scratch path access.
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000324 ScratchPath.Access = AccessToHere;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000325
326 return FoundPath;
327}
328
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000329bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches,
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000330 CXXBasePaths &Paths,
331 bool LookupInDependent) const {
Douglas Gregor3e637462010-03-03 04:38:46 +0000332 // If we didn't find anything, report that.
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000333 if (!Paths.lookupInBases(getASTContext(), this, BaseMatches,
334 LookupInDependent))
Douglas Gregor3e637462010-03-03 04:38:46 +0000335 return false;
336
337 // If we're not recording paths or we won't ever find ambiguities,
338 // we're done.
339 if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
340 return true;
341
342 // C++ [class.member.lookup]p6:
343 // When virtual base classes are used, a hidden declaration can be
344 // reached along a path through the sub-object lattice that does
345 // not pass through the hiding declaration. This is not an
346 // ambiguity. The identical use with nonvirtual base classes is an
347 // ambiguity; in that case there is no unique instance of the name
348 // that hides all the others.
349 //
350 // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
351 // way to make it any faster.
Benjamin Kramerece036e2015-02-11 19:09:16 +0000352 Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) {
353 for (const CXXBasePathElement &PE : Path) {
354 if (!PE.Base->isVirtual())
355 continue;
Douglas Gregor3e637462010-03-03 04:38:46 +0000356
Benjamin Kramerece036e2015-02-11 19:09:16 +0000357 CXXRecordDecl *VBase = nullptr;
358 if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>())
359 VBase = cast<CXXRecordDecl>(Record->getDecl());
360 if (!VBase)
361 break;
362
363 // The declaration(s) we found along this path were found in a
364 // subobject of a virtual base. Check whether this virtual
365 // base is a subobject of any other path; if so, then the
366 // declaration in this path are hidden by that patch.
367 for (const CXXBasePath &HidingP : Paths) {
368 CXXRecordDecl *HidingClass = nullptr;
369 if (const RecordType *Record =
370 HidingP.back().Base->getType()->getAs<RecordType>())
371 HidingClass = cast<CXXRecordDecl>(Record->getDecl());
372 if (!HidingClass)
Douglas Gregor3e637462010-03-03 04:38:46 +0000373 break;
374
Benjamin Kramerece036e2015-02-11 19:09:16 +0000375 if (HidingClass->isVirtuallyDerivedFrom(VBase))
376 return true;
Douglas Gregor3e637462010-03-03 04:38:46 +0000377 }
378 }
Benjamin Kramerece036e2015-02-11 19:09:16 +0000379 return false;
380 });
Douglas Gregor3e637462010-03-03 04:38:46 +0000381
Douglas Gregor3e637462010-03-03 04:38:46 +0000382 return true;
Douglas Gregor0555f7e2010-03-03 02:18:00 +0000383}
384
John McCall84c16cf2009-11-12 03:15:40 +0000385bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000386 CXXBasePath &Path,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000387 const CXXRecordDecl *BaseRecord) {
Benjamin Kramer1d38be92015-07-25 15:27:04 +0000388 assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
Douglas Gregor36d1b142009-10-06 17:59:45 +0000389 "User data for FindBaseClass is not canonical!");
Ted Kremenek28831752012-08-23 20:46:57 +0000390 return Specifier->getType()->castAs<RecordType>()->getDecl()
391 ->getCanonicalDecl() == BaseRecord;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000392}
393
Douglas Gregor3e637462010-03-03 04:38:46 +0000394bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
395 CXXBasePath &Path,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000396 const CXXRecordDecl *BaseRecord) {
Benjamin Kramer1d38be92015-07-25 15:27:04 +0000397 assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
Douglas Gregor3e637462010-03-03 04:38:46 +0000398 "User data for FindBaseClass is not canonical!");
399 return Specifier->isVirtual() &&
Ted Kremenek28831752012-08-23 20:46:57 +0000400 Specifier->getType()->castAs<RecordType>()->getDecl()
401 ->getCanonicalDecl() == BaseRecord;
Douglas Gregor3e637462010-03-03 04:38:46 +0000402}
403
John McCall84c16cf2009-11-12 03:15:40 +0000404bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000405 CXXBasePath &Path,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000406 DeclarationName Name) {
Ted Kremenek28831752012-08-23 20:46:57 +0000407 RecordDecl *BaseRecord =
408 Specifier->getType()->castAs<RecordType>()->getDecl();
Douglas Gregor36d1b142009-10-06 17:59:45 +0000409
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000410 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +0000411 !Path.Decls.empty();
412 Path.Decls = Path.Decls.slice(1)) {
413 if (Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
Douglas Gregor36d1b142009-10-06 17:59:45 +0000414 return true;
415 }
416
417 return false;
418}
419
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000420static bool findOrdinaryMember(RecordDecl *BaseRecord, CXXBasePath &Path,
421 DeclarationName Name) {
422 const unsigned IDNS = clang::Decl::IDNS_Ordinary | clang::Decl::IDNS_Tag |
423 clang::Decl::IDNS_Member;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000424 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +0000425 !Path.Decls.empty();
426 Path.Decls = Path.Decls.slice(1)) {
427 if (Path.Decls.front()->isInIdentifierNamespace(IDNS))
Douglas Gregor36d1b142009-10-06 17:59:45 +0000428 return true;
429 }
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000430
Douglas Gregor36d1b142009-10-06 17:59:45 +0000431 return false;
432}
433
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000434bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
435 CXXBasePath &Path,
436 DeclarationName Name) {
437 RecordDecl *BaseRecord =
438 Specifier->getType()->castAs<RecordType>()->getDecl();
439 return findOrdinaryMember(BaseRecord, Path, Name);
440}
441
442bool CXXRecordDecl::FindOrdinaryMemberInDependentClasses(
443 const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
444 DeclarationName Name) {
445 const TemplateSpecializationType *TST =
446 Specifier->getType()->getAs<TemplateSpecializationType>();
447 if (!TST) {
448 auto *RT = Specifier->getType()->getAs<RecordType>();
449 if (!RT)
450 return false;
451 return findOrdinaryMember(RT->getDecl(), Path, Name);
452 }
453 TemplateName TN = TST->getTemplateName();
454 const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
455 if (!TD)
456 return false;
457 CXXRecordDecl *RD = TD->getTemplatedDecl();
458 if (!RD)
459 return false;
460 return findOrdinaryMember(RD, Path, Name);
461}
462
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000463bool CXXRecordDecl::FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
464 CXXBasePath &Path,
465 DeclarationName Name) {
466 RecordDecl *BaseRecord =
467 Specifier->getType()->castAs<RecordType>()->getDecl();
468
469 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
470 Path.Decls = Path.Decls.slice(1)) {
471 if (Path.Decls.front()->isInIdentifierNamespace(IDNS_OMPReduction))
472 return true;
473 }
474
475 return false;
476}
477
John McCall84c16cf2009-11-12 03:15:40 +0000478bool CXXRecordDecl::
479FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
480 CXXBasePath &Path,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000481 DeclarationName Name) {
Ted Kremenek28831752012-08-23 20:46:57 +0000482 RecordDecl *BaseRecord =
483 Specifier->getType()->castAs<RecordType>()->getDecl();
Douglas Gregor36d1b142009-10-06 17:59:45 +0000484
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000485 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +0000486 !Path.Decls.empty();
487 Path.Decls = Path.Decls.slice(1)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000488 // FIXME: Refactor the "is it a nested-name-specifier?" check
David Blaikieff7d47a2012-12-19 00:45:41 +0000489 if (isa<TypedefNameDecl>(Path.Decls.front()) ||
490 Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
Douglas Gregor36d1b142009-10-06 17:59:45 +0000491 return true;
492 }
493
494 return false;
Mike Stump512c5b72009-10-06 23:38:59 +0000495}
Douglas Gregor4165bd62010-03-23 23:47:56 +0000496
Alex Lorenz4e1377a2017-05-10 09:47:41 +0000497std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName(
498 const DeclarationName &Name,
499 llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
500 std::vector<const NamedDecl *> Results;
501 // Lookup in the class.
502 DeclContext::lookup_result DirectResult = lookup(Name);
503 if (!DirectResult.empty()) {
504 for (const NamedDecl *ND : DirectResult) {
505 if (Filter(ND))
506 Results.push_back(ND);
507 }
508 return Results;
509 }
510 // Perform lookup into our base classes.
511 CXXBasePaths Paths;
512 Paths.setOrigin(this);
513 if (!lookupInBases(
514 [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
515 return CXXRecordDecl::FindOrdinaryMemberInDependentClasses(
516 Specifier, Path, Name);
517 },
518 Paths, /*LookupInDependent=*/true))
519 return Results;
520 for (const NamedDecl *ND : Paths.front().Decls) {
521 if (Filter(ND))
522 Results.push_back(ND);
523 }
524 return Results;
525}
526
Douglas Gregor4165bd62010-03-23 23:47:56 +0000527void OverridingMethods::add(unsigned OverriddenSubobject,
528 UniqueVirtualMethod Overriding) {
Craig Topper2341c0d2013-07-04 03:08:24 +0000529 SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides
Douglas Gregor4165bd62010-03-23 23:47:56 +0000530 = Overrides[OverriddenSubobject];
531 if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(),
532 Overriding) == SubobjectOverrides.end())
533 SubobjectOverrides.push_back(Overriding);
534}
535
536void OverridingMethods::add(const OverridingMethods &Other) {
537 for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
538 for (overriding_const_iterator M = I->second.begin(),
539 MEnd = I->second.end();
540 M != MEnd;
541 ++M)
542 add(I->first, *M);
543 }
544}
545
546void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
547 for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
548 I->second.clear();
549 I->second.push_back(Overriding);
550 }
551}
552
553
554namespace {
555 class FinalOverriderCollector {
556 /// \brief The number of subobjects of a given class type that
557 /// occur within the class hierarchy.
558 llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
559
560 /// \brief Overriders for each virtual base subobject.
561 llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
562
563 CXXFinalOverriderMap FinalOverriders;
564
565 public:
566 ~FinalOverriderCollector();
567
568 void Collect(const CXXRecordDecl *RD, bool VirtualBase,
569 const CXXRecordDecl *InVirtualSubobject,
570 CXXFinalOverriderMap &Overriders);
571 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000572}
Douglas Gregor4165bd62010-03-23 23:47:56 +0000573
574void FinalOverriderCollector::Collect(const CXXRecordDecl *RD,
575 bool VirtualBase,
576 const CXXRecordDecl *InVirtualSubobject,
577 CXXFinalOverriderMap &Overriders) {
578 unsigned SubobjectNumber = 0;
579 if (!VirtualBase)
580 SubobjectNumber
581 = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
582
Aaron Ballman574705e2014-03-13 15:41:46 +0000583 for (const auto &Base : RD->bases()) {
584 if (const RecordType *RT = Base.getType()->getAs<RecordType>()) {
Douglas Gregor4165bd62010-03-23 23:47:56 +0000585 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
586 if (!BaseDecl->isPolymorphic())
587 continue;
588
Aaron Ballman574705e2014-03-13 15:41:46 +0000589 if (Overriders.empty() && !Base.isVirtual()) {
Douglas Gregor4165bd62010-03-23 23:47:56 +0000590 // There are no other overriders of virtual member functions,
591 // so let the base class fill in our overriders for us.
592 Collect(BaseDecl, false, InVirtualSubobject, Overriders);
593 continue;
594 }
595
596 // Collect all of the overridders from the base class subobject
597 // and merge them into the set of overridders for this class.
598 // For virtual base classes, populate or use the cached virtual
599 // overrides so that we do not walk the virtual base class (and
600 // its base classes) more than once.
601 CXXFinalOverriderMap ComputedBaseOverriders;
602 CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
Aaron Ballman574705e2014-03-13 15:41:46 +0000603 if (Base.isVirtual()) {
Douglas Gregor4165bd62010-03-23 23:47:56 +0000604 CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
Benjamin Kramerea388a22012-05-27 22:41:08 +0000605 BaseOverriders = MyVirtualOverriders;
Douglas Gregor4165bd62010-03-23 23:47:56 +0000606 if (!MyVirtualOverriders) {
607 MyVirtualOverriders = new CXXFinalOverriderMap;
Benjamin Kramerea388a22012-05-27 22:41:08 +0000608
609 // Collect may cause VirtualOverriders to reallocate, invalidating the
610 // MyVirtualOverriders reference. Set BaseOverriders to the right
611 // value now.
612 BaseOverriders = MyVirtualOverriders;
613
Douglas Gregor4165bd62010-03-23 23:47:56 +0000614 Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
615 }
Douglas Gregor4165bd62010-03-23 23:47:56 +0000616 } else
617 Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
618
619 // Merge the overriders from this base class into our own set of
620 // overriders.
621 for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(),
622 OMEnd = BaseOverriders->end();
623 OM != OMEnd;
624 ++OM) {
625 const CXXMethodDecl *CanonOM
626 = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
627 Overriders[CanonOM].add(OM->second);
628 }
629 }
630 }
631
Aaron Ballman2b124d12014-03-13 16:36:16 +0000632 for (auto *M : RD->methods()) {
Douglas Gregor4165bd62010-03-23 23:47:56 +0000633 // We only care about virtual methods.
634 if (!M->isVirtual())
635 continue;
636
637 CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
638
639 if (CanonM->begin_overridden_methods()
640 == CanonM->end_overridden_methods()) {
641 // This is a new virtual function that does not override any
642 // other virtual function. Add it to the map of virtual
643 // functions for which we are tracking overridders.
644
645 // C++ [class.virtual]p2:
646 // For convenience we say that any virtual function overrides itself.
647 Overriders[CanonM].add(SubobjectNumber,
648 UniqueVirtualMethod(CanonM, SubobjectNumber,
649 InVirtualSubobject));
650 continue;
651 }
652
653 // This virtual method overrides other virtual methods, so it does
654 // not add any new slots into the set of overriders. Instead, we
655 // replace entries in the set of overriders with the new
656 // overrider. To do so, we dig down to the original virtual
657 // functions using data recursion and update all of the methods it
658 // overrides.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000659 typedef llvm::iterator_range<CXXMethodDecl::method_iterator>
660 OverriddenMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000661 SmallVector<OverriddenMethods, 4> Stack;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000662 Stack.push_back(llvm::make_range(CanonM->begin_overridden_methods(),
663 CanonM->end_overridden_methods()));
Douglas Gregor4165bd62010-03-23 23:47:56 +0000664 while (!Stack.empty()) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000665 for (const CXXMethodDecl *OM : Stack.pop_back_val()) {
666 const CXXMethodDecl *CanonOM = OM->getCanonicalDecl();
Anders Carlssona2f74f32010-06-03 01:00:02 +0000667
668 // C++ [class.virtual]p2:
669 // A virtual member function C::vf of a class object S is
670 // a final overrider unless the most derived class (1.8)
671 // of which S is a base class subobject (if any) declares
672 // or inherits another member function that overrides vf.
673 //
674 // Treating this object like the most derived class, we
675 // replace any overrides from base classes with this
676 // overriding virtual function.
677 Overriders[CanonOM].replaceAll(
678 UniqueVirtualMethod(CanonM, SubobjectNumber,
679 InVirtualSubobject));
680
Douglas Gregor4165bd62010-03-23 23:47:56 +0000681 if (CanonOM->begin_overridden_methods()
Anders Carlssona2f74f32010-06-03 01:00:02 +0000682 == CanonOM->end_overridden_methods())
Douglas Gregor4165bd62010-03-23 23:47:56 +0000683 continue;
Douglas Gregor4165bd62010-03-23 23:47:56 +0000684
685 // Continue recursion to the methods that this virtual method
686 // overrides.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000687 Stack.push_back(llvm::make_range(CanonOM->begin_overridden_methods(),
688 CanonOM->end_overridden_methods()));
Douglas Gregor4165bd62010-03-23 23:47:56 +0000689 }
690 }
Anders Carlssona2f74f32010-06-03 01:00:02 +0000691
692 // C++ [class.virtual]p2:
693 // For convenience we say that any virtual function overrides itself.
694 Overriders[CanonM].add(SubobjectNumber,
695 UniqueVirtualMethod(CanonM, SubobjectNumber,
696 InVirtualSubobject));
Douglas Gregor4165bd62010-03-23 23:47:56 +0000697 }
698}
699
700FinalOverriderCollector::~FinalOverriderCollector() {
701 for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
702 VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
703 VO != VOEnd;
704 ++VO)
705 delete VO->second;
706}
707
708void
709CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
710 FinalOverriderCollector Collector;
Craig Topper36250ad2014-05-12 05:36:57 +0000711 Collector.Collect(this, false, nullptr, FinalOverriders);
Douglas Gregor4165bd62010-03-23 23:47:56 +0000712
713 // Weed out any final overriders that come from virtual base class
714 // subobjects that were hidden by other subobjects along any path.
715 // This is the final-overrider variant of C++ [class.member.lookup]p10.
Benjamin Kramerece036e2015-02-11 19:09:16 +0000716 for (auto &OM : FinalOverriders) {
717 for (auto &SO : OM.second) {
718 SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second;
Douglas Gregor4165bd62010-03-23 23:47:56 +0000719 if (Overriding.size() < 2)
720 continue;
721
Benjamin Kramerece036e2015-02-11 19:09:16 +0000722 auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) {
723 if (!M.InVirtualSubobject)
724 return false;
Douglas Gregor4165bd62010-03-23 23:47:56 +0000725
726 // We have an overriding method in a virtual base class
727 // subobject (or non-virtual base class subobject thereof);
728 // determine whether there exists an other overriding method
729 // in a base class subobject that hides the virtual base class
730 // subobject.
Benjamin Kramerece036e2015-02-11 19:09:16 +0000731 for (const UniqueVirtualMethod &OP : Overriding)
732 if (&M != &OP &&
733 OP.Method->getParent()->isVirtuallyDerivedFrom(
734 M.InVirtualSubobject))
735 return true;
736 return false;
737 };
Douglas Gregor4165bd62010-03-23 23:47:56 +0000738
Benjamin Kramerece036e2015-02-11 19:09:16 +0000739 Overriding.erase(
740 std::remove_if(Overriding.begin(), Overriding.end(), IsHidden),
741 Overriding.end());
Douglas Gregor4165bd62010-03-23 23:47:56 +0000742 }
743 }
744}
Anders Carlsson4131f002010-11-24 22:50:27 +0000745
746static void
747AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
748 CXXIndirectPrimaryBaseSet& Bases) {
749 // If the record has a virtual primary base class, add it to our set.
750 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000751 if (Layout.isPrimaryBaseVirtual())
Anders Carlsson4131f002010-11-24 22:50:27 +0000752 Bases.insert(Layout.getPrimaryBase());
753
Aaron Ballman574705e2014-03-13 15:41:46 +0000754 for (const auto &I : RD->bases()) {
755 assert(!I.getType()->isDependentType() &&
Anders Carlsson4131f002010-11-24 22:50:27 +0000756 "Cannot get indirect primary bases for class with dependent bases.");
757
758 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000759 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson4131f002010-11-24 22:50:27 +0000760
761 // Only bases with virtual bases participate in computing the
762 // indirect primary virtual base classes.
763 if (BaseDecl->getNumVBases())
764 AddIndirectPrimaryBases(BaseDecl, Context, Bases);
765 }
766
767}
768
769void
770CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
771 ASTContext &Context = getASTContext();
772
773 if (!getNumVBases())
774 return;
775
Aaron Ballman574705e2014-03-13 15:41:46 +0000776 for (const auto &I : bases()) {
777 assert(!I.getType()->isDependentType() &&
Anders Carlsson4131f002010-11-24 22:50:27 +0000778 "Cannot get indirect primary bases for class with dependent bases.");
779
780 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000781 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson4131f002010-11-24 22:50:27 +0000782
783 // Only bases with virtual bases participate in computing the
784 // indirect primary virtual base classes.
785 if (BaseDecl->getNumVBases())
786 AddIndirectPrimaryBases(BaseDecl, Context, Bases);
787 }
788}