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