1 //===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
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 #include "clang/AST/VTableBuilder.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "llvm/ADT/SetOperations.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
29 #define DUMP_OVERRIDERS 0
33 /// BaseOffset - Represents an offset from a derived class to a direct or
34 /// indirect base class.
36 /// DerivedClass - The derived class.
37 const CXXRecordDecl *DerivedClass;
39 /// VirtualBase - If the path from the derived class to the base class
40 /// involves virtual base classes, this holds the declaration of the last
41 /// virtual base in this path (i.e. closest to the base class).
42 const CXXRecordDecl *VirtualBase;
44 /// NonVirtualOffset - The offset from the derived class to the base class.
45 /// (Or the offset from the virtual base class to the base class, if the
46 /// path from the derived class to the base class involves a virtual base
48 CharUnits NonVirtualOffset;
50 BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
51 NonVirtualOffset(CharUnits::Zero()) { }
52 BaseOffset(const CXXRecordDecl *DerivedClass,
53 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
54 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
55 NonVirtualOffset(NonVirtualOffset) { }
57 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
60 /// FinalOverriders - Contains the final overrider member functions for all
61 /// member functions in the base subobjects of a class.
62 class FinalOverriders {
64 /// OverriderInfo - Information about a final overrider.
65 struct OverriderInfo {
66 /// Method - The method decl of the overrider.
67 const CXXMethodDecl *Method;
69 /// VirtualBase - The virtual base class subobject of this overrider.
70 /// Note that this records the closest derived virtual base class subobject.
71 const CXXRecordDecl *VirtualBase;
73 /// Offset - the base offset of the overrider's parent in the layout class.
76 OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
77 Offset(CharUnits::Zero()) { }
81 /// MostDerivedClass - The most derived class for which the final overriders
83 const CXXRecordDecl *MostDerivedClass;
85 /// MostDerivedClassOffset - If we're building final overriders for a
86 /// construction vtable, this holds the offset from the layout class to the
87 /// most derived class.
88 const CharUnits MostDerivedClassOffset;
90 /// LayoutClass - The class we're using for layout information. Will be
91 /// different than the most derived class if the final overriders are for a
92 /// construction vtable.
93 const CXXRecordDecl *LayoutClass;
97 /// MostDerivedClassLayout - the AST record layout of the most derived class.
98 const ASTRecordLayout &MostDerivedClassLayout;
100 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
101 /// in a base subobject.
102 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
104 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
105 OverriderInfo> OverridersMapTy;
107 /// OverridersMap - The final overriders for all virtual member functions of
108 /// all the base subobjects of the most derived class.
109 OverridersMapTy OverridersMap;
111 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
112 /// as a record decl and a subobject number) and its offsets in the most
113 /// derived class as well as the layout class.
114 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
115 CharUnits> SubobjectOffsetMapTy;
117 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
119 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
121 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
122 CharUnits OffsetInLayoutClass,
123 SubobjectOffsetMapTy &SubobjectOffsets,
124 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
125 SubobjectCountMapTy &SubobjectCounts);
127 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
129 /// dump - dump the final overriders for a base subobject, and all its direct
130 /// and indirect base subobjects.
131 void dump(raw_ostream &Out, BaseSubobject Base,
132 VisitedVirtualBasesSetTy& VisitedVirtualBases);
135 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
136 CharUnits MostDerivedClassOffset,
137 const CXXRecordDecl *LayoutClass);
139 /// getOverrider - Get the final overrider for the given method declaration in
140 /// the subobject with the given base offset.
141 OverriderInfo getOverrider(const CXXMethodDecl *MD,
142 CharUnits BaseOffset) const {
143 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
144 "Did not find overrider!");
146 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
149 /// dump - dump the final overriders.
151 VisitedVirtualBasesSetTy VisitedVirtualBases;
152 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
153 VisitedVirtualBases);
158 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
159 CharUnits MostDerivedClassOffset,
160 const CXXRecordDecl *LayoutClass)
161 : MostDerivedClass(MostDerivedClass),
162 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
163 Context(MostDerivedClass->getASTContext()),
164 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
166 // Compute base offsets.
167 SubobjectOffsetMapTy SubobjectOffsets;
168 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
169 SubobjectCountMapTy SubobjectCounts;
170 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
172 MostDerivedClassOffset,
173 SubobjectOffsets, SubobjectLayoutClassOffsets,
176 // Get the final overriders.
177 CXXFinalOverriderMap FinalOverriders;
178 MostDerivedClass->getFinalOverriders(FinalOverriders);
180 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
181 E = FinalOverriders.end(); I != E; ++I) {
182 const CXXMethodDecl *MD = I->first;
183 const OverridingMethods& Methods = I->second;
185 for (OverridingMethods::const_iterator I = Methods.begin(),
186 E = Methods.end(); I != E; ++I) {
187 unsigned SubobjectNumber = I->first;
188 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
190 "Did not find subobject offset!");
192 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
195 assert(I->second.size() == 1 && "Final overrider is not unique!");
196 const UniqueVirtualMethod &Method = I->second.front();
198 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
199 assert(SubobjectLayoutClassOffsets.count(
200 std::make_pair(OverriderRD, Method.Subobject))
201 && "Did not find subobject offset!");
202 CharUnits OverriderOffset =
203 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
206 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
207 assert(!Overrider.Method && "Overrider should not exist yet!");
209 Overrider.Offset = OverriderOffset;
210 Overrider.Method = Method.Method;
211 Overrider.VirtualBase = Method.InVirtualSubobject;
216 // And dump them (for now).
221 static BaseOffset ComputeBaseOffset(const ASTContext &Context,
222 const CXXRecordDecl *DerivedRD,
223 const CXXBasePath &Path) {
224 CharUnits NonVirtualOffset = CharUnits::Zero();
226 unsigned NonVirtualStart = 0;
227 const CXXRecordDecl *VirtualBase = nullptr;
229 // First, look for the virtual base class.
230 for (int I = Path.size(), E = 0; I != E; --I) {
231 const CXXBasePathElement &Element = Path[I - 1];
233 if (Element.Base->isVirtual()) {
235 QualType VBaseType = Element.Base->getType();
236 VirtualBase = VBaseType->getAsCXXRecordDecl();
241 // Now compute the non-virtual offset.
242 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
243 const CXXBasePathElement &Element = Path[I];
245 // Check the base class offset.
246 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
248 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
250 NonVirtualOffset += Layout.getBaseClassOffset(Base);
253 // FIXME: This should probably use CharUnits or something. Maybe we should
254 // even change the base offsets in ASTRecordLayout to be specified in
256 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
260 static BaseOffset ComputeBaseOffset(const ASTContext &Context,
261 const CXXRecordDecl *BaseRD,
262 const CXXRecordDecl *DerivedRD) {
263 CXXBasePaths Paths(/*FindAmbiguities=*/false,
264 /*RecordPaths=*/true, /*DetectVirtual=*/false);
266 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
267 llvm_unreachable("Class must be derived from the passed in base class!");
269 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
273 ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
274 const CXXMethodDecl *DerivedMD,
275 const CXXMethodDecl *BaseMD) {
276 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
277 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
279 // Canonicalize the return types.
280 CanQualType CanDerivedReturnType =
281 Context.getCanonicalType(DerivedFT->getReturnType());
282 CanQualType CanBaseReturnType =
283 Context.getCanonicalType(BaseFT->getReturnType());
285 assert(CanDerivedReturnType->getTypeClass() ==
286 CanBaseReturnType->getTypeClass() &&
287 "Types must have same type class!");
289 if (CanDerivedReturnType == CanBaseReturnType) {
290 // No adjustment needed.
294 if (isa<ReferenceType>(CanDerivedReturnType)) {
295 CanDerivedReturnType =
296 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
298 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
299 } else if (isa<PointerType>(CanDerivedReturnType)) {
300 CanDerivedReturnType =
301 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
303 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
305 llvm_unreachable("Unexpected return type!");
308 // We need to compare unqualified types here; consider
309 // const T *Base::foo();
310 // T *Derived::foo();
311 if (CanDerivedReturnType.getUnqualifiedType() ==
312 CanBaseReturnType.getUnqualifiedType()) {
313 // No adjustment needed.
317 const CXXRecordDecl *DerivedRD =
318 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
320 const CXXRecordDecl *BaseRD =
321 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
323 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
327 FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
328 CharUnits OffsetInLayoutClass,
329 SubobjectOffsetMapTy &SubobjectOffsets,
330 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
331 SubobjectCountMapTy &SubobjectCounts) {
332 const CXXRecordDecl *RD = Base.getBase();
334 unsigned SubobjectNumber = 0;
336 SubobjectNumber = ++SubobjectCounts[RD];
338 // Set up the subobject to offset mapping.
339 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
340 && "Subobject offset already exists!");
341 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
342 && "Subobject offset already exists!");
344 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
345 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
348 // Traverse our bases.
349 for (const auto &B : RD->bases()) {
350 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
352 CharUnits BaseOffset;
353 CharUnits BaseOffsetInLayoutClass;
355 // Check if we've visited this virtual base before.
356 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
359 const ASTRecordLayout &LayoutClassLayout =
360 Context.getASTRecordLayout(LayoutClass);
362 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
363 BaseOffsetInLayoutClass =
364 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
366 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
367 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
369 BaseOffset = Base.getBaseOffset() + Offset;
370 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
373 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
374 B.isVirtual(), BaseOffsetInLayoutClass,
375 SubobjectOffsets, SubobjectLayoutClassOffsets,
380 void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
381 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
382 const CXXRecordDecl *RD = Base.getBase();
383 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
385 for (const auto &B : RD->bases()) {
386 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
388 // Ignore bases that don't have any virtual member functions.
389 if (!BaseDecl->isPolymorphic())
392 CharUnits BaseOffset;
394 if (!VisitedVirtualBases.insert(BaseDecl).second) {
395 // We've visited this base before.
399 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
401 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
404 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
407 Out << "Final overriders for (";
408 RD->printQualifiedName(Out);
410 Out << Base.getBaseOffset().getQuantity() << ")\n";
412 // Now dump the overriders for this base subobject.
413 for (const auto *MD : RD->methods()) {
414 if (!MD->isVirtual())
416 MD = MD->getCanonicalDecl();
418 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
421 MD->printQualifiedName(Out);
423 Overrider.Method->printQualifiedName(Out);
424 Out << ", " << Overrider.Offset.getQuantity() << ')';
427 if (!Overrider.Method->isPure())
428 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
430 if (!Offset.isEmpty()) {
431 Out << " [ret-adj: ";
432 if (Offset.VirtualBase) {
433 Offset.VirtualBase->printQualifiedName(Out);
437 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
444 /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
445 struct VCallOffsetMap {
447 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
449 /// Offsets - Keeps track of methods and their offsets.
450 // FIXME: This should be a real map and not a vector.
451 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
453 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
454 /// can share the same vcall offset.
455 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
456 const CXXMethodDecl *RHS);
459 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
460 /// add was successful, or false if there was already a member function with
461 /// the same signature in the map.
462 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
464 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
465 /// vtable address point) for the given virtual member function.
466 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
468 // empty - Return whether the offset map is empty or not.
469 bool empty() const { return Offsets.empty(); }
472 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
473 const CXXMethodDecl *RHS) {
474 const FunctionProtoType *LT =
475 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
476 const FunctionProtoType *RT =
477 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
479 // Fast-path matches in the canonical types.
480 if (LT == RT) return true;
482 // Force the signatures to match. We can't rely on the overrides
483 // list here because there isn't necessarily an inheritance
484 // relationship between the two methods.
485 if (LT->getTypeQuals() != RT->getTypeQuals() ||
486 LT->getNumParams() != RT->getNumParams())
488 for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
489 if (LT->getParamType(I) != RT->getParamType(I))
494 bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
495 const CXXMethodDecl *RHS) {
496 assert(LHS->isVirtual() && "LHS must be virtual!");
497 assert(RHS->isVirtual() && "LHS must be virtual!");
499 // A destructor can share a vcall offset with another destructor.
500 if (isa<CXXDestructorDecl>(LHS))
501 return isa<CXXDestructorDecl>(RHS);
503 // FIXME: We need to check more things here.
505 // The methods must have the same name.
506 DeclarationName LHSName = LHS->getDeclName();
507 DeclarationName RHSName = RHS->getDeclName();
508 if (LHSName != RHSName)
511 // And the same signatures.
512 return HasSameVirtualSignature(LHS, RHS);
515 bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
516 CharUnits OffsetOffset) {
517 // Check if we can reuse an offset.
518 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
519 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
524 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
528 CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
529 // Look for an offset.
530 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
531 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
532 return Offsets[I].second;
535 llvm_unreachable("Should always find a vcall offset offset!");
538 /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
539 class VCallAndVBaseOffsetBuilder {
541 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
542 VBaseOffsetOffsetsMapTy;
545 /// MostDerivedClass - The most derived class for which we're building vcall
546 /// and vbase offsets.
547 const CXXRecordDecl *MostDerivedClass;
549 /// LayoutClass - The class we're using for layout information. Will be
550 /// different than the most derived class if we're building a construction
552 const CXXRecordDecl *LayoutClass;
554 /// Context - The ASTContext which we will use for layout information.
557 /// Components - vcall and vbase offset components
558 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
559 VTableComponentVectorTy Components;
561 /// VisitedVirtualBases - Visited virtual bases.
562 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
564 /// VCallOffsets - Keeps track of vcall offsets.
565 VCallOffsetMap VCallOffsets;
568 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
569 /// relative to the address point.
570 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
572 /// FinalOverriders - The final overriders of the most derived class.
573 /// (Can be null when we're not building a vtable of the most derived class).
574 const FinalOverriders *Overriders;
576 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
577 /// given base subobject.
578 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
579 CharUnits RealBaseOffset);
581 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
582 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
584 /// AddVBaseOffsets - Add vbase offsets for the given class.
585 void AddVBaseOffsets(const CXXRecordDecl *Base,
586 CharUnits OffsetInLayoutClass);
588 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
589 /// chars, relative to the vtable address point.
590 CharUnits getCurrentOffsetOffset() const;
593 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
594 const CXXRecordDecl *LayoutClass,
595 const FinalOverriders *Overriders,
596 BaseSubobject Base, bool BaseIsVirtual,
597 CharUnits OffsetInLayoutClass)
598 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
599 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
601 // Add vcall and vbase offsets.
602 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
605 /// Methods for iterating over the components.
606 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
607 const_iterator components_begin() const { return Components.rbegin(); }
608 const_iterator components_end() const { return Components.rend(); }
610 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
611 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
612 return VBaseOffsetOffsets;
617 VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
619 CharUnits RealBaseOffset) {
620 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
622 // Itanium C++ ABI 2.5.2:
623 // ..in classes sharing a virtual table with a primary base class, the vcall
624 // and vbase offsets added by the derived class all come before the vcall
625 // and vbase offsets required by the base class, so that the latter may be
626 // laid out as required by the base class without regard to additions from
627 // the derived class(es).
629 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
630 // emit them for the primary base first).
631 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
632 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
634 CharUnits PrimaryBaseOffset;
636 // Get the base offset of the primary base.
637 if (PrimaryBaseIsVirtual) {
638 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
639 "Primary vbase should have a zero offset!");
641 const ASTRecordLayout &MostDerivedClassLayout =
642 Context.getASTRecordLayout(MostDerivedClass);
645 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
647 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
648 "Primary base should have a zero offset!");
650 PrimaryBaseOffset = Base.getBaseOffset();
653 AddVCallAndVBaseOffsets(
654 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
655 PrimaryBaseIsVirtual, RealBaseOffset);
658 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
660 // We only want to add vcall offsets for virtual bases.
662 AddVCallOffsets(Base, RealBaseOffset);
665 CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
666 // OffsetIndex is the index of this vcall or vbase offset, relative to the
667 // vtable address point. (We subtract 3 to account for the information just
668 // above the address point, the RTTI info, the offset to top, and the
669 // vcall offset itself).
670 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
672 CharUnits PointerWidth =
673 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
674 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
678 void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
679 CharUnits VBaseOffset) {
680 const CXXRecordDecl *RD = Base.getBase();
681 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
683 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
685 // Handle the primary base first.
686 // We only want to add vcall offsets if the base is non-virtual; a virtual
687 // primary base will have its vcall and vbase offsets emitted already.
688 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
689 // Get the base offset of the primary base.
690 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
691 "Primary base should have a zero offset!");
693 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
697 // Add the vcall offsets.
698 for (const auto *MD : RD->methods()) {
699 if (!MD->isVirtual())
701 MD = MD->getCanonicalDecl();
703 CharUnits OffsetOffset = getCurrentOffsetOffset();
705 // Don't add a vcall offset if we already have one for this member function
707 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
710 CharUnits Offset = CharUnits::Zero();
713 // Get the final overrider.
714 FinalOverriders::OverriderInfo Overrider =
715 Overriders->getOverrider(MD, Base.getBaseOffset());
717 /// The vcall offset is the offset from the virtual base to the object
718 /// where the function was overridden.
719 Offset = Overrider.Offset - VBaseOffset;
722 Components.push_back(
723 VTableComponent::MakeVCallOffset(Offset));
726 // And iterate over all non-virtual bases (ignoring the primary base).
727 for (const auto &B : RD->bases()) {
731 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
732 if (BaseDecl == PrimaryBase)
735 // Get the base offset of this base.
736 CharUnits BaseOffset = Base.getBaseOffset() +
737 Layout.getBaseClassOffset(BaseDecl);
739 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
745 VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
746 CharUnits OffsetInLayoutClass) {
747 const ASTRecordLayout &LayoutClassLayout =
748 Context.getASTRecordLayout(LayoutClass);
750 // Add vbase offsets.
751 for (const auto &B : RD->bases()) {
752 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
754 // Check if this is a virtual base that we haven't visited before.
755 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
757 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
759 // Add the vbase offset offset.
760 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
761 "vbase offset offset already exists!");
763 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
764 VBaseOffsetOffsets.insert(
765 std::make_pair(BaseDecl, VBaseOffsetOffset));
767 Components.push_back(
768 VTableComponent::MakeVBaseOffset(Offset));
771 // Check the base class looking for more vbase offsets.
772 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
776 /// ItaniumVTableBuilder - Class for building vtable layout information.
777 class ItaniumVTableBuilder {
779 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
781 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
782 PrimaryBasesSetVectorTy;
784 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
785 VBaseOffsetOffsetsMapTy;
787 typedef llvm::DenseMap<BaseSubobject, uint64_t>
790 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
793 /// VTables - Global vtable information.
794 ItaniumVTableContext &VTables;
796 /// MostDerivedClass - The most derived class for which we're building this
798 const CXXRecordDecl *MostDerivedClass;
800 /// MostDerivedClassOffset - If we're building a construction vtable, this
801 /// holds the offset from the layout class to the most derived class.
802 const CharUnits MostDerivedClassOffset;
804 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
805 /// base. (This only makes sense when building a construction vtable).
806 bool MostDerivedClassIsVirtual;
808 /// LayoutClass - The class we're using for layout information. Will be
809 /// different than the most derived class if we're building a construction
811 const CXXRecordDecl *LayoutClass;
813 /// Context - The ASTContext which we will use for layout information.
816 /// FinalOverriders - The final overriders of the most derived class.
817 const FinalOverriders Overriders;
819 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
820 /// bases in this vtable.
821 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
823 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
824 /// the most derived class.
825 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
827 /// Components - The components of the vtable being built.
828 SmallVector<VTableComponent, 64> Components;
830 /// AddressPoints - Address points for the vtable being built.
831 AddressPointsMapTy AddressPoints;
833 /// MethodInfo - Contains information about a method in a vtable.
834 /// (Used for computing 'this' pointer adjustment thunks.
836 /// BaseOffset - The base offset of this method.
837 const CharUnits BaseOffset;
839 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
841 const CharUnits BaseOffsetInLayoutClass;
843 /// VTableIndex - The index in the vtable that this method has.
844 /// (For destructors, this is the index of the complete destructor).
845 const uint64_t VTableIndex;
847 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
848 uint64_t VTableIndex)
849 : BaseOffset(BaseOffset),
850 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851 VTableIndex(VTableIndex) { }
854 : BaseOffset(CharUnits::Zero()),
855 BaseOffsetInLayoutClass(CharUnits::Zero()),
859 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
861 /// MethodInfoMap - The information for all methods in the vtable we're
862 /// currently building.
863 MethodInfoMapTy MethodInfoMap;
865 /// MethodVTableIndices - Contains the index (relative to the vtable address
866 /// point) where the function pointer for a virtual function is stored.
867 MethodVTableIndicesTy MethodVTableIndices;
869 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
871 /// VTableThunks - The thunks by vtable index in the vtable currently being
873 VTableThunksMapTy VTableThunks;
875 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
876 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
878 /// Thunks - A map that contains all the thunks needed for all methods in the
879 /// most derived class for which the vtable is currently being built.
882 /// AddThunk - Add a thunk for the given method.
883 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
885 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
886 /// part of the vtable we're currently building.
887 void ComputeThisAdjustments();
889 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
891 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
893 VisitedVirtualBasesSetTy PrimaryVirtualBases;
895 /// ComputeReturnAdjustment - Compute the return adjustment given a return
896 /// adjustment base offset.
897 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
899 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
900 /// the 'this' pointer from the base subobject to the derived subobject.
901 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
902 BaseSubobject Derived) const;
904 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
905 /// given virtual member function, its offset in the layout class and its
908 ComputeThisAdjustment(const CXXMethodDecl *MD,
909 CharUnits BaseOffsetInLayoutClass,
910 FinalOverriders::OverriderInfo Overrider);
912 /// AddMethod - Add a single virtual member function to the vtable
913 /// components vector.
914 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
916 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
917 /// part of the vtable.
919 /// Itanium C++ ABI 2.5.2:
921 /// struct A { virtual void f(); };
922 /// struct B : virtual public A { int i; };
923 /// struct C : virtual public A { int j; };
924 /// struct D : public B, public C {};
926 /// When B and C are declared, A is a primary base in each case, so although
927 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
928 /// adjustment is required and no thunk is generated. However, inside D
929 /// objects, A is no longer a primary base of C, so if we allowed calls to
930 /// C::f() to use the copy of A's vtable in the C subobject, we would need
931 /// to adjust this from C* to B::A*, which would require a third-party
932 /// thunk. Since we require that a call to C::f() first convert to A*,
933 /// C-in-D's copy of A's vtable is never referenced, so this is not
935 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
936 CharUnits BaseOffsetInLayoutClass,
937 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
938 CharUnits FirstBaseOffsetInLayoutClass) const;
941 /// AddMethods - Add the methods of this base subobject and all its
942 /// primary bases to the vtable components vector.
943 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
944 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
945 CharUnits FirstBaseOffsetInLayoutClass,
946 PrimaryBasesSetVectorTy &PrimaryBases);
948 // LayoutVTable - Layout the vtable for the given base class, including its
949 // secondary vtables and any vtables for virtual bases.
952 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
953 /// given base subobject, as well as all its secondary vtables.
955 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
956 /// or a direct or indirect base of a virtual base.
958 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
959 /// in the layout class.
960 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
961 bool BaseIsMorallyVirtual,
962 bool BaseIsVirtualInLayoutClass,
963 CharUnits OffsetInLayoutClass);
965 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
968 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
969 /// or a direct or indirect base of a virtual base.
970 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
971 CharUnits OffsetInLayoutClass);
973 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
975 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
976 CharUnits OffsetInLayoutClass,
977 VisitedVirtualBasesSetTy &VBases);
979 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
980 /// given base (excluding any primary bases).
981 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
982 VisitedVirtualBasesSetTy &VBases);
984 /// isBuildingConstructionVTable - Return whether this vtable builder is
985 /// building a construction vtable.
986 bool isBuildingConstructorVTable() const {
987 return MostDerivedClass != LayoutClass;
991 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
992 const CXXRecordDecl *MostDerivedClass,
993 CharUnits MostDerivedClassOffset,
994 bool MostDerivedClassIsVirtual,
995 const CXXRecordDecl *LayoutClass)
996 : VTables(VTables), MostDerivedClass(MostDerivedClass),
997 MostDerivedClassOffset(MostDerivedClassOffset),
998 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
999 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1000 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1001 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
1005 if (Context.getLangOpts().DumpVTableLayouts)
1006 dumpLayout(llvm::outs());
1009 uint64_t getNumThunks() const {
1010 return Thunks.size();
1013 ThunksMapTy::const_iterator thunks_begin() const {
1014 return Thunks.begin();
1017 ThunksMapTy::const_iterator thunks_end() const {
1018 return Thunks.end();
1021 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1022 return VBaseOffsetOffsets;
1025 const AddressPointsMapTy &getAddressPoints() const {
1026 return AddressPoints;
1029 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1030 return MethodVTableIndices.begin();
1033 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1034 return MethodVTableIndices.end();
1037 /// getNumVTableComponents - Return the number of components in the vtable
1038 /// currently built.
1039 uint64_t getNumVTableComponents() const {
1040 return Components.size();
1043 const VTableComponent *vtable_component_begin() const {
1044 return Components.begin();
1047 const VTableComponent *vtable_component_end() const {
1048 return Components.end();
1051 AddressPointsMapTy::const_iterator address_points_begin() const {
1052 return AddressPoints.begin();
1055 AddressPointsMapTy::const_iterator address_points_end() const {
1056 return AddressPoints.end();
1059 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1060 return VTableThunks.begin();
1063 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1064 return VTableThunks.end();
1067 /// dumpLayout - Dump the vtable layout.
1068 void dumpLayout(raw_ostream&);
1071 void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1072 const ThunkInfo &Thunk) {
1073 assert(!isBuildingConstructorVTable() &&
1074 "Can't add thunks for construction vtable");
1076 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1078 // Check if we have this thunk already.
1079 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1083 ThunksVector.push_back(Thunk);
1086 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1088 /// Visit all the methods overridden by the given method recursively,
1089 /// in a depth-first pre-order. The Visitor's visitor method returns a bool
1090 /// indicating whether to continue the recursion for the given overridden
1091 /// method (i.e. returning false stops the iteration).
1092 template <class VisitorTy>
1094 visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
1095 assert(MD->isVirtual() && "Method is not virtual!");
1097 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1098 E = MD->end_overridden_methods(); I != E; ++I) {
1099 const CXXMethodDecl *OverriddenMD = *I;
1100 if (!Visitor.visit(OverriddenMD))
1102 visitAllOverriddenMethods(OverriddenMD, Visitor);
1107 struct OverriddenMethodsCollector {
1108 OverriddenMethodsSetTy *Methods;
1110 bool visit(const CXXMethodDecl *MD) {
1111 // Don't recurse on this method if we've already collected it.
1112 return Methods->insert(MD).second;
1117 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1118 /// the overridden methods that the function decl overrides.
1120 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1121 OverriddenMethodsSetTy& OverriddenMethods) {
1122 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1123 visitAllOverriddenMethods(MD, Collector);
1126 void ItaniumVTableBuilder::ComputeThisAdjustments() {
1127 // Now go through the method info map and see if any of the methods need
1128 // 'this' pointer adjustments.
1129 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1130 E = MethodInfoMap.end(); I != E; ++I) {
1131 const CXXMethodDecl *MD = I->first;
1132 const MethodInfo &MethodInfo = I->second;
1134 // Ignore adjustments for unused function pointers.
1135 uint64_t VTableIndex = MethodInfo.VTableIndex;
1136 if (Components[VTableIndex].getKind() ==
1137 VTableComponent::CK_UnusedFunctionPointer)
1140 // Get the final overrider for this method.
1141 FinalOverriders::OverriderInfo Overrider =
1142 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1144 // Check if we need an adjustment at all.
1145 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1146 // When a return thunk is needed by a derived class that overrides a
1147 // virtual base, gcc uses a virtual 'this' adjustment as well.
1148 // While the thunk itself might be needed by vtables in subclasses or
1149 // in construction vtables, there doesn't seem to be a reason for using
1150 // the thunk in this vtable. Still, we do so to match gcc.
1151 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1155 ThisAdjustment ThisAdjustment =
1156 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1158 if (ThisAdjustment.isEmpty())
1162 VTableThunks[VTableIndex].This = ThisAdjustment;
1164 if (isa<CXXDestructorDecl>(MD)) {
1165 // Add an adjustment for the deleting destructor as well.
1166 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1170 /// Clear the method info map.
1171 MethodInfoMap.clear();
1173 if (isBuildingConstructorVTable()) {
1174 // We don't need to store thunk information for construction vtables.
1178 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1179 E = VTableThunks.end(); I != E; ++I) {
1180 const VTableComponent &Component = Components[I->first];
1181 const ThunkInfo &Thunk = I->second;
1182 const CXXMethodDecl *MD;
1184 switch (Component.getKind()) {
1186 llvm_unreachable("Unexpected vtable component kind!");
1187 case VTableComponent::CK_FunctionPointer:
1188 MD = Component.getFunctionDecl();
1190 case VTableComponent::CK_CompleteDtorPointer:
1191 MD = Component.getDestructorDecl();
1193 case VTableComponent::CK_DeletingDtorPointer:
1194 // We've already added the thunk when we saw the complete dtor pointer.
1198 if (MD->getParent() == MostDerivedClass)
1199 AddThunk(MD, Thunk);
1204 ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1205 ReturnAdjustment Adjustment;
1207 if (!Offset.isEmpty()) {
1208 if (Offset.VirtualBase) {
1209 // Get the virtual base offset offset.
1210 if (Offset.DerivedClass == MostDerivedClass) {
1211 // We can get the offset offset directly from our map.
1212 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1213 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1215 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1216 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1217 Offset.VirtualBase).getQuantity();
1221 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1227 BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1228 BaseSubobject Base, BaseSubobject Derived) const {
1229 const CXXRecordDecl *BaseRD = Base.getBase();
1230 const CXXRecordDecl *DerivedRD = Derived.getBase();
1232 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1233 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1235 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1236 llvm_unreachable("Class must be derived from the passed in base class!");
1238 // We have to go through all the paths, and see which one leads us to the
1239 // right base subobject.
1240 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1242 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1244 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1246 if (Offset.VirtualBase) {
1247 // If we have a virtual base class, the non-virtual offset is relative
1248 // to the virtual base class offset.
1249 const ASTRecordLayout &LayoutClassLayout =
1250 Context.getASTRecordLayout(LayoutClass);
1252 /// Get the virtual base offset, relative to the most derived class
1254 OffsetToBaseSubobject +=
1255 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1257 // Otherwise, the non-virtual offset is relative to the derived class
1259 OffsetToBaseSubobject += Derived.getBaseOffset();
1262 // Check if this path gives us the right base subobject.
1263 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1264 // Since we're going from the base class _to_ the derived class, we'll
1265 // invert the non-virtual offset here.
1266 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1271 return BaseOffset();
1274 ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1275 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1276 FinalOverriders::OverriderInfo Overrider) {
1277 // Ignore adjustments for pure virtual member functions.
1278 if (Overrider.Method->isPure())
1279 return ThisAdjustment();
1281 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1282 BaseOffsetInLayoutClass);
1284 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1287 // Compute the adjustment offset.
1288 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1289 OverriderBaseSubobject);
1290 if (Offset.isEmpty())
1291 return ThisAdjustment();
1293 ThisAdjustment Adjustment;
1295 if (Offset.VirtualBase) {
1296 // Get the vcall offset map for this virtual base.
1297 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1299 if (VCallOffsets.empty()) {
1300 // We don't have vcall offsets for this virtual base, go ahead and
1302 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1303 /*FinalOverriders=*/nullptr,
1304 BaseSubobject(Offset.VirtualBase,
1306 /*BaseIsVirtual=*/true,
1307 /*OffsetInLayoutClass=*/
1310 VCallOffsets = Builder.getVCallOffsets();
1313 Adjustment.Virtual.Itanium.VCallOffsetOffset =
1314 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1317 // Set the non-virtual part of the adjustment.
1318 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1323 void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1324 ReturnAdjustment ReturnAdjustment) {
1325 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1326 assert(ReturnAdjustment.isEmpty() &&
1327 "Destructor can't have return adjustment!");
1329 // Add both the complete destructor and the deleting destructor.
1330 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1331 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1333 // Add the return adjustment if necessary.
1334 if (!ReturnAdjustment.isEmpty())
1335 VTableThunks[Components.size()].Return = ReturnAdjustment;
1337 // Add the function.
1338 Components.push_back(VTableComponent::MakeFunction(MD));
1342 /// OverridesIndirectMethodInBase - Return whether the given member function
1343 /// overrides any methods in the set of given bases.
1344 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1345 /// For example, if we have:
1347 /// struct A { virtual void f(); }
1348 /// struct B : A { virtual void f(); }
1349 /// struct C : B { virtual void f(); }
1351 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1352 /// and { A } as the set of bases.
1353 static bool OverridesIndirectMethodInBases(
1354 const CXXMethodDecl *MD,
1355 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1356 if (Bases.count(MD->getParent()))
1359 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1360 E = MD->end_overridden_methods(); I != E; ++I) {
1361 const CXXMethodDecl *OverriddenMD = *I;
1363 // Check "indirect overriders".
1364 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1371 bool ItaniumVTableBuilder::IsOverriderUsed(
1372 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1373 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1374 CharUnits FirstBaseOffsetInLayoutClass) const {
1375 // If the base and the first base in the primary base chain have the same
1376 // offsets, then this overrider will be used.
1377 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1380 // We know now that Base (or a direct or indirect base of it) is a primary
1381 // base in part of the class hierarchy, but not a primary base in the most
1384 // If the overrider is the first base in the primary base chain, we know
1385 // that the overrider will be used.
1386 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1389 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1391 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1392 PrimaryBases.insert(RD);
1394 // Now traverse the base chain, starting with the first base, until we find
1395 // the base that is no longer a primary base.
1397 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1398 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1403 if (Layout.isPrimaryBaseVirtual()) {
1404 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1405 "Primary base should always be at offset 0!");
1407 const ASTRecordLayout &LayoutClassLayout =
1408 Context.getASTRecordLayout(LayoutClass);
1410 // Now check if this is the primary base that is not a primary base in the
1411 // most derived class.
1412 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1413 FirstBaseOffsetInLayoutClass) {
1414 // We found it, stop walking the chain.
1418 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1419 "Primary base should always be at offset 0!");
1422 if (!PrimaryBases.insert(PrimaryBase))
1423 llvm_unreachable("Found a duplicate primary base!");
1428 // If the final overrider is an override of one of the primary bases,
1429 // then we know that it will be used.
1430 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1433 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1435 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1436 /// from the nearest base. Returns null if no method was found.
1437 /// The Bases are expected to be sorted in a base-to-derived order.
1438 static const CXXMethodDecl *
1439 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1440 BasesSetVectorTy &Bases) {
1441 OverriddenMethodsSetTy OverriddenMethods;
1442 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1444 for (int I = Bases.size(), E = 0; I != E; --I) {
1445 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1447 // Now check the overridden methods.
1448 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1449 E = OverriddenMethods.end(); I != E; ++I) {
1450 const CXXMethodDecl *OverriddenMD = *I;
1452 // We found our overridden method.
1453 if (OverriddenMD->getParent() == PrimaryBase)
1454 return OverriddenMD;
1461 void ItaniumVTableBuilder::AddMethods(
1462 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1463 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1464 CharUnits FirstBaseOffsetInLayoutClass,
1465 PrimaryBasesSetVectorTy &PrimaryBases) {
1466 // Itanium C++ ABI 2.5.2:
1467 // The order of the virtual function pointers in a virtual table is the
1468 // order of declaration of the corresponding member functions in the class.
1470 // There is an entry for any virtual function declared in a class,
1471 // whether it is a new function or overrides a base class function,
1472 // unless it overrides a function from the primary base, and conversion
1473 // between their return types does not require an adjustment.
1475 const CXXRecordDecl *RD = Base.getBase();
1476 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1478 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1479 CharUnits PrimaryBaseOffset;
1480 CharUnits PrimaryBaseOffsetInLayoutClass;
1481 if (Layout.isPrimaryBaseVirtual()) {
1482 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1483 "Primary vbase should have a zero offset!");
1485 const ASTRecordLayout &MostDerivedClassLayout =
1486 Context.getASTRecordLayout(MostDerivedClass);
1489 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1491 const ASTRecordLayout &LayoutClassLayout =
1492 Context.getASTRecordLayout(LayoutClass);
1494 PrimaryBaseOffsetInLayoutClass =
1495 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1497 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1498 "Primary base should have a zero offset!");
1500 PrimaryBaseOffset = Base.getBaseOffset();
1501 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1504 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1505 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1506 FirstBaseOffsetInLayoutClass, PrimaryBases);
1508 if (!PrimaryBases.insert(PrimaryBase))
1509 llvm_unreachable("Found a duplicate primary base!");
1512 const CXXDestructorDecl *ImplicitVirtualDtor = nullptr;
1514 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1515 NewVirtualFunctionsTy NewVirtualFunctions;
1517 // Now go through all virtual member functions and add them.
1518 for (const auto *MD : RD->methods()) {
1519 if (!MD->isVirtual())
1521 MD = MD->getCanonicalDecl();
1523 // Get the final overrider.
1524 FinalOverriders::OverriderInfo Overrider =
1525 Overriders.getOverrider(MD, Base.getBaseOffset());
1527 // Check if this virtual member function overrides a method in a primary
1528 // base. If this is the case, and the return type doesn't require adjustment
1529 // then we can just use the member function from the primary base.
1530 if (const CXXMethodDecl *OverriddenMD =
1531 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1532 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1533 OverriddenMD).isEmpty()) {
1534 // Replace the method info of the overridden method with our own
1536 assert(MethodInfoMap.count(OverriddenMD) &&
1537 "Did not find the overridden method!");
1538 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1540 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1541 OverriddenMethodInfo.VTableIndex);
1543 assert(!MethodInfoMap.count(MD) &&
1544 "Should not have method info for this method yet!");
1546 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1547 MethodInfoMap.erase(OverriddenMD);
1549 // If the overridden method exists in a virtual base class or a direct
1550 // or indirect base class of a virtual base class, we need to emit a
1551 // thunk if we ever have a class hierarchy where the base class is not
1552 // a primary base in the complete object.
1553 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1554 // Compute the this adjustment.
1555 ThisAdjustment ThisAdjustment =
1556 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1559 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
1560 Overrider.Method->getParent() == MostDerivedClass) {
1562 // There's no return adjustment from OverriddenMD and MD,
1563 // but that doesn't mean there isn't one between MD and
1564 // the final overrider.
1565 BaseOffset ReturnAdjustmentOffset =
1566 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1567 ReturnAdjustment ReturnAdjustment =
1568 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1570 // This is a virtual thunk for the most derived class, add it.
1571 AddThunk(Overrider.Method,
1572 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1580 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1581 if (MD->isImplicit()) {
1582 // Itanium C++ ABI 2.5.2:
1583 // If a class has an implicitly-defined virtual destructor,
1584 // its entries come after the declared virtual function pointers.
1586 assert(!ImplicitVirtualDtor &&
1587 "Did already see an implicit virtual dtor!");
1588 ImplicitVirtualDtor = DD;
1593 NewVirtualFunctions.push_back(MD);
1596 if (ImplicitVirtualDtor)
1597 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1599 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1600 E = NewVirtualFunctions.end(); I != E; ++I) {
1601 const CXXMethodDecl *MD = *I;
1603 // Get the final overrider.
1604 FinalOverriders::OverriderInfo Overrider =
1605 Overriders.getOverrider(MD, Base.getBaseOffset());
1607 // Insert the method info for this method.
1608 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1611 assert(!MethodInfoMap.count(MD) &&
1612 "Should not have method info for this method yet!");
1613 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1615 // Check if this overrider is going to be used.
1616 const CXXMethodDecl *OverriderMD = Overrider.Method;
1617 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1618 FirstBaseInPrimaryBaseChain,
1619 FirstBaseOffsetInLayoutClass)) {
1620 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1624 // Check if this overrider needs a return adjustment.
1625 // We don't want to do this for pure virtual member functions.
1626 BaseOffset ReturnAdjustmentOffset;
1627 if (!OverriderMD->isPure()) {
1628 ReturnAdjustmentOffset =
1629 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1632 ReturnAdjustment ReturnAdjustment =
1633 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1635 AddMethod(Overrider.Method, ReturnAdjustment);
1639 void ItaniumVTableBuilder::LayoutVTable() {
1640 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1642 /*BaseIsMorallyVirtual=*/false,
1643 MostDerivedClassIsVirtual,
1644 MostDerivedClassOffset);
1646 VisitedVirtualBasesSetTy VBases;
1648 // Determine the primary virtual bases.
1649 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1653 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1655 // -fapple-kext adds an extra entry at end of vtbl.
1656 bool IsAppleKext = Context.getLangOpts().AppleKext;
1658 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1661 void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1662 BaseSubobject Base, bool BaseIsMorallyVirtual,
1663 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
1664 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1666 // Add vcall and vbase offsets for this vtable.
1667 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1668 Base, BaseIsVirtualInLayoutClass,
1669 OffsetInLayoutClass);
1670 Components.append(Builder.components_begin(), Builder.components_end());
1672 // Check if we need to add these vcall offsets.
1673 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1674 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1676 if (VCallOffsets.empty())
1677 VCallOffsets = Builder.getVCallOffsets();
1680 // If we're laying out the most derived class we want to keep track of the
1681 // virtual base class offset offsets.
1682 if (Base.getBase() == MostDerivedClass)
1683 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1685 // Add the offset to top.
1686 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1687 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1689 // Next, add the RTTI.
1690 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1692 uint64_t AddressPoint = Components.size();
1694 // Now go through all virtual member functions and add them.
1695 PrimaryBasesSetVectorTy PrimaryBases;
1696 AddMethods(Base, OffsetInLayoutClass,
1697 Base.getBase(), OffsetInLayoutClass,
1700 const CXXRecordDecl *RD = Base.getBase();
1701 if (RD == MostDerivedClass) {
1702 assert(MethodVTableIndices.empty());
1703 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1704 E = MethodInfoMap.end(); I != E; ++I) {
1705 const CXXMethodDecl *MD = I->first;
1706 const MethodInfo &MI = I->second;
1707 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1708 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1709 = MI.VTableIndex - AddressPoint;
1710 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1711 = MI.VTableIndex + 1 - AddressPoint;
1713 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1718 // Compute 'this' pointer adjustments.
1719 ComputeThisAdjustments();
1721 // Add all address points.
1723 AddressPoints.insert(std::make_pair(
1724 BaseSubobject(RD, OffsetInLayoutClass),
1727 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1728 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1733 if (Layout.isPrimaryBaseVirtual()) {
1734 // Check if this virtual primary base is a primary base in the layout
1735 // class. If it's not, we don't want to add it.
1736 const ASTRecordLayout &LayoutClassLayout =
1737 Context.getASTRecordLayout(LayoutClass);
1739 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1740 OffsetInLayoutClass) {
1741 // We don't want to add this class (or any of its primary bases).
1749 // Layout secondary vtables.
1750 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1754 ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1755 bool BaseIsMorallyVirtual,
1756 CharUnits OffsetInLayoutClass) {
1757 // Itanium C++ ABI 2.5.2:
1758 // Following the primary virtual table of a derived class are secondary
1759 // virtual tables for each of its proper base classes, except any primary
1760 // base(s) with which it shares its primary virtual table.
1762 const CXXRecordDecl *RD = Base.getBase();
1763 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1764 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1766 for (const auto &B : RD->bases()) {
1767 // Ignore virtual bases, we'll emit them later.
1771 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1773 // Ignore bases that don't have a vtable.
1774 if (!BaseDecl->isDynamicClass())
1777 if (isBuildingConstructorVTable()) {
1778 // Itanium C++ ABI 2.6.4:
1779 // Some of the base class subobjects may not need construction virtual
1780 // tables, which will therefore not be present in the construction
1781 // virtual table group, even though the subobject virtual tables are
1782 // present in the main virtual table group for the complete object.
1783 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1787 // Get the base offset of this base.
1788 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1789 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1791 CharUnits BaseOffsetInLayoutClass =
1792 OffsetInLayoutClass + RelativeBaseOffset;
1794 // Don't emit a secondary vtable for a primary base. We might however want
1795 // to emit secondary vtables for other bases of this base.
1796 if (BaseDecl == PrimaryBase) {
1797 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1798 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1802 // Layout the primary vtable (and any secondary vtables) for this base.
1803 LayoutPrimaryAndSecondaryVTables(
1804 BaseSubobject(BaseDecl, BaseOffset),
1805 BaseIsMorallyVirtual,
1806 /*BaseIsVirtualInLayoutClass=*/false,
1807 BaseOffsetInLayoutClass);
1811 void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1812 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1813 VisitedVirtualBasesSetTy &VBases) {
1814 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1816 // Check if this base has a primary base.
1817 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1819 // Check if it's virtual.
1820 if (Layout.isPrimaryBaseVirtual()) {
1821 bool IsPrimaryVirtualBase = true;
1823 if (isBuildingConstructorVTable()) {
1824 // Check if the base is actually a primary base in the class we use for
1826 const ASTRecordLayout &LayoutClassLayout =
1827 Context.getASTRecordLayout(LayoutClass);
1829 CharUnits PrimaryBaseOffsetInLayoutClass =
1830 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1832 // We know that the base is not a primary base in the layout class if
1833 // the base offsets are different.
1834 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1835 IsPrimaryVirtualBase = false;
1838 if (IsPrimaryVirtualBase)
1839 PrimaryVirtualBases.insert(PrimaryBase);
1843 // Traverse bases, looking for more primary virtual bases.
1844 for (const auto &B : RD->bases()) {
1845 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1847 CharUnits BaseOffsetInLayoutClass;
1849 if (B.isVirtual()) {
1850 if (!VBases.insert(BaseDecl).second)
1853 const ASTRecordLayout &LayoutClassLayout =
1854 Context.getASTRecordLayout(LayoutClass);
1856 BaseOffsetInLayoutClass =
1857 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1859 BaseOffsetInLayoutClass =
1860 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1863 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1867 void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1868 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
1869 // Itanium C++ ABI 2.5.2:
1870 // Then come the virtual base virtual tables, also in inheritance graph
1871 // order, and again excluding primary bases (which share virtual tables with
1872 // the classes for which they are primary).
1873 for (const auto &B : RD->bases()) {
1874 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1876 // Check if this base needs a vtable. (If it's virtual, not a primary base
1877 // of some other class, and we haven't visited it before).
1878 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1879 !PrimaryVirtualBases.count(BaseDecl) &&
1880 VBases.insert(BaseDecl).second) {
1881 const ASTRecordLayout &MostDerivedClassLayout =
1882 Context.getASTRecordLayout(MostDerivedClass);
1883 CharUnits BaseOffset =
1884 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1886 const ASTRecordLayout &LayoutClassLayout =
1887 Context.getASTRecordLayout(LayoutClass);
1888 CharUnits BaseOffsetInLayoutClass =
1889 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1891 LayoutPrimaryAndSecondaryVTables(
1892 BaseSubobject(BaseDecl, BaseOffset),
1893 /*BaseIsMorallyVirtual=*/true,
1894 /*BaseIsVirtualInLayoutClass=*/true,
1895 BaseOffsetInLayoutClass);
1898 // We only need to check the base for virtual base vtables if it actually
1899 // has virtual bases.
1900 if (BaseDecl->getNumVBases())
1901 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1905 /// dumpLayout - Dump the vtable layout.
1906 void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
1907 // FIXME: write more tests that actually use the dumpLayout output to prevent
1908 // ItaniumVTableBuilder regressions.
1910 if (isBuildingConstructorVTable()) {
1911 Out << "Construction vtable for ('";
1912 MostDerivedClass->printQualifiedName(Out);
1914 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1915 LayoutClass->printQualifiedName(Out);
1917 Out << "Vtable for '";
1918 MostDerivedClass->printQualifiedName(Out);
1920 Out << "' (" << Components.size() << " entries).\n";
1922 // Iterate through the address points and insert them into a new map where
1923 // they are keyed by the index and not the base object.
1924 // Since an address point can be shared by multiple subobjects, we use an
1926 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1927 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1928 E = AddressPoints.end(); I != E; ++I) {
1929 const BaseSubobject& Base = I->first;
1930 uint64_t Index = I->second;
1932 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1935 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1938 Out << llvm::format("%4d | ", I);
1940 const VTableComponent &Component = Components[I];
1942 // Dump the component.
1943 switch (Component.getKind()) {
1945 case VTableComponent::CK_VCallOffset:
1946 Out << "vcall_offset ("
1947 << Component.getVCallOffset().getQuantity()
1951 case VTableComponent::CK_VBaseOffset:
1952 Out << "vbase_offset ("
1953 << Component.getVBaseOffset().getQuantity()
1957 case VTableComponent::CK_OffsetToTop:
1958 Out << "offset_to_top ("
1959 << Component.getOffsetToTop().getQuantity()
1963 case VTableComponent::CK_RTTI:
1964 Component.getRTTIDecl()->printQualifiedName(Out);
1968 case VTableComponent::CK_FunctionPointer: {
1969 const CXXMethodDecl *MD = Component.getFunctionDecl();
1972 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1978 if (MD->isDeleted())
1979 Out << " [deleted]";
1981 ThunkInfo Thunk = VTableThunks.lookup(I);
1982 if (!Thunk.isEmpty()) {
1983 // If this function pointer has a return adjustment, dump it.
1984 if (!Thunk.Return.isEmpty()) {
1985 Out << "\n [return adjustment: ";
1986 Out << Thunk.Return.NonVirtual << " non-virtual";
1988 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1989 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
1990 Out << " vbase offset offset";
1996 // If this function pointer has a 'this' pointer adjustment, dump it.
1997 if (!Thunk.This.isEmpty()) {
1998 Out << "\n [this adjustment: ";
1999 Out << Thunk.This.NonVirtual << " non-virtual";
2001 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2002 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2003 Out << " vcall offset offset";
2013 case VTableComponent::CK_CompleteDtorPointer:
2014 case VTableComponent::CK_DeletingDtorPointer: {
2016 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2018 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2020 DD->printQualifiedName(Out);
2022 Out << "() [complete]";
2024 Out << "() [deleting]";
2029 ThunkInfo Thunk = VTableThunks.lookup(I);
2030 if (!Thunk.isEmpty()) {
2031 // If this destructor has a 'this' pointer adjustment, dump it.
2032 if (!Thunk.This.isEmpty()) {
2033 Out << "\n [this adjustment: ";
2034 Out << Thunk.This.NonVirtual << " non-virtual";
2036 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2037 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2038 Out << " vcall offset offset";
2048 case VTableComponent::CK_UnusedFunctionPointer: {
2049 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2052 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2054 Out << "[unused] " << Str;
2063 // Dump the next address point.
2064 uint64_t NextIndex = Index + 1;
2065 if (AddressPointsByIndex.count(NextIndex)) {
2066 if (AddressPointsByIndex.count(NextIndex) == 1) {
2067 const BaseSubobject &Base =
2068 AddressPointsByIndex.find(NextIndex)->second;
2071 Base.getBase()->printQualifiedName(Out);
2072 Out << ", " << Base.getBaseOffset().getQuantity();
2073 Out << ") vtable address --\n";
2075 CharUnits BaseOffset =
2076 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2078 // We store the class names in a set to get a stable order.
2079 std::set<std::string> ClassNames;
2080 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2081 AddressPointsByIndex.lower_bound(NextIndex), E =
2082 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2083 assert(I->second.getBaseOffset() == BaseOffset &&
2084 "Invalid base offset!");
2085 const CXXRecordDecl *RD = I->second.getBase();
2086 ClassNames.insert(RD->getQualifiedNameAsString());
2089 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2090 E = ClassNames.end(); I != E; ++I) {
2091 Out << " -- (" << *I;
2092 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2100 if (isBuildingConstructorVTable())
2103 if (MostDerivedClass->getNumVBases()) {
2104 // We store the virtual base class names and their offsets in a map to get
2107 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2108 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2109 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2110 std::string ClassName = I->first->getQualifiedNameAsString();
2111 CharUnits OffsetOffset = I->second;
2112 ClassNamesAndOffsets.insert(
2113 std::make_pair(ClassName, OffsetOffset));
2116 Out << "Virtual base offset offsets for '";
2117 MostDerivedClass->printQualifiedName(Out);
2119 Out << ClassNamesAndOffsets.size();
2120 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2122 for (std::map<std::string, CharUnits>::const_iterator I =
2123 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2125 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2130 if (!Thunks.empty()) {
2131 // We store the method names in a map to get a stable order.
2132 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2134 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2136 const CXXMethodDecl *MD = I->first;
2137 std::string MethodName =
2138 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2141 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2144 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2145 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2147 const std::string &MethodName = I->first;
2148 const CXXMethodDecl *MD = I->second;
2150 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2151 std::sort(ThunksVector.begin(), ThunksVector.end(),
2152 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2153 assert(LHS.Method == nullptr && RHS.Method == nullptr);
2154 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
2157 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2158 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2160 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2161 const ThunkInfo &Thunk = ThunksVector[I];
2163 Out << llvm::format("%4d | ", I);
2165 // If this function pointer has a return pointer adjustment, dump it.
2166 if (!Thunk.Return.isEmpty()) {
2167 Out << "return adjustment: " << Thunk.Return.NonVirtual;
2168 Out << " non-virtual";
2169 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2170 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
2171 Out << " vbase offset offset";
2174 if (!Thunk.This.isEmpty())
2178 // If this function pointer has a 'this' pointer adjustment, dump it.
2179 if (!Thunk.This.isEmpty()) {
2180 Out << "this adjustment: ";
2181 Out << Thunk.This.NonVirtual << " non-virtual";
2183 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2184 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2185 Out << " vcall offset offset";
2196 // Compute the vtable indices for all the member functions.
2197 // Store them in a map keyed by the index so we'll get a sorted table.
2198 std::map<uint64_t, std::string> IndicesMap;
2200 for (const auto *MD : MostDerivedClass->methods()) {
2201 // We only want virtual member functions.
2202 if (!MD->isVirtual())
2204 MD = MD->getCanonicalDecl();
2206 std::string MethodName =
2207 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2210 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2211 GlobalDecl GD(DD, Dtor_Complete);
2212 assert(MethodVTableIndices.count(GD));
2213 uint64_t VTableIndex = MethodVTableIndices[GD];
2214 IndicesMap[VTableIndex] = MethodName + " [complete]";
2215 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
2217 assert(MethodVTableIndices.count(MD));
2218 IndicesMap[MethodVTableIndices[MD]] = MethodName;
2222 // Print the vtable indices for all the member functions.
2223 if (!IndicesMap.empty()) {
2224 Out << "VTable indices for '";
2225 MostDerivedClass->printQualifiedName(Out);
2226 Out << "' (" << IndicesMap.size() << " entries).\n";
2228 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2229 E = IndicesMap.end(); I != E; ++I) {
2230 uint64_t VTableIndex = I->first;
2231 const std::string &MethodName = I->second;
2233 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
2242 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2243 const VTableComponent *VTableComponents,
2244 uint64_t NumVTableThunks,
2245 const VTableThunkTy *VTableThunks,
2246 const AddressPointsMapTy &AddressPoints,
2247 bool IsMicrosoftABI)
2248 : NumVTableComponents(NumVTableComponents),
2249 VTableComponents(new VTableComponent[NumVTableComponents]),
2250 NumVTableThunks(NumVTableThunks),
2251 VTableThunks(new VTableThunkTy[NumVTableThunks]),
2252 AddressPoints(AddressPoints),
2253 IsMicrosoftABI(IsMicrosoftABI) {
2254 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2255 this->VTableComponents.get());
2256 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2257 this->VTableThunks.get());
2258 std::sort(this->VTableThunks.get(),
2259 this->VTableThunks.get() + NumVTableThunks,
2260 [](const VTableLayout::VTableThunkTy &LHS,
2261 const VTableLayout::VTableThunkTy &RHS) {
2262 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2263 "Different thunks should have unique indices!");
2264 return LHS.first < RHS.first;
2268 VTableLayout::~VTableLayout() { }
2270 ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
2271 : VTableContextBase(/*MS=*/false) {}
2273 ItaniumVTableContext::~ItaniumVTableContext() {
2274 llvm::DeleteContainerSeconds(VTableLayouts);
2277 uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
2278 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2279 if (I != MethodVTableIndices.end())
2282 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2284 computeVTableRelatedInformation(RD);
2286 I = MethodVTableIndices.find(GD);
2287 assert(I != MethodVTableIndices.end() && "Did not find index!");
2292 ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2293 const CXXRecordDecl *VBase) {
2294 ClassPairTy ClassPair(RD, VBase);
2296 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2297 VirtualBaseClassOffsetOffsets.find(ClassPair);
2298 if (I != VirtualBaseClassOffsetOffsets.end())
2301 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/nullptr,
2302 BaseSubobject(RD, CharUnits::Zero()),
2303 /*BaseIsVirtual=*/false,
2304 /*OffsetInLayoutClass=*/CharUnits::Zero());
2306 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2307 Builder.getVBaseOffsetOffsets().begin(),
2308 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2309 // Insert all types.
2310 ClassPairTy ClassPair(RD, I->first);
2312 VirtualBaseClassOffsetOffsets.insert(
2313 std::make_pair(ClassPair, I->second));
2316 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2317 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2322 static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
2323 SmallVector<VTableLayout::VTableThunkTy, 1>
2324 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2326 return new VTableLayout(Builder.getNumVTableComponents(),
2327 Builder.vtable_component_begin(),
2328 VTableThunks.size(),
2329 VTableThunks.data(),
2330 Builder.getAddressPoints(),
2331 /*IsMicrosoftABI=*/false);
2335 ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
2336 const VTableLayout *&Entry = VTableLayouts[RD];
2338 // Check if we've computed this information before.
2342 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2343 /*MostDerivedClassIsVirtual=*/0, RD);
2344 Entry = CreateVTableLayout(Builder);
2346 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2347 Builder.vtable_indices_end());
2349 // Add the known thunks.
2350 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2352 // If we don't have the vbase information for this class, insert it.
2353 // getVirtualBaseOffsetOffset will compute it separately without computing
2354 // the rest of the vtable related information.
2355 if (!RD->getNumVBases())
2358 const CXXRecordDecl *VBase =
2359 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
2361 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2364 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2365 I = Builder.getVBaseOffsetOffsets().begin(),
2366 E = Builder.getVBaseOffsetOffsets().end();
2368 // Insert all types.
2369 ClassPairTy ClassPair(RD, I->first);
2371 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2375 VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2376 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2377 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2378 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2379 MostDerivedClassIsVirtual, LayoutClass);
2380 return CreateVTableLayout(Builder);
2385 // Vtables in the Microsoft ABI are different from the Itanium ABI.
2387 // The main differences are:
2388 // 1. Separate vftable and vbtable.
2390 // 2. Each subobject with a vfptr gets its own vftable rather than an address
2391 // point in a single vtable shared between all the subobjects.
2392 // Each vftable is represented by a separate section and virtual calls
2393 // must be done using the vftable which has a slot for the function to be
2396 // 3. Virtual method definitions expect their 'this' parameter to point to the
2397 // first vfptr whose table provides a compatible overridden method. In many
2398 // cases, this permits the original vf-table entry to directly call
2399 // the method instead of passing through a thunk.
2400 // See example before VFTableBuilder::ComputeThisOffset below.
2402 // A compatible overridden method is one which does not have a non-trivial
2403 // covariant-return adjustment.
2405 // The first vfptr is the one with the lowest offset in the complete-object
2406 // layout of the defining class, and the method definition will subtract
2407 // that constant offset from the parameter value to get the real 'this'
2408 // value. Therefore, if the offset isn't really constant (e.g. if a virtual
2409 // function defined in a virtual base is overridden in a more derived
2410 // virtual base and these bases have a reverse order in the complete
2411 // object), the vf-table may require a this-adjustment thunk.
2413 // 4. vftables do not contain new entries for overrides that merely require
2414 // this-adjustment. Together with #3, this keeps vf-tables smaller and
2415 // eliminates the need for this-adjustment thunks in many cases, at the cost
2416 // of often requiring redundant work to adjust the "this" pointer.
2418 // 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2419 // Vtordisps are emitted into the class layout if a class has
2420 // a) a user-defined ctor/dtor
2422 // b) a method overriding a method in a virtual base.
2424 // To get a better understanding of this code,
2425 // you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
2427 class VFTableBuilder {
2429 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
2431 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2432 MethodVFTableLocationsTy;
2434 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2435 method_locations_range;
2438 /// VTables - Global vtable information.
2439 MicrosoftVTableContext &VTables;
2441 /// Context - The ASTContext which we will use for layout information.
2442 ASTContext &Context;
2444 /// MostDerivedClass - The most derived class for which we're building this
2446 const CXXRecordDecl *MostDerivedClass;
2448 const ASTRecordLayout &MostDerivedClassLayout;
2450 const VPtrInfo &WhichVFPtr;
2452 /// FinalOverriders - The final overriders of the most derived class.
2453 const FinalOverriders Overriders;
2455 /// Components - The components of the vftable being built.
2456 SmallVector<VTableComponent, 64> Components;
2458 MethodVFTableLocationsTy MethodVFTableLocations;
2460 /// \brief Does this class have an RTTI component?
2461 bool HasRTTIComponent;
2463 /// MethodInfo - Contains information about a method in a vtable.
2464 /// (Used for computing 'this' pointer adjustment thunks.
2466 /// VBTableIndex - The nonzero index in the vbtable that
2467 /// this method's base has, or zero.
2468 const uint64_t VBTableIndex;
2470 /// VFTableIndex - The index in the vftable that this method has.
2471 const uint64_t VFTableIndex;
2473 /// Shadowed - Indicates if this vftable slot is shadowed by
2474 /// a slot for a covariant-return override. If so, it shouldn't be printed
2475 /// or used for vcalls in the most derived class.
2478 /// UsesExtraSlot - Indicates if this vftable slot was created because
2479 /// any of the overridden slots required a return adjusting thunk.
2482 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2483 bool UsesExtraSlot = false)
2484 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2485 Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2488 : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2489 UsesExtraSlot(false) {}
2492 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2494 /// MethodInfoMap - The information for all methods in the vftable we're
2495 /// currently building.
2496 MethodInfoMapTy MethodInfoMap;
2498 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2500 /// VTableThunks - The thunks by vftable index in the vftable currently being
2502 VTableThunksMapTy VTableThunks;
2504 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2505 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2507 /// Thunks - A map that contains all the thunks needed for all methods in the
2508 /// most derived class for which the vftable is currently being built.
2511 /// AddThunk - Add a thunk for the given method.
2512 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2513 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2515 // Check if we have this thunk already.
2516 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2520 ThunksVector.push_back(Thunk);
2523 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2524 /// method, relative to the beginning of the MostDerivedClass.
2525 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
2527 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2528 CharUnits ThisOffset, ThisAdjustment &TA);
2530 /// AddMethod - Add a single virtual member function to the vftable
2531 /// components vector.
2532 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
2533 if (!TI.isEmpty()) {
2534 VTableThunks[Components.size()] = TI;
2537 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2538 assert(TI.Return.isEmpty() &&
2539 "Destructor can't have return adjustment!");
2540 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2542 Components.push_back(VTableComponent::MakeFunction(MD));
2546 /// AddMethods - Add the methods of this base subobject and the relevant
2547 /// subbases to the vftable we're currently laying out.
2548 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2549 const CXXRecordDecl *LastVBase,
2550 BasesSetVectorTy &VisitedBases);
2552 void LayoutVFTable() {
2553 // RTTI data goes before all other entries.
2554 if (HasRTTIComponent)
2555 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
2557 BasesSetVectorTy VisitedBases;
2558 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
2560 assert((HasRTTIComponent ? Components.size() - 1 : Components.size()) &&
2561 "vftable can't be empty");
2563 assert(MethodVFTableLocations.empty());
2564 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2565 E = MethodInfoMap.end(); I != E; ++I) {
2566 const CXXMethodDecl *MD = I->first;
2567 const MethodInfo &MI = I->second;
2568 // Skip the methods that the MostDerivedClass didn't override
2569 // and the entries shadowed by return adjusting thunks.
2570 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2572 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2573 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
2574 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2575 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2577 MethodVFTableLocations[MD] = Loc;
2583 VFTableBuilder(MicrosoftVTableContext &VTables,
2584 const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
2586 Context(MostDerivedClass->getASTContext()),
2587 MostDerivedClass(MostDerivedClass),
2588 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2590 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2591 // Only include the RTTI component if we know that we will provide a
2592 // definition of the vftable.
2593 HasRTTIComponent = Context.getLangOpts().RTTIData &&
2594 !MostDerivedClass->hasAttr<DLLImportAttr>() &&
2595 MostDerivedClass->getTemplateSpecializationKind() !=
2596 TSK_ExplicitInstantiationDeclaration;
2600 if (Context.getLangOpts().DumpVTableLayouts)
2601 dumpLayout(llvm::outs());
2604 uint64_t getNumThunks() const { return Thunks.size(); }
2606 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2608 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2610 method_locations_range vtable_locations() const {
2611 return method_locations_range(MethodVFTableLocations.begin(),
2612 MethodVFTableLocations.end());
2615 uint64_t getNumVTableComponents() const { return Components.size(); }
2617 const VTableComponent *vtable_component_begin() const {
2618 return Components.begin();
2621 const VTableComponent *vtable_component_end() const {
2622 return Components.end();
2625 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2626 return VTableThunks.begin();
2629 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2630 return VTableThunks.end();
2633 void dumpLayout(raw_ostream &);
2636 /// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2637 /// that define the given method.
2638 struct InitialOverriddenDefinitionCollector {
2639 BasesSetVectorTy Bases;
2640 OverriddenMethodsSetTy VisitedOverriddenMethods;
2642 bool visit(const CXXMethodDecl *OverriddenMD) {
2643 if (OverriddenMD->size_overridden_methods() == 0)
2644 Bases.insert(OverriddenMD->getParent());
2645 // Don't recurse on this method if we've already collected it.
2646 return VisitedOverriddenMethods.insert(OverriddenMD).second;
2652 static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2653 CXXBasePath &Path, void *BasesSet) {
2654 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2655 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2658 // Let's study one class hierarchy as an example:
2660 // virtual void f();
2664 // struct B : virtual A {
2665 // virtual void f();
2670 // 0 | (A vftable pointer)
2674 // 0 | (B vbtable pointer)
2675 // 4 | struct A (virtual base)
2676 // 4 | (A vftable pointer)
2679 // Let's assume we have a pointer to the A part of an object of dynamic type B:
2684 // In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2685 // "this" parameter to point at the A subobject, which is B+4.
2686 // In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
2687 // performed as a *static* adjustment.
2689 // Interesting thing happens when we alter the relative placement of A and B
2690 // subobjects in a class:
2691 // struct C : virtual B { };
2697 // Respective record layout is:
2698 // 0 | (C vbtable pointer)
2699 // 4 | struct A (virtual base)
2700 // 4 | (A vftable pointer)
2702 // 12 | struct B (virtual base)
2703 // 12 | (B vbtable pointer)
2705 // The final overrider of f() in class C is still B::f(), so B+4 should be
2706 // passed as "this" to that code. However, "a" points at B-8, so the respective
2707 // vftable entry should hold a thunk that adds 12 to the "this" argument before
2708 // performing a tail call to B::f().
2710 // With this example in mind, we can now calculate the 'this' argument offset
2711 // for the given method, relative to the beginning of the MostDerivedClass.
2713 VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
2714 InitialOverriddenDefinitionCollector Collector;
2715 visitAllOverriddenMethods(Overrider.Method, Collector);
2717 // If there are no overrides then 'this' is located
2718 // in the base that defines the method.
2719 if (Collector.Bases.size() == 0)
2720 return Overrider.Offset;
2723 Overrider.Method->getParent()->lookupInBases(BaseInSet, &Collector.Bases,
2726 // This will hold the smallest this offset among overridees of MD.
2727 // This implies that an offset of a non-virtual base will dominate an offset
2728 // of a virtual base to potentially reduce the number of thunks required
2729 // in the derived classes that inherit this method.
2733 const ASTRecordLayout &OverriderRDLayout =
2734 Context.getASTRecordLayout(Overrider.Method->getParent());
2735 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2737 const CXXBasePath &Path = (*I);
2738 CharUnits ThisOffset = Overrider.Offset;
2739 CharUnits LastVBaseOffset;
2741 // For each path from the overrider to the parents of the overridden
2742 // methods, traverse the path, calculating the this offset in the most
2744 for (int J = 0, F = Path.size(); J != F; ++J) {
2745 const CXXBasePathElement &Element = Path[J];
2746 QualType CurTy = Element.Base->getType();
2747 const CXXRecordDecl *PrevRD = Element.Class,
2748 *CurRD = CurTy->getAsCXXRecordDecl();
2749 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2751 if (Element.Base->isVirtual()) {
2752 // The interesting things begin when you have virtual inheritance.
2753 // The final overrider will use a static adjustment equal to the offset
2754 // of the vbase in the final overrider class.
2755 // For example, if the final overrider is in a vbase B of the most
2756 // derived class and it overrides a method of the B's own vbase A,
2757 // it uses A* as "this". In its prologue, it can cast A* to B* with
2758 // a static offset. This offset is used regardless of the actual
2759 // offset of A from B in the most derived class, requiring an
2760 // this-adjusting thunk in the vftable if A and B are laid out
2761 // differently in the most derived class.
2762 LastVBaseOffset = ThisOffset =
2763 Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
2765 ThisOffset += Layout.getBaseClassOffset(CurRD);
2769 if (isa<CXXDestructorDecl>(Overrider.Method)) {
2770 if (LastVBaseOffset.isZero()) {
2771 // If a "Base" class has at least one non-virtual base with a virtual
2772 // destructor, the "Base" virtual destructor will take the address
2773 // of the "Base" subobject as the "this" argument.
2774 ThisOffset = Overrider.Offset;
2776 // A virtual destructor of a virtual base takes the address of the
2777 // virtual base subobject as the "this" argument.
2778 ThisOffset = LastVBaseOffset;
2782 if (Ret > ThisOffset || First) {
2788 assert(!First && "Method not found in the given subobject?");
2792 // Things are getting even more complex when the "this" adjustment has to
2793 // use a dynamic offset instead of a static one, or even two dynamic offsets.
2794 // This is sometimes required when a virtual call happens in the middle of
2795 // a non-most-derived class construction or destruction.
2797 // Let's take a look at the following example:
2799 // virtual void f();
2802 // void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
2804 // struct B : virtual A {
2805 // virtual void f();
2811 // struct C : virtual B {
2812 // virtual void f();
2815 // Record layouts for these classes are:
2817 // 0 | (A vftable pointer)
2820 // 0 | (B vbtable pointer)
2821 // 4 | (vtordisp for vbase A)
2822 // 8 | struct A (virtual base)
2823 // 8 | (A vftable pointer)
2826 // 0 | (C vbtable pointer)
2827 // 4 | (vtordisp for vbase A)
2828 // 8 | struct A (virtual base) // A precedes B!
2829 // 8 | (A vftable pointer)
2830 // 12 | struct B (virtual base)
2831 // 12 | (B vbtable pointer)
2833 // When one creates an object of type C, the C constructor:
2834 // - initializes all the vbptrs, then
2835 // - calls the A subobject constructor
2836 // (initializes A's vfptr with an address of A vftable), then
2837 // - calls the B subobject constructor
2838 // (initializes A's vfptr with an address of B vftable and vtordisp for A),
2839 // that in turn calls foo(), then
2840 // - initializes A's vfptr with an address of C vftable and zeroes out the
2842 // FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2843 // without vtordisp thunks?
2844 // FIXME: how are vtordisp handled in the presence of nooverride/final?
2846 // When foo() is called, an object with a layout of class C has a vftable
2847 // referencing B::f() that assumes a B layout, so the "this" adjustments are
2848 // incorrect, unless an extra adjustment is done. This adjustment is called
2849 // "vtordisp adjustment". Vtordisp basically holds the difference between the
2850 // actual location of a vbase in the layout class and the location assumed by
2851 // the vftable of the class being constructed/destructed. Vtordisp is only
2852 // needed if "this" escapes a
2853 // structor (or we can't prove otherwise).
2854 // [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2855 // estimation of a dynamic adjustment]
2857 // foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2858 // so it just passes that pointer as "this" in a virtual call.
2859 // If there was no vtordisp, that would just dispatch to B::f().
2860 // However, B::f() assumes B+8 is passed as "this",
2861 // yet the pointer foo() passes along is B-4 (i.e. C+8).
2862 // An extra adjustment is needed, so we emit a thunk into the B vftable.
2863 // This vtordisp thunk subtracts the value of vtordisp
2864 // from the "this" argument (-12) before making a tailcall to B::f().
2866 // Let's consider an even more complex example:
2867 // struct D : virtual B, virtual C {
2874 // 0 | (D vbtable pointer)
2875 // 4 | (vtordisp for vbase A)
2876 // 8 | struct A (virtual base) // A precedes both B and C!
2877 // 8 | (A vftable pointer)
2878 // 12 | struct B (virtual base) // B precedes C!
2879 // 12 | (B vbtable pointer)
2880 // 16 | struct C (virtual base)
2881 // 16 | (C vbtable pointer)
2883 // When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2884 // to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
2885 // passes along A, which is C-8. The A vtordisp holds
2886 // "D.vbptr[index_of_A] - offset_of_A_in_D"
2887 // and we statically know offset_of_A_in_D, so can get a pointer to D.
2888 // When we know it, we can make an extra vbtable lookup to locate the C vbase
2889 // and one extra static adjustment to calculate the expected value of C+8.
2890 void VFTableBuilder::CalculateVtordispAdjustment(
2891 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2892 ThisAdjustment &TA) {
2893 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2894 MostDerivedClassLayout.getVBaseOffsetsMap();
2895 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
2896 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
2897 assert(VBaseMapEntry != VBaseMap.end());
2899 // If there's no vtordisp or the final overrider is defined in the same vbase
2900 // as the initial declaration, we don't need any vtordisp adjustment.
2901 if (!VBaseMapEntry->second.hasVtorDisp() ||
2902 Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
2905 // OK, now we know we need to use a vtordisp thunk.
2906 // The implicit vtordisp field is located right before the vbase.
2907 CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
2908 TA.Virtual.Microsoft.VtordispOffset =
2909 (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
2911 // A simple vtordisp thunk will suffice if the final overrider is defined
2912 // in either the most derived class or its non-virtual base.
2913 if (Overrider.Method->getParent() == MostDerivedClass ||
2914 !Overrider.VirtualBase)
2917 // Otherwise, we need to do use the dynamic offset of the final overrider
2918 // in order to get "this" adjustment right.
2919 TA.Virtual.Microsoft.VBPtrOffset =
2920 (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
2921 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2922 TA.Virtual.Microsoft.VBOffsetOffset =
2923 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2924 VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
2926 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2929 static void GroupNewVirtualOverloads(
2930 const CXXRecordDecl *RD,
2931 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2932 // Put the virtual methods into VirtualMethods in the proper order:
2933 // 1) Group overloads by declaration name. New groups are added to the
2934 // vftable in the order of their first declarations in this class
2935 // (including overrides and non-virtual methods).
2936 // 2) In each group, new overloads appear in the reverse order of declaration.
2937 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2938 SmallVector<MethodGroup, 10> Groups;
2939 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2940 VisitedGroupIndicesTy VisitedGroupIndices;
2941 for (const auto *MD : RD->methods()) {
2942 MD = MD->getCanonicalDecl();
2943 VisitedGroupIndicesTy::iterator J;
2945 std::tie(J, Inserted) = VisitedGroupIndices.insert(
2946 std::make_pair(MD->getDeclName(), Groups.size()));
2948 Groups.push_back(MethodGroup());
2949 if (MD->isVirtual())
2950 Groups[J->second].push_back(MD);
2953 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2954 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2957 static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2958 for (const auto &B : RD->bases()) {
2959 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2965 void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2966 const CXXRecordDecl *LastVBase,
2967 BasesSetVectorTy &VisitedBases) {
2968 const CXXRecordDecl *RD = Base.getBase();
2969 if (!RD->isPolymorphic())
2972 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2974 // See if this class expands a vftable of the base we look at, which is either
2975 // the one defined by the vfptr base path or the primary base of the current
2977 const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
2978 CharUnits NextBaseOffset;
2979 if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2980 NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
2981 if (isDirectVBase(NextBase, RD)) {
2982 NextLastVBase = NextBase;
2983 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2986 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2988 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2989 assert(!Layout.isPrimaryBaseVirtual() &&
2990 "No primary virtual bases in this ABI");
2991 NextBase = PrimaryBase;
2992 NextBaseOffset = Base.getBaseOffset();
2996 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2997 NextLastVBase, VisitedBases);
2998 if (!VisitedBases.insert(NextBase))
2999 llvm_unreachable("Found a duplicate primary base!");
3002 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
3003 // Put virtual methods in the proper order.
3004 GroupNewVirtualOverloads(RD, VirtualMethods);
3006 // Now go through all virtual member functions and add them to the current
3007 // vftable. This is done by
3008 // - replacing overridden methods in their existing slots, as long as they
3009 // don't require return adjustment; calculating This adjustment if needed.
3010 // - adding new slots for methods of the current base not present in any
3012 // - adding new slots for methods that require Return adjustment.
3013 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
3014 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
3015 const CXXMethodDecl *MD = VirtualMethods[I];
3017 FinalOverriders::OverriderInfo FinalOverrider =
3018 Overriders.getOverrider(MD, Base.getBaseOffset());
3019 const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
3020 const CXXMethodDecl *OverriddenMD =
3021 FindNearestOverriddenMethod(MD, VisitedBases);
3023 ThisAdjustment ThisAdjustmentOffset;
3024 bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
3025 CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
3026 ThisAdjustmentOffset.NonVirtual =
3027 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
3028 if ((OverriddenMD || FinalOverriderMD != MD) &&
3029 WhichVFPtr.getVBaseWithVPtr())
3030 CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
3031 ThisAdjustmentOffset);
3034 // If MD overrides anything in this vftable, we need to update the
3036 MethodInfoMapTy::iterator OverriddenMDIterator =
3037 MethodInfoMap.find(OverriddenMD);
3039 // If the overridden method went to a different vftable, skip it.
3040 if (OverriddenMDIterator == MethodInfoMap.end())
3043 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
3045 // Let's check if the overrider requires any return adjustments.
3046 // We must create a new slot if the MD's return type is not trivially
3047 // convertible to the OverriddenMD's one.
3048 // Once a chain of method overrides adds a return adjusting vftable slot,
3049 // all subsequent overrides will also use an extra method slot.
3050 ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
3051 Context, MD, OverriddenMD).isEmpty() ||
3052 OverriddenMethodInfo.UsesExtraSlot;
3054 if (!ReturnAdjustingThunk) {
3055 // No return adjustment needed - just replace the overridden method info
3056 // with the current info.
3057 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
3058 OverriddenMethodInfo.VFTableIndex);
3059 MethodInfoMap.erase(OverriddenMDIterator);
3061 assert(!MethodInfoMap.count(MD) &&
3062 "Should not have method info for this method yet!");
3063 MethodInfoMap.insert(std::make_pair(MD, MI));
3067 // In case we need a return adjustment, we'll add a new slot for
3068 // the overrider. Mark the overriden method as shadowed by the new slot.
3069 OverriddenMethodInfo.Shadowed = true;
3071 // Force a special name mangling for a return-adjusting thunk
3072 // unless the method is the final overrider without this adjustment.
3073 ForceReturnAdjustmentMangling =
3074 !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
3075 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
3076 MD->size_overridden_methods()) {
3077 // Skip methods that don't belong to the vftable of the current class,
3078 // e.g. each method that wasn't seen in any of the visited sub-bases
3079 // but overrides multiple methods of other sub-bases.
3083 // If we got here, MD is a method not seen in any of the sub-bases or
3084 // it requires return adjustment. Insert the method info for this method.
3086 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
3087 MethodInfo MI(VBIndex,
3088 HasRTTIComponent ? Components.size() - 1 : Components.size(),
3089 ReturnAdjustingThunk);
3091 assert(!MethodInfoMap.count(MD) &&
3092 "Should not have method info for this method yet!");
3093 MethodInfoMap.insert(std::make_pair(MD, MI));
3095 // Check if this overrider needs a return adjustment.
3096 // We don't want to do this for pure virtual member functions.
3097 BaseOffset ReturnAdjustmentOffset;
3098 ReturnAdjustment ReturnAdjustment;
3099 if (!FinalOverriderMD->isPure()) {
3100 ReturnAdjustmentOffset =
3101 ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
3103 if (!ReturnAdjustmentOffset.isEmpty()) {
3104 ForceReturnAdjustmentMangling = true;
3105 ReturnAdjustment.NonVirtual =
3106 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3107 if (ReturnAdjustmentOffset.VirtualBase) {
3108 const ASTRecordLayout &DerivedLayout =
3109 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3110 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
3111 DerivedLayout.getVBPtrOffset().getQuantity();
3112 ReturnAdjustment.Virtual.Microsoft.VBIndex =
3113 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3114 ReturnAdjustmentOffset.VirtualBase);
3118 AddMethod(FinalOverriderMD,
3119 ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3120 ForceReturnAdjustmentMangling ? MD : nullptr));
3124 static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
3125 for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
3126 E = Path.rend(); I != E; ++I) {
3128 (*I)->printQualifiedName(Out);
3133 static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3134 bool ContinueFirstLine) {
3135 const ReturnAdjustment &R = TI.Return;
3136 bool Multiline = false;
3137 const char *LinePrefix = "\n ";
3138 if (!R.isEmpty() || TI.Method) {
3139 if (!ContinueFirstLine)
3141 Out << "[return adjustment (to type '"
3142 << TI.Method->getReturnType().getCanonicalType().getAsString()
3144 if (R.Virtual.Microsoft.VBPtrOffset)
3145 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3146 if (R.Virtual.Microsoft.VBIndex)
3147 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3148 Out << R.NonVirtual << " non-virtual]";
3152 const ThisAdjustment &T = TI.This;
3154 if (Multiline || !ContinueFirstLine)
3156 Out << "[this adjustment: ";
3157 if (!TI.This.Virtual.isEmpty()) {
3158 assert(T.Virtual.Microsoft.VtordispOffset < 0);
3159 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3160 if (T.Virtual.Microsoft.VBPtrOffset) {
3161 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
3163 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3164 Out << LinePrefix << " vboffset at "
3165 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3168 Out << T.NonVirtual << " non-virtual]";
3172 void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3173 Out << "VFTable for ";
3174 PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
3176 MostDerivedClass->printQualifiedName(Out);
3177 Out << "' (" << Components.size()
3178 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
3180 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3181 Out << llvm::format("%4d | ", I);
3183 const VTableComponent &Component = Components[I];
3185 // Dump the component.
3186 switch (Component.getKind()) {
3187 case VTableComponent::CK_RTTI:
3188 Component.getRTTIDecl()->printQualifiedName(Out);
3192 case VTableComponent::CK_FunctionPointer: {
3193 const CXXMethodDecl *MD = Component.getFunctionDecl();
3195 // FIXME: Figure out how to print the real thunk type, since they can
3196 // differ in the return type.
3197 std::string Str = PredefinedExpr::ComputeName(
3198 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3203 if (MD->isDeleted())
3204 Out << " [deleted]";
3206 ThunkInfo Thunk = VTableThunks.lookup(I);
3207 if (!Thunk.isEmpty())
3208 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3213 case VTableComponent::CK_DeletingDtorPointer: {
3214 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3216 DD->printQualifiedName(Out);
3217 Out << "() [scalar deleting]";
3222 ThunkInfo Thunk = VTableThunks.lookup(I);
3223 if (!Thunk.isEmpty()) {
3224 assert(Thunk.Return.isEmpty() &&
3225 "No return adjustment needed for destructors!");
3226 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3233 DiagnosticsEngine &Diags = Context.getDiagnostics();
3234 unsigned DiagID = Diags.getCustomDiagID(
3235 DiagnosticsEngine::Error,
3236 "Unexpected vftable component type %0 for component number %1");
3237 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3238 << I << Component.getKind();
3246 if (!Thunks.empty()) {
3247 // We store the method names in a map to get a stable order.
3248 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3250 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3252 const CXXMethodDecl *MD = I->first;
3253 std::string MethodName = PredefinedExpr::ComputeName(
3254 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3256 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3259 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3260 I = MethodNamesAndDecls.begin(),
3261 E = MethodNamesAndDecls.end();
3263 const std::string &MethodName = I->first;
3264 const CXXMethodDecl *MD = I->second;
3266 ThunkInfoVectorTy ThunksVector = Thunks[MD];
3267 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
3268 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3269 // Keep different thunks with the same adjustments in the order they
3270 // were put into the vector.
3271 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
3274 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3275 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3277 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3278 const ThunkInfo &Thunk = ThunksVector[I];
3280 Out << llvm::format("%4d | ", I);
3281 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
3292 static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3293 ArrayRef<const CXXRecordDecl *> B) {
3294 for (ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(), E = B.end();
3302 static bool rebucketPaths(VPtrInfoVector &Paths);
3304 /// Produces MSVC-compatible vbtable data. The symbols produced by this
3305 /// algorithm match those produced by MSVC 2012 and newer, which is different
3308 /// MSVC 2012 appears to minimize the vbtable names using the following
3309 /// algorithm. First, walk the class hierarchy in the usual order, depth first,
3310 /// left to right, to find all of the subobjects which contain a vbptr field.
3311 /// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3312 /// record with a vbptr creates an initially empty path.
3314 /// To combine paths from child nodes, the paths are compared to check for
3315 /// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3316 /// components in the same order. Each group of ambiguous paths is extended by
3317 /// appending the class of the base from which it came. If the current class
3318 /// node produced an ambiguous path, its path is extended with the current class.
3319 /// After extending paths, MSVC again checks for ambiguity, and extends any
3320 /// ambiguous path which wasn't already extended. Because each node yields an
3321 /// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3322 /// to produce an unambiguous set of paths.
3324 /// TODO: Presumably vftables use the same algorithm.
3325 void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3326 const CXXRecordDecl *RD,
3327 VPtrInfoVector &Paths) {
3328 assert(Paths.empty());
3329 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3331 // Base case: this subobject has its own vptr.
3332 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3333 Paths.push_back(new VPtrInfo(RD));
3335 // Recursive case: get all the vbtables from our bases and remove anything
3336 // that shares a virtual base.
3337 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
3338 for (const auto &B : RD->bases()) {
3339 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3340 if (B.isVirtual() && VBasesSeen.count(Base))
3343 if (!Base->isDynamicClass())
3346 const VPtrInfoVector &BasePaths =
3347 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3349 for (VPtrInfo *BaseInfo : BasePaths) {
3350 // Don't include the path if it goes through a virtual base that we've
3351 // already included.
3352 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
3355 // Copy the path and adjust it as necessary.
3356 VPtrInfo *P = new VPtrInfo(*BaseInfo);
3358 // We mangle Base into the path if the path would've been ambiguous and it
3359 // wasn't already extended with Base.
3360 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3361 P->NextBaseToMangle = Base;
3363 // Keep track of which vtable the derived class is going to extend with
3364 // new methods or bases. We append to either the vftable of our primary
3365 // base, or the first non-virtual base that has a vbtable.
3366 if (P->ReusingBase == Base &&
3367 Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3368 : Layout.getPrimaryBase()))
3369 P->ReusingBase = RD;
3371 // Keep track of the full adjustment from the MDC to this vtable. The
3372 // adjustment is captured by an optional vbase and a non-virtual offset.
3374 P->ContainingVBases.push_back(Base);
3375 else if (P->ContainingVBases.empty())
3376 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3378 // Update the full offset in the MDC.
3379 P->FullOffsetInMDC = P->NonVirtualOffset;
3380 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3381 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3387 VBasesSeen.insert(Base);
3389 // After visiting any direct base, we've transitively visited all of its
3390 // morally virtual bases.
3391 for (const auto &VB : Base->vbases())
3392 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
3395 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3396 // paths in ambiguous buckets.
3397 bool Changed = true;
3399 Changed = rebucketPaths(Paths);
3402 static bool extendPath(VPtrInfo *P) {
3403 if (P->NextBaseToMangle) {
3404 P->MangledPath.push_back(P->NextBaseToMangle);
3405 P->NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
3411 static bool rebucketPaths(VPtrInfoVector &Paths) {
3412 // What we're essentially doing here is bucketing together ambiguous paths.
3413 // Any bucket with more than one path in it gets extended by NextBase, which
3414 // is usually the direct base of the inherited the vbptr. This code uses a
3415 // sorted vector to implement a multiset to form the buckets. Note that the
3416 // ordering is based on pointers, but it doesn't change our output order. The
3417 // current algorithm is designed to match MSVC 2012's names.
3418 VPtrInfoVector PathsSorted(Paths);
3419 std::sort(PathsSorted.begin(), PathsSorted.end(),
3420 [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3421 return LHS->MangledPath < RHS->MangledPath;
3423 bool Changed = false;
3424 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3425 // Scan forward to find the end of the bucket.
3426 size_t BucketStart = I;
3429 } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3430 PathsSorted[I]->MangledPath);
3432 // If this bucket has multiple paths, extend them all.
3433 if (I - BucketStart > 1) {
3434 for (size_t II = BucketStart; II != I; ++II)
3435 Changed |= extendPath(PathsSorted[II]);
3436 assert(Changed && "no paths were extended to fix ambiguity");
3442 MicrosoftVTableContext::~MicrosoftVTableContext() {
3443 for (auto &P : VFPtrLocations)
3444 llvm::DeleteContainerPointers(*P.second);
3445 llvm::DeleteContainerSeconds(VFPtrLocations);
3446 llvm::DeleteContainerSeconds(VFTableLayouts);
3447 llvm::DeleteContainerSeconds(VBaseInfo);
3451 typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3452 llvm::DenseSet<BaseSubobject>> FullPathTy;
3455 // This recursive function finds all paths from a subobject centered at
3456 // (RD, Offset) to the subobject located at BaseWithVPtr.
3457 static void findPathsToSubobject(ASTContext &Context,
3458 const ASTRecordLayout &MostDerivedLayout,
3459 const CXXRecordDecl *RD, CharUnits Offset,
3460 BaseSubobject BaseWithVPtr,
3461 FullPathTy &FullPath,
3462 std::list<FullPathTy> &Paths) {
3463 if (BaseSubobject(RD, Offset) == BaseWithVPtr) {
3464 Paths.push_back(FullPath);
3468 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3470 for (const CXXBaseSpecifier &BS : RD->bases()) {
3471 const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
3472 CharUnits NewOffset = BS.isVirtual()
3473 ? MostDerivedLayout.getVBaseClassOffset(Base)
3474 : Offset + Layout.getBaseClassOffset(Base);
3475 FullPath.insert(BaseSubobject(Base, NewOffset));
3476 findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
3477 BaseWithVPtr, FullPath, Paths);
3478 FullPath.pop_back();
3482 // Return the paths which are not subsets of other paths.
3483 static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3484 FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3485 for (const FullPathTy &OtherPath : FullPaths) {
3486 if (&SpecificPath == &OtherPath)
3488 if (std::all_of(SpecificPath.begin(), SpecificPath.end(),
3489 [&](const BaseSubobject &BSO) {
3490 return OtherPath.count(BSO) != 0;
3499 static CharUnits getOffsetOfFullPath(ASTContext &Context,
3500 const CXXRecordDecl *RD,
3501 const FullPathTy &FullPath) {
3502 const ASTRecordLayout &MostDerivedLayout =
3503 Context.getASTRecordLayout(RD);
3504 CharUnits Offset = CharUnits::fromQuantity(-1);
3505 for (const BaseSubobject &BSO : FullPath) {
3506 const CXXRecordDecl *Base = BSO.getBase();
3507 // The first entry in the path is always the most derived record, skip it.
3509 assert(Offset.getQuantity() == -1);
3510 Offset = CharUnits::Zero();
3513 assert(Offset.getQuantity() != -1);
3514 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3515 // While we know which base has to be traversed, we don't know if that base
3516 // was a virtual base.
3517 const CXXBaseSpecifier *BaseBS = std::find_if(
3518 RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3519 return BS.getType()->getAsCXXRecordDecl() == Base;
3521 Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3522 : Offset + Layout.getBaseClassOffset(Base);
3528 // We want to select the path which introduces the most covariant overrides. If
3529 // two paths introduce overrides which the other path doesn't contain, issue a
3531 static const FullPathTy *selectBestPath(ASTContext &Context,
3532 const CXXRecordDecl *RD, VPtrInfo *Info,
3533 std::list<FullPathTy> &FullPaths) {
3534 // Handle some easy cases first.
3535 if (FullPaths.empty())
3537 if (FullPaths.size() == 1)
3538 return &FullPaths.front();
3540 const FullPathTy *BestPath = nullptr;
3541 typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3542 OverriderSetTy LastOverrides;
3543 for (const FullPathTy &SpecificPath : FullPaths) {
3544 assert(!SpecificPath.empty());
3545 OverriderSetTy CurrentOverrides;
3546 const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3547 // Find the distance from the start of the path to the subobject with the
3549 CharUnits BaseOffset =
3550 getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3551 FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
3552 for (const CXXMethodDecl *MD : Info->BaseWithVPtr->methods()) {
3553 if (!MD->isVirtual())
3555 FinalOverriders::OverriderInfo OI =
3556 Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
3557 const CXXMethodDecl *OverridingMethod = OI.Method;
3558 // Only overriders which have a return adjustment introduce problematic
3560 if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3563 // It's possible that the overrider isn't in this path. If so, skip it
3564 // because this path didn't introduce it.
3565 const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
3566 if (std::none_of(SpecificPath.begin(), SpecificPath.end(),
3567 [&](const BaseSubobject &BSO) {
3568 return BSO.getBase() == OverridingParent;
3571 CurrentOverrides.insert(OverridingMethod);
3573 OverriderSetTy NewOverrides =
3574 llvm::set_difference(CurrentOverrides, LastOverrides);
3575 if (NewOverrides.empty())
3577 OverriderSetTy MissingOverrides =
3578 llvm::set_difference(LastOverrides, CurrentOverrides);
3579 if (MissingOverrides.empty()) {
3580 // This path is a strict improvement over the last path, let's use it.
3581 BestPath = &SpecificPath;
3582 std::swap(CurrentOverrides, LastOverrides);
3584 // This path introduces an overrider with a conflicting covariant thunk.
3585 DiagnosticsEngine &Diags = Context.getDiagnostics();
3586 const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3587 const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3588 Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3590 Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3592 Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3596 // Go with the path that introduced the most covariant overrides. If there is
3597 // no such path, pick the first path.
3598 return BestPath ? BestPath : &FullPaths.front();
3601 static void computeFullPathsForVFTables(ASTContext &Context,
3602 const CXXRecordDecl *RD,
3603 VPtrInfoVector &Paths) {
3604 const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
3605 FullPathTy FullPath;
3606 std::list<FullPathTy> FullPaths;
3607 for (VPtrInfo *Info : Paths) {
3608 findPathsToSubobject(
3609 Context, MostDerivedLayout, RD, CharUnits::Zero(),
3610 BaseSubobject(Info->BaseWithVPtr, Info->FullOffsetInMDC), FullPath,
3613 removeRedundantPaths(FullPaths);
3614 Info->PathToBaseWithVPtr.clear();
3615 if (const FullPathTy *BestPath =
3616 selectBestPath(Context, RD, Info, FullPaths))
3617 for (const BaseSubobject &BSO : *BestPath)
3618 Info->PathToBaseWithVPtr.push_back(BSO.getBase());
3623 void MicrosoftVTableContext::computeVTableRelatedInformation(
3624 const CXXRecordDecl *RD) {
3625 assert(RD->isDynamicClass());
3627 // Check if we've computed this information before.
3628 if (VFPtrLocations.count(RD))
3631 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3633 VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3634 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3635 computeFullPathsForVFTables(Context, RD, *VFPtrs);
3636 VFPtrLocations[RD] = VFPtrs;
3638 MethodVFTableLocationsTy NewMethodLocations;
3639 for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
3641 VFTableBuilder Builder(*this, RD, *I);
3643 VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
3644 assert(VFTableLayouts.count(id) == 0);
3645 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3646 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
3647 VFTableLayouts[id] = new VTableLayout(
3648 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3649 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3650 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3652 for (const auto &Loc : Builder.vtable_locations()) {
3653 GlobalDecl GD = Loc.first;
3654 MethodVFTableLocation NewLoc = Loc.second;
3655 auto M = NewMethodLocations.find(GD);
3656 if (M == NewMethodLocations.end() || NewLoc < M->second)
3657 NewMethodLocations[GD] = NewLoc;
3661 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3662 NewMethodLocations.end());
3663 if (Context.getLangOpts().DumpVTableLayouts)
3664 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
3667 void MicrosoftVTableContext::dumpMethodLocations(
3668 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3670 // Compute the vtable indices for all the member functions.
3671 // Store them in a map keyed by the location so we'll get a sorted table.
3672 std::map<MethodVFTableLocation, std::string> IndicesMap;
3673 bool HasNonzeroOffset = false;
3675 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3676 E = NewMethods.end(); I != E; ++I) {
3677 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3678 assert(MD->isVirtual());
3680 std::string MethodName = PredefinedExpr::ComputeName(
3681 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3683 if (isa<CXXDestructorDecl>(MD)) {
3684 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3686 IndicesMap[I->second] = MethodName;
3689 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
3690 HasNonzeroOffset = true;
3693 // Print the vtable indices for all the member functions.
3694 if (!IndicesMap.empty()) {
3695 Out << "VFTable indices for ";
3697 RD->printQualifiedName(Out);
3698 Out << "' (" << IndicesMap.size()
3699 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
3701 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3702 uint64_t LastVBIndex = 0;
3703 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3704 I = IndicesMap.begin(),
3705 E = IndicesMap.end();
3707 CharUnits VFPtrOffset = I->first.VFPtrOffset;
3708 uint64_t VBIndex = I->first.VBTableIndex;
3709 if (HasNonzeroOffset &&
3710 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3711 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3712 Out << " -- accessible via ";
3714 Out << "vbtable index " << VBIndex << ", ";
3715 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3716 LastVFPtrOffset = VFPtrOffset;
3717 LastVBIndex = VBIndex;
3720 uint64_t VTableIndex = I->first.Index;
3721 const std::string &MethodName = I->second;
3722 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3730 const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
3731 const CXXRecordDecl *RD) {
3732 VirtualBaseInfo *VBI;
3735 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3736 // as it may be modified and rehashed under us.
3737 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3740 Entry = VBI = new VirtualBaseInfo();
3743 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
3745 // First, see if the Derived class shared the vbptr with a non-virtual base.
3746 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3747 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
3748 // If the Derived class shares the vbptr with a non-virtual base, the shared
3749 // virtual bases come first so that the layout is the same.
3750 const VirtualBaseInfo *BaseInfo =
3751 computeVBTableRelatedInformation(VBPtrBase);
3752 VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3753 BaseInfo->VBTableIndices.end());
3756 // New vbases are added to the end of the vbtable.
3757 // Skip the self entry and vbases visited in the non-virtual base, if any.
3758 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
3759 for (const auto &VB : RD->vbases()) {
3760 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
3761 if (!VBI->VBTableIndices.count(CurVBase))
3762 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
3768 unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3769 const CXXRecordDecl *VBase) {
3770 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3771 assert(VBInfo->VBTableIndices.count(VBase));
3772 return VBInfo->VBTableIndices.find(VBase)->second;
3775 const VPtrInfoVector &
3776 MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
3777 return computeVBTableRelatedInformation(RD)->VBPtrPaths;
3780 const VPtrInfoVector &
3781 MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3782 computeVTableRelatedInformation(RD);
3784 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3785 return *VFPtrLocations[RD];
3788 const VTableLayout &
3789 MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3790 CharUnits VFPtrOffset) {
3791 computeVTableRelatedInformation(RD);
3793 VFTableIdTy id(RD, VFPtrOffset);
3794 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3795 return *VFTableLayouts[id];
3798 const MicrosoftVTableContext::MethodVFTableLocation &
3799 MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3800 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3801 "Only use this method for virtual methods or dtors");
3802 if (isa<CXXDestructorDecl>(GD.getDecl()))
3803 assert(GD.getDtorType() == Dtor_Deleting);
3805 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3806 if (I != MethodVFTableLocations.end())
3809 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3811 computeVTableRelatedInformation(RD);
3813 I = MethodVFTableLocations.find(GD);
3814 assert(I != MethodVFTableLocations.end() && "Did not find index!");