1 //===--- VTableBuilder.h - C++ vtable layout builder --------------*- 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 contains code dealing with generation of the layout of virtual tables.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_VTABLEBUILDER_H
15 #define LLVM_CLANG_AST_VTABLEBUILDER_H
17 #include "clang/AST/BaseSubobject.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/GlobalDecl.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/Basic/ABI.h"
22 #include "llvm/ADT/DenseMap.h"
29 /// \brief Represents a single component in a vtable.
30 class VTableComponent {
39 /// \brief A pointer to the complete destructor.
40 CK_CompleteDtorPointer,
42 /// \brief A pointer to the deleting destructor.
43 CK_DeletingDtorPointer,
45 /// \brief An entry that is never used.
47 /// In some cases, a vtable function pointer will end up never being
48 /// called. Such vtable function pointers are represented as a
49 /// CK_UnusedFunctionPointer.
50 CK_UnusedFunctionPointer
53 VTableComponent() = default;
55 static VTableComponent MakeVCallOffset(CharUnits Offset) {
56 return VTableComponent(CK_VCallOffset, Offset);
59 static VTableComponent MakeVBaseOffset(CharUnits Offset) {
60 return VTableComponent(CK_VBaseOffset, Offset);
63 static VTableComponent MakeOffsetToTop(CharUnits Offset) {
64 return VTableComponent(CK_OffsetToTop, Offset);
67 static VTableComponent MakeRTTI(const CXXRecordDecl *RD) {
68 return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
71 static VTableComponent MakeFunction(const CXXMethodDecl *MD) {
72 assert(!isa<CXXDestructorDecl>(MD) &&
73 "Don't use MakeFunction with destructors!");
75 return VTableComponent(CK_FunctionPointer,
76 reinterpret_cast<uintptr_t>(MD));
79 static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
80 return VTableComponent(CK_CompleteDtorPointer,
81 reinterpret_cast<uintptr_t>(DD));
84 static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
85 return VTableComponent(CK_DeletingDtorPointer,
86 reinterpret_cast<uintptr_t>(DD));
89 static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
90 assert(!isa<CXXDestructorDecl>(MD) &&
91 "Don't use MakeUnusedFunction with destructors!");
92 return VTableComponent(CK_UnusedFunctionPointer,
93 reinterpret_cast<uintptr_t>(MD));
96 static VTableComponent getFromOpaqueInteger(uint64_t I) {
97 return VTableComponent(I);
100 /// \brief Get the kind of this vtable component.
101 Kind getKind() const {
102 return (Kind)(Value & 0x7);
105 CharUnits getVCallOffset() const {
106 assert(getKind() == CK_VCallOffset && "Invalid component kind!");
111 CharUnits getVBaseOffset() const {
112 assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
117 CharUnits getOffsetToTop() const {
118 assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
123 const CXXRecordDecl *getRTTIDecl() const {
124 assert(isRTTIKind() && "Invalid component kind!");
125 return reinterpret_cast<CXXRecordDecl *>(getPointer());
128 const CXXMethodDecl *getFunctionDecl() const {
129 assert(isFunctionPointerKind() && "Invalid component kind!");
130 if (isDestructorKind())
131 return getDestructorDecl();
132 return reinterpret_cast<CXXMethodDecl *>(getPointer());
135 const CXXDestructorDecl *getDestructorDecl() const {
136 assert(isDestructorKind() && "Invalid component kind!");
137 return reinterpret_cast<CXXDestructorDecl *>(getPointer());
140 const CXXMethodDecl *getUnusedFunctionDecl() const {
141 assert(getKind() == CK_UnusedFunctionPointer && "Invalid component kind!");
142 return reinterpret_cast<CXXMethodDecl *>(getPointer());
145 bool isDestructorKind() const { return isDestructorKind(getKind()); }
147 bool isUsedFunctionPointerKind() const {
148 return isUsedFunctionPointerKind(getKind());
151 bool isFunctionPointerKind() const {
152 return isFunctionPointerKind(getKind());
155 bool isRTTIKind() const { return isRTTIKind(getKind()); }
158 static bool isFunctionPointerKind(Kind ComponentKind) {
159 return isUsedFunctionPointerKind(ComponentKind) ||
160 ComponentKind == CK_UnusedFunctionPointer;
162 static bool isUsedFunctionPointerKind(Kind ComponentKind) {
163 return ComponentKind == CK_FunctionPointer ||
164 isDestructorKind(ComponentKind);
166 static bool isDestructorKind(Kind ComponentKind) {
167 return ComponentKind == CK_CompleteDtorPointer ||
168 ComponentKind == CK_DeletingDtorPointer;
170 static bool isRTTIKind(Kind ComponentKind) {
171 return ComponentKind == CK_RTTI;
174 VTableComponent(Kind ComponentKind, CharUnits Offset) {
175 assert((ComponentKind == CK_VCallOffset ||
176 ComponentKind == CK_VBaseOffset ||
177 ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
178 assert(Offset.getQuantity() < (1LL << 56) && "Offset is too big!");
179 assert(Offset.getQuantity() >= -(1LL << 56) && "Offset is too small!");
181 Value = (uint64_t(Offset.getQuantity()) << 3) | ComponentKind;
184 VTableComponent(Kind ComponentKind, uintptr_t Ptr) {
185 assert((isRTTIKind(ComponentKind) || isFunctionPointerKind(ComponentKind)) &&
186 "Invalid component kind!");
188 assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
190 Value = Ptr | ComponentKind;
193 CharUnits getOffset() const {
194 assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
195 getKind() == CK_OffsetToTop) && "Invalid component kind!");
197 return CharUnits::fromQuantity(Value >> 3);
200 uintptr_t getPointer() const {
201 assert((getKind() == CK_RTTI || isFunctionPointerKind()) &&
202 "Invalid component kind!");
204 return static_cast<uintptr_t>(Value & ~7ULL);
207 explicit VTableComponent(uint64_t Value)
210 /// The kind is stored in the lower 3 bits of the value. For offsets, we
211 /// make use of the facts that classes can't be larger than 2^55 bytes,
212 /// so we store the offset in the lower part of the 61 bits that remain.
213 /// (The reason that we're not simply using a PointerIntPair here is that we
214 /// need the offsets to be 64-bit, even when on a 32-bit machine).
220 typedef std::pair<uint64_t, ThunkInfo> VTableThunkTy;
221 struct AddressPointLocation {
222 unsigned VTableIndex, AddressPointIndex;
224 typedef llvm::DenseMap<BaseSubobject, AddressPointLocation>
228 // Stores the component indices of the first component of each virtual table in
229 // the virtual table group. To save a little memory in the common case where
230 // the vtable group contains a single vtable, an empty vector here represents
232 OwningArrayRef<size_t> VTableIndices;
234 OwningArrayRef<VTableComponent> VTableComponents;
236 /// \brief Contains thunks needed by vtables, sorted by indices.
237 OwningArrayRef<VTableThunkTy> VTableThunks;
239 /// \brief Address points for all vtables.
240 AddressPointsMapTy AddressPoints;
243 VTableLayout(ArrayRef<size_t> VTableIndices,
244 ArrayRef<VTableComponent> VTableComponents,
245 ArrayRef<VTableThunkTy> VTableThunks,
246 const AddressPointsMapTy &AddressPoints);
249 ArrayRef<VTableComponent> vtable_components() const {
250 return VTableComponents;
253 ArrayRef<VTableThunkTy> vtable_thunks() const {
257 AddressPointLocation getAddressPoint(BaseSubobject Base) const {
258 assert(AddressPoints.count(Base) && "Did not find address point!");
259 return AddressPoints.find(Base)->second;
262 const AddressPointsMapTy &getAddressPoints() const {
263 return AddressPoints;
266 size_t getNumVTables() const {
267 if (VTableIndices.empty())
269 return VTableIndices.size();
272 size_t getVTableOffset(size_t i) const {
273 if (VTableIndices.empty()) {
277 return VTableIndices[i];
280 size_t getVTableSize(size_t i) const {
281 if (VTableIndices.empty()) {
283 return vtable_components().size();
286 size_t thisIndex = VTableIndices[i];
287 size_t nextIndex = (i + 1 == VTableIndices.size())
288 ? vtable_components().size()
289 : VTableIndices[i + 1];
290 return nextIndex - thisIndex;
294 class VTableContextBase {
296 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
298 bool isMicrosoft() const { return IsMicrosoftABI; }
300 virtual ~VTableContextBase() {}
303 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
305 /// \brief Contains all thunks that a given method decl will need.
308 /// Compute and store all vtable related information (vtable layout, vbase
309 /// offset offsets, thunks etc) for the given record decl.
310 virtual void computeVTableRelatedInformation(const CXXRecordDecl *RD) = 0;
312 VTableContextBase(bool MS) : IsMicrosoftABI(MS) {}
315 virtual const ThunkInfoVectorTy *getThunkInfo(GlobalDecl GD) {
316 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()->getCanonicalDecl());
317 computeVTableRelatedInformation(MD->getParent());
319 // This assumes that all the destructors present in the vtable
320 // use exactly the same set of thunks.
321 ThunksMapTy::const_iterator I = Thunks.find(MD);
322 if (I == Thunks.end()) {
323 // We did not find a thunk for this method.
333 class ItaniumVTableContext : public VTableContextBase {
336 /// \brief Contains the index (relative to the vtable address point)
337 /// where the function pointer for a virtual function is stored.
338 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
339 MethodVTableIndicesTy MethodVTableIndices;
341 typedef llvm::DenseMap<const CXXRecordDecl *,
342 std::unique_ptr<const VTableLayout>>
344 VTableLayoutMapTy VTableLayouts;
346 typedef std::pair<const CXXRecordDecl *,
347 const CXXRecordDecl *> ClassPairTy;
349 /// \brief vtable offsets for offsets of virtual bases of a class.
351 /// Contains the vtable offset (relative to the address point) in chars
352 /// where the offsets for virtual bases of a class are stored.
353 typedef llvm::DenseMap<ClassPairTy, CharUnits>
354 VirtualBaseClassOffsetOffsetsMapTy;
355 VirtualBaseClassOffsetOffsetsMapTy VirtualBaseClassOffsetOffsets;
357 void computeVTableRelatedInformation(const CXXRecordDecl *RD) override;
360 ItaniumVTableContext(ASTContext &Context);
361 ~ItaniumVTableContext() override;
363 const VTableLayout &getVTableLayout(const CXXRecordDecl *RD) {
364 computeVTableRelatedInformation(RD);
365 assert(VTableLayouts.count(RD) && "No layout for this record decl!");
367 return *VTableLayouts[RD];
370 std::unique_ptr<VTableLayout> createConstructionVTableLayout(
371 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
372 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass);
374 /// \brief Locate a virtual function in the vtable.
376 /// Return the index (relative to the vtable address point) where the
377 /// function pointer for the given virtual function is stored.
378 uint64_t getMethodVTableIndex(GlobalDecl GD);
380 /// Return the offset in chars (relative to the vtable address point) where
381 /// the offset of the virtual base that contains the given base is stored,
382 /// otherwise, if no virtual base contains the given class, return 0.
384 /// Base must be a virtual base class or an unambiguous base.
385 CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
386 const CXXRecordDecl *VBase);
388 static bool classof(const VTableContextBase *VT) {
389 return !VT->isMicrosoft();
393 /// Holds information about the inheritance path to a virtual base or function
394 /// table pointer. A record may contain as many vfptrs or vbptrs as there are
397 typedef SmallVector<const CXXRecordDecl *, 1> BasePath;
399 VPtrInfo(const CXXRecordDecl *RD)
400 : ObjectWithVPtr(RD), IntroducingObject(RD), NextBaseToMangle(RD) {}
402 /// This is the most derived class that has this vptr at offset zero. When
403 /// single inheritance is used, this is always the most derived class. If
404 /// multiple inheritance is used, it may be any direct or indirect base.
405 const CXXRecordDecl *ObjectWithVPtr;
407 /// This is the class that introduced the vptr by declaring new virtual
408 /// methods or virtual bases.
409 const CXXRecordDecl *IntroducingObject;
411 /// IntroducingObject is at this offset from its containing complete object or
413 CharUnits NonVirtualOffset;
415 /// The bases from the inheritance path that got used to mangle the vbtable
416 /// name. This is not really a full path like a CXXBasePath. It holds the
417 /// subset of records that need to be mangled into the vbtable symbol name in
418 /// order to get a unique name.
419 BasePath MangledPath;
421 /// The next base to push onto the mangled path if this path is ambiguous in a
422 /// derived class. If it's null, then it's already been pushed onto the path.
423 const CXXRecordDecl *NextBaseToMangle;
425 /// The set of possibly indirect vbases that contain this vbtable. When a
426 /// derived class indirectly inherits from the same vbase twice, we only keep
427 /// vtables and their paths from the first instance.
428 BasePath ContainingVBases;
430 /// This holds the base classes path from the complete type to the first base
431 /// with the given vfptr offset, in the base-to-derived order. Only used for
433 BasePath PathToIntroducingObject;
435 /// Static offset from the top of the most derived class to this vfptr,
436 /// including any virtual base offset. Only used for vftables.
437 CharUnits FullOffsetInMDC;
439 /// The vptr is stored inside the non-virtual component of this virtual base.
440 const CXXRecordDecl *getVBaseWithVPtr() const {
441 return ContainingVBases.empty() ? nullptr : ContainingVBases.front();
445 typedef SmallVector<std::unique_ptr<VPtrInfo>, 2> VPtrInfoVector;
447 /// All virtual base related information about a given record decl. Includes
448 /// information on all virtual base tables and the path components that are used
450 struct VirtualBaseInfo {
451 /// A map from virtual base to vbtable index for doing a conversion from the
452 /// the derived class to the a base.
453 llvm::DenseMap<const CXXRecordDecl *, unsigned> VBTableIndices;
455 /// Information on all virtual base tables used when this record is the most
457 VPtrInfoVector VBPtrPaths;
460 class MicrosoftVTableContext : public VTableContextBase {
462 struct MethodVFTableLocation {
463 /// If nonzero, holds the vbtable index of the virtual base with the vfptr.
464 uint64_t VBTableIndex;
466 /// If nonnull, holds the last vbase which contains the vfptr that the
467 /// method definition is adjusted to.
468 const CXXRecordDecl *VBase;
470 /// This is the offset of the vfptr from the start of the last vbase, or the
471 /// complete type if there are no virtual bases.
472 CharUnits VFPtrOffset;
474 /// Method's index in the vftable.
477 MethodVFTableLocation()
478 : VBTableIndex(0), VBase(nullptr), VFPtrOffset(CharUnits::Zero()),
481 MethodVFTableLocation(uint64_t VBTableIndex, const CXXRecordDecl *VBase,
482 CharUnits VFPtrOffset, uint64_t Index)
483 : VBTableIndex(VBTableIndex), VBase(VBase),
484 VFPtrOffset(VFPtrOffset), Index(Index) {}
486 bool operator<(const MethodVFTableLocation &other) const {
487 if (VBTableIndex != other.VBTableIndex) {
488 assert(VBase != other.VBase);
489 return VBTableIndex < other.VBTableIndex;
491 return std::tie(VFPtrOffset, Index) <
492 std::tie(other.VFPtrOffset, other.Index);
499 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
500 MethodVFTableLocationsTy;
501 MethodVFTableLocationsTy MethodVFTableLocations;
503 typedef llvm::DenseMap<const CXXRecordDecl *, VPtrInfoVector>
505 VFPtrLocationsMapTy VFPtrLocations;
507 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
508 typedef llvm::DenseMap<VFTableIdTy, std::unique_ptr<const VTableLayout>>
510 VFTableLayoutMapTy VFTableLayouts;
512 llvm::DenseMap<const CXXRecordDecl *, std::unique_ptr<VirtualBaseInfo>>
515 void enumerateVFPtrs(const CXXRecordDecl *ForClass, VPtrInfoVector &Result);
517 void computeVTableRelatedInformation(const CXXRecordDecl *RD) override;
519 void dumpMethodLocations(const CXXRecordDecl *RD,
520 const MethodVFTableLocationsTy &NewMethods,
523 const VirtualBaseInfo &
524 computeVBTableRelatedInformation(const CXXRecordDecl *RD);
526 void computeVTablePaths(bool ForVBTables, const CXXRecordDecl *RD,
527 VPtrInfoVector &Paths);
530 MicrosoftVTableContext(ASTContext &Context)
531 : VTableContextBase(/*MS=*/true), Context(Context) {}
533 ~MicrosoftVTableContext() override;
535 const VPtrInfoVector &getVFPtrOffsets(const CXXRecordDecl *RD);
537 const VTableLayout &getVFTableLayout(const CXXRecordDecl *RD,
538 CharUnits VFPtrOffset);
540 const MethodVFTableLocation &getMethodVFTableLocation(GlobalDecl GD);
542 const ThunkInfoVectorTy *getThunkInfo(GlobalDecl GD) override {
543 // Complete destructors don't have a slot in a vftable, so no thunks needed.
544 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
545 GD.getDtorType() == Dtor_Complete)
547 return VTableContextBase::getThunkInfo(GD);
550 /// \brief Returns the index of VBase in the vbtable of Derived.
551 /// VBase must be a morally virtual base of Derived.
552 /// The vbtable is an array of i32 offsets. The first entry is a self entry,
553 /// and the rest are offsets from the vbptr to virtual bases.
554 unsigned getVBTableIndex(const CXXRecordDecl *Derived,
555 const CXXRecordDecl *VBase);
557 const VPtrInfoVector &enumerateVBTables(const CXXRecordDecl *RD);
559 static bool classof(const VTableContextBase *VT) { return VT->isMicrosoft(); }