CXXInheritance.h revision 327952
1//===- CXXInheritance.h - 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
14#ifndef LLVM_CLANG_AST_CXXINHERITANCE_H
15#define LLVM_CLANG_AST_CXXINHERITANCE_H
16
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/Type.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/iterator_range.h"
29#include <list>
30#include <memory>
31#include <utility>
32
33namespace clang {
34
35class ASTContext;
36class NamedDecl;
37
38/// \brief Represents an element in a path from a derived class to a
39/// base class.
40///
41/// Each step in the path references the link from a
42/// derived class to one of its direct base classes, along with a
43/// base "number" that identifies which base subobject of the
44/// original derived class we are referencing.
45struct CXXBasePathElement {
46  /// \brief The base specifier that states the link from a derived
47  /// class to a base class, which will be followed by this base
48  /// path element.
49  const CXXBaseSpecifier *Base;
50
51  /// \brief The record decl of the class that the base is a base of.
52  const CXXRecordDecl *Class;
53
54  /// \brief Identifies which base class subobject (of type
55  /// \c Base->getType()) this base path element refers to.
56  ///
57  /// This value is only valid if \c !Base->isVirtual(), because there
58  /// is no base numbering for the zero or one virtual bases of a
59  /// given type.
60  int SubobjectNumber;
61};
62
63/// \brief Represents a path from a specific derived class
64/// (which is not represented as part of the path) to a particular
65/// (direct or indirect) base class subobject.
66///
67/// Individual elements in the path are described by the \c CXXBasePathElement
68/// structure, which captures both the link from a derived class to one of its
69/// direct bases and identification describing which base class
70/// subobject is being used.
71class CXXBasePath : public SmallVector<CXXBasePathElement, 4> {
72public:
73  /// \brief The access along this inheritance path.  This is only
74  /// calculated when recording paths.  AS_none is a special value
75  /// used to indicate a path which permits no legal access.
76  AccessSpecifier Access = AS_public;
77
78  CXXBasePath() = default;
79
80  /// \brief The set of declarations found inside this base class
81  /// subobject.
82  DeclContext::lookup_result Decls;
83
84  void clear() {
85    SmallVectorImpl<CXXBasePathElement>::clear();
86    Access = AS_public;
87  }
88};
89
90/// BasePaths - Represents the set of paths from a derived class to
91/// one of its (direct or indirect) bases. For example, given the
92/// following class hierarchy:
93///
94/// @code
95/// class A { };
96/// class B : public A { };
97/// class C : public A { };
98/// class D : public B, public C{ };
99/// @endcode
100///
101/// There are two potential BasePaths to represent paths from D to a
102/// base subobject of type A. One path is (D,0) -> (B,0) -> (A,0)
103/// and another is (D,0)->(C,0)->(A,1). These two paths actually
104/// refer to two different base class subobjects of the same type,
105/// so the BasePaths object refers to an ambiguous path. On the
106/// other hand, consider the following class hierarchy:
107///
108/// @code
109/// class A { };
110/// class B : public virtual A { };
111/// class C : public virtual A { };
112/// class D : public B, public C{ };
113/// @endcode
114///
115/// Here, there are two potential BasePaths again, (D, 0) -> (B, 0)
116/// -> (A,v) and (D, 0) -> (C, 0) -> (A, v), but since both of them
117/// refer to the same base class subobject of type A (the virtual
118/// one), there is no ambiguity.
119class CXXBasePaths {
120  friend class CXXRecordDecl;
121
122  /// \brief The type from which this search originated.
123  CXXRecordDecl *Origin = nullptr;
124
125  /// Paths - The actual set of paths that can be taken from the
126  /// derived class to the same base class.
127  std::list<CXXBasePath> Paths;
128
129  /// ClassSubobjects - Records the class subobjects for each class
130  /// type that we've seen. The first element in the pair says
131  /// whether we found a path to a virtual base for that class type,
132  /// while the element contains the number of non-virtual base
133  /// class subobjects for that class type. The key of the map is
134  /// the cv-unqualified canonical type of the base class subobject.
135  llvm::SmallDenseMap<QualType, std::pair<bool, unsigned>, 8> ClassSubobjects;
136
137  /// VisitedDependentRecords - Records the dependent records that have been
138  /// already visited.
139  llvm::SmallDenseSet<const CXXRecordDecl *, 4> VisitedDependentRecords;
140
141  /// FindAmbiguities - Whether Sema::IsDerivedFrom should try find
142  /// ambiguous paths while it is looking for a path from a derived
143  /// type to a base type.
144  bool FindAmbiguities;
145
146  /// RecordPaths - Whether Sema::IsDerivedFrom should record paths
147  /// while it is determining whether there are paths from a derived
148  /// type to a base type.
149  bool RecordPaths;
150
151  /// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search
152  /// if it finds a path that goes across a virtual base. The virtual class
153  /// is also recorded.
154  bool DetectVirtual;
155
156  /// ScratchPath - A BasePath that is used by Sema::lookupInBases
157  /// to help build the set of paths.
158  CXXBasePath ScratchPath;
159
160  /// DetectedVirtual - The base class that is virtual.
161  const RecordType *DetectedVirtual = nullptr;
162
163  /// \brief Array of the declarations that have been found. This
164  /// array is constructed only if needed, e.g., to iterate over the
165  /// results within LookupResult.
166  std::unique_ptr<NamedDecl *[]> DeclsFound;
167  unsigned NumDeclsFound = 0;
168
169  void ComputeDeclsFound();
170
171  bool lookupInBases(ASTContext &Context, const CXXRecordDecl *Record,
172                     CXXRecordDecl::BaseMatchesCallback BaseMatches,
173                     bool LookupInDependent = false);
174
175public:
176  using paths_iterator = std::list<CXXBasePath>::iterator;
177  using const_paths_iterator = std::list<CXXBasePath>::const_iterator;
178  using decl_iterator = NamedDecl **;
179
180  /// BasePaths - Construct a new BasePaths structure to record the
181  /// paths for a derived-to-base search.
182  explicit CXXBasePaths(bool FindAmbiguities = true, bool RecordPaths = true,
183                        bool DetectVirtual = true)
184      : FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths),
185        DetectVirtual(DetectVirtual) {}
186
187  paths_iterator begin() { return Paths.begin(); }
188  paths_iterator end()   { return Paths.end(); }
189  const_paths_iterator begin() const { return Paths.begin(); }
190  const_paths_iterator end()   const { return Paths.end(); }
191
192  CXXBasePath&       front()       { return Paths.front(); }
193  const CXXBasePath& front() const { return Paths.front(); }
194
195  using decl_range = llvm::iterator_range<decl_iterator>;
196
197  decl_range found_decls();
198
199  /// \brief Determine whether the path from the most-derived type to the
200  /// given base type is ambiguous (i.e., it refers to multiple subobjects of
201  /// the same base type).
202  bool isAmbiguous(CanQualType BaseType);
203
204  /// \brief Whether we are finding multiple paths to detect ambiguities.
205  bool isFindingAmbiguities() const { return FindAmbiguities; }
206
207  /// \brief Whether we are recording paths.
208  bool isRecordingPaths() const { return RecordPaths; }
209
210  /// \brief Specify whether we should be recording paths or not.
211  void setRecordingPaths(bool RP) { RecordPaths = RP; }
212
213  /// \brief Whether we are detecting virtual bases.
214  bool isDetectingVirtual() const { return DetectVirtual; }
215
216  /// \brief The virtual base discovered on the path (if we are merely
217  /// detecting virtuals).
218  const RecordType* getDetectedVirtual() const {
219    return DetectedVirtual;
220  }
221
222  /// \brief Retrieve the type from which this base-paths search
223  /// began
224  CXXRecordDecl *getOrigin() const { return Origin; }
225  void setOrigin(CXXRecordDecl *Rec) { Origin = Rec; }
226
227  /// \brief Clear the base-paths results.
228  void clear();
229
230  /// \brief Swap this data structure's contents with another CXXBasePaths
231  /// object.
232  void swap(CXXBasePaths &Other);
233};
234
235/// \brief Uniquely identifies a virtual method within a class
236/// hierarchy by the method itself and a class subobject number.
237struct UniqueVirtualMethod {
238  /// \brief The overriding virtual method.
239  CXXMethodDecl *Method = nullptr;
240
241  /// \brief The subobject in which the overriding virtual method
242  /// resides.
243  unsigned Subobject = 0;
244
245  /// \brief The virtual base class subobject of which this overridden
246  /// virtual method is a part. Note that this records the closest
247  /// derived virtual base class subobject.
248  const CXXRecordDecl *InVirtualSubobject = nullptr;
249
250  UniqueVirtualMethod() = default;
251
252  UniqueVirtualMethod(CXXMethodDecl *Method, unsigned Subobject,
253                      const CXXRecordDecl *InVirtualSubobject)
254      : Method(Method), Subobject(Subobject),
255        InVirtualSubobject(InVirtualSubobject) {}
256
257  friend bool operator==(const UniqueVirtualMethod &X,
258                         const UniqueVirtualMethod &Y) {
259    return X.Method == Y.Method && X.Subobject == Y.Subobject &&
260      X.InVirtualSubobject == Y.InVirtualSubobject;
261  }
262
263  friend bool operator!=(const UniqueVirtualMethod &X,
264                         const UniqueVirtualMethod &Y) {
265    return !(X == Y);
266  }
267};
268
269/// \brief The set of methods that override a given virtual method in
270/// each subobject where it occurs.
271///
272/// The first part of the pair is the subobject in which the
273/// overridden virtual function occurs, while the second part of the
274/// pair is the virtual method that overrides it (including the
275/// subobject in which that virtual function occurs).
276class OverridingMethods {
277  using ValuesT = SmallVector<UniqueVirtualMethod, 4>;
278  using MapType = llvm::MapVector<unsigned, ValuesT>;
279
280  MapType Overrides;
281
282public:
283  // Iterate over the set of subobjects that have overriding methods.
284  using iterator = MapType::iterator;
285  using const_iterator = MapType::const_iterator;
286
287  iterator begin() { return Overrides.begin(); }
288  const_iterator begin() const { return Overrides.begin(); }
289  iterator end() { return Overrides.end(); }
290  const_iterator end() const { return Overrides.end(); }
291  unsigned size() const { return Overrides.size(); }
292
293  // Iterate over the set of overriding virtual methods in a given
294  // subobject.
295  using overriding_iterator =
296      SmallVectorImpl<UniqueVirtualMethod>::iterator;
297  using overriding_const_iterator =
298      SmallVectorImpl<UniqueVirtualMethod>::const_iterator;
299
300  // Add a new overriding method for a particular subobject.
301  void add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding);
302
303  // Add all of the overriding methods from "other" into overrides for
304  // this method. Used when merging the overrides from multiple base
305  // class subobjects.
306  void add(const OverridingMethods &Other);
307
308  // Replace all overriding virtual methods in all subobjects with the
309  // given virtual method.
310  void replaceAll(UniqueVirtualMethod Overriding);
311};
312
313/// \brief A mapping from each virtual member function to its set of
314/// final overriders.
315///
316/// Within a class hierarchy for a given derived class, each virtual
317/// member function in that hierarchy has one or more "final
318/// overriders" (C++ [class.virtual]p2). A final overrider for a
319/// virtual function "f" is the virtual function that will actually be
320/// invoked when dispatching a call to "f" through the
321/// vtable. Well-formed classes have a single final overrider for each
322/// virtual function; in abstract classes, the final overrider for at
323/// least one virtual function is a pure virtual function. Due to
324/// multiple, virtual inheritance, it is possible for a class to have
325/// more than one final overrider. Athough this is an error (per C++
326/// [class.virtual]p2), it is not considered an error here: the final
327/// overrider map can represent multiple final overriders for a
328/// method, and it is up to the client to determine whether they are
329/// problem. For example, the following class \c D has two final
330/// overriders for the virtual function \c A::f(), one in \c C and one
331/// in \c D:
332///
333/// \code
334///   struct A { virtual void f(); };
335///   struct B : virtual A { virtual void f(); };
336///   struct C : virtual A { virtual void f(); };
337///   struct D : B, C { };
338/// \endcode
339///
340/// This data structure contains a mapping from every virtual
341/// function *that does not override an existing virtual function* and
342/// in every subobject where that virtual function occurs to the set
343/// of virtual functions that override it. Thus, the same virtual
344/// function \c A::f can actually occur in multiple subobjects of type
345/// \c A due to multiple inheritance, and may be overridden by
346/// different virtual functions in each, as in the following example:
347///
348/// \code
349///   struct A { virtual void f(); };
350///   struct B : A { virtual void f(); };
351///   struct C : A { virtual void f(); };
352///   struct D : B, C { };
353/// \endcode
354///
355/// Unlike in the previous example, where the virtual functions \c
356/// B::f and \c C::f both overrode \c A::f in the same subobject of
357/// type \c A, in this example the two virtual functions both override
358/// \c A::f but in *different* subobjects of type A. This is
359/// represented by numbering the subobjects in which the overridden
360/// and the overriding virtual member functions are located. Subobject
361/// 0 represents the virtual base class subobject of that type, while
362/// subobject numbers greater than 0 refer to non-virtual base class
363/// subobjects of that type.
364class CXXFinalOverriderMap
365  : public llvm::MapVector<const CXXMethodDecl *, OverridingMethods> {};
366
367/// \brief A set of all the primary bases for a class.
368class CXXIndirectPrimaryBaseSet
369  : public llvm::SmallSet<const CXXRecordDecl*, 32> {};
370
371} // namespace clang
372
373#endif // LLVM_CLANG_AST_CXXINHERITANCE_H
374