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/CXXInheritance.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/Support/Format.h"
23 using namespace clang;
25 #define DUMP_OVERRIDERS 0
29 /// BaseOffset - Represents an offset from a derived class to a direct or
30 /// indirect base class.
32 /// DerivedClass - The derived class.
33 const CXXRecordDecl *DerivedClass;
35 /// VirtualBase - If the path from the derived class to the base class
36 /// involves a virtual base class, this holds its declaration.
37 const CXXRecordDecl *VirtualBase;
39 /// NonVirtualOffset - The offset from the derived class to the base class.
40 /// (Or the offset from the virtual base class to the base class, if the
41 /// path from the derived class to the base class involves a virtual base
43 CharUnits NonVirtualOffset;
45 BaseOffset() : DerivedClass(0), VirtualBase(0),
46 NonVirtualOffset(CharUnits::Zero()) { }
47 BaseOffset(const CXXRecordDecl *DerivedClass,
48 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
49 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
50 NonVirtualOffset(NonVirtualOffset) { }
52 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
55 /// FinalOverriders - Contains the final overrider member functions for all
56 /// member functions in the base subobjects of a class.
57 class FinalOverriders {
59 /// OverriderInfo - Information about a final overrider.
60 struct OverriderInfo {
61 /// Method - The method decl of the overrider.
62 const CXXMethodDecl *Method;
64 /// Offset - the base offset of the overrider in the layout class.
67 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
71 /// MostDerivedClass - The most derived class for which the final overriders
73 const CXXRecordDecl *MostDerivedClass;
75 /// MostDerivedClassOffset - If we're building final overriders for a
76 /// construction vtable, this holds the offset from the layout class to the
77 /// most derived class.
78 const CharUnits MostDerivedClassOffset;
80 /// LayoutClass - The class we're using for layout information. Will be
81 /// different than the most derived class if the final overriders are for a
82 /// construction vtable.
83 const CXXRecordDecl *LayoutClass;
87 /// MostDerivedClassLayout - the AST record layout of the most derived class.
88 const ASTRecordLayout &MostDerivedClassLayout;
90 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
91 /// in a base subobject.
92 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
94 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
95 OverriderInfo> OverridersMapTy;
97 /// OverridersMap - The final overriders for all virtual member functions of
98 /// all the base subobjects of the most derived class.
99 OverridersMapTy OverridersMap;
101 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
102 /// as a record decl and a subobject number) and its offsets in the most
103 /// derived class as well as the layout class.
104 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
105 CharUnits> SubobjectOffsetMapTy;
107 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
109 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
111 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
112 CharUnits OffsetInLayoutClass,
113 SubobjectOffsetMapTy &SubobjectOffsets,
114 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
115 SubobjectCountMapTy &SubobjectCounts);
117 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
119 /// dump - dump the final overriders for a base subobject, and all its direct
120 /// and indirect base subobjects.
121 void dump(raw_ostream &Out, BaseSubobject Base,
122 VisitedVirtualBasesSetTy& VisitedVirtualBases);
125 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
126 CharUnits MostDerivedClassOffset,
127 const CXXRecordDecl *LayoutClass);
129 /// getOverrider - Get the final overrider for the given method declaration in
130 /// the subobject with the given base offset.
131 OverriderInfo getOverrider(const CXXMethodDecl *MD,
132 CharUnits BaseOffset) const {
133 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
134 "Did not find overrider!");
136 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
139 /// dump - dump the final overriders.
141 VisitedVirtualBasesSetTy VisitedVirtualBases;
142 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
143 VisitedVirtualBases);
148 #define DUMP_OVERRIDERS 0
150 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
151 CharUnits MostDerivedClassOffset,
152 const CXXRecordDecl *LayoutClass)
153 : MostDerivedClass(MostDerivedClass),
154 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
155 Context(MostDerivedClass->getASTContext()),
156 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
158 // Compute base offsets.
159 SubobjectOffsetMapTy SubobjectOffsets;
160 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
161 SubobjectCountMapTy SubobjectCounts;
162 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
164 MostDerivedClassOffset,
165 SubobjectOffsets, SubobjectLayoutClassOffsets,
168 // Get the final overriders.
169 CXXFinalOverriderMap FinalOverriders;
170 MostDerivedClass->getFinalOverriders(FinalOverriders);
172 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
173 E = FinalOverriders.end(); I != E; ++I) {
174 const CXXMethodDecl *MD = I->first;
175 const OverridingMethods& Methods = I->second;
177 for (OverridingMethods::const_iterator I = Methods.begin(),
178 E = Methods.end(); I != E; ++I) {
179 unsigned SubobjectNumber = I->first;
180 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
182 "Did not find subobject offset!");
184 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
187 assert(I->second.size() == 1 && "Final overrider is not unique!");
188 const UniqueVirtualMethod &Method = I->second.front();
190 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
191 assert(SubobjectLayoutClassOffsets.count(
192 std::make_pair(OverriderRD, Method.Subobject))
193 && "Did not find subobject offset!");
194 CharUnits OverriderOffset =
195 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
198 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
199 assert(!Overrider.Method && "Overrider should not exist yet!");
201 Overrider.Offset = OverriderOffset;
202 Overrider.Method = Method.Method;
207 // And dump them (for now).
212 static BaseOffset ComputeBaseOffset(ASTContext &Context,
213 const CXXRecordDecl *DerivedRD,
214 const CXXBasePath &Path) {
215 CharUnits NonVirtualOffset = CharUnits::Zero();
217 unsigned NonVirtualStart = 0;
218 const CXXRecordDecl *VirtualBase = 0;
220 // First, look for the virtual base class.
221 for (unsigned I = 0, E = Path.size(); I != E; ++I) {
222 const CXXBasePathElement &Element = Path[I];
224 if (Element.Base->isVirtual()) {
225 // FIXME: Can we break when we find the first virtual base?
226 // (If we can't, can't we just iterate over the path in reverse order?)
227 NonVirtualStart = I + 1;
228 QualType VBaseType = Element.Base->getType();
230 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
234 // Now compute the non-virtual offset.
235 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
236 const CXXBasePathElement &Element = Path[I];
238 // Check the base class offset.
239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
241 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
242 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
244 NonVirtualOffset += Layout.getBaseClassOffset(Base);
247 // FIXME: This should probably use CharUnits or something. Maybe we should
248 // even change the base offsets in ASTRecordLayout to be specified in
250 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
254 static BaseOffset ComputeBaseOffset(ASTContext &Context,
255 const CXXRecordDecl *BaseRD,
256 const CXXRecordDecl *DerivedRD) {
257 CXXBasePaths Paths(/*FindAmbiguities=*/false,
258 /*RecordPaths=*/true, /*DetectVirtual=*/false);
260 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
261 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
262 llvm_unreachable("Class must be derived from the passed in base class!");
265 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
269 ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
270 const CXXMethodDecl *DerivedMD,
271 const CXXMethodDecl *BaseMD) {
272 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
273 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
275 // Canonicalize the return types.
276 CanQualType CanDerivedReturnType =
277 Context.getCanonicalType(DerivedFT->getResultType());
278 CanQualType CanBaseReturnType =
279 Context.getCanonicalType(BaseFT->getResultType());
281 assert(CanDerivedReturnType->getTypeClass() ==
282 CanBaseReturnType->getTypeClass() &&
283 "Types must have same type class!");
285 if (CanDerivedReturnType == CanBaseReturnType) {
286 // No adjustment needed.
290 if (isa<ReferenceType>(CanDerivedReturnType)) {
291 CanDerivedReturnType =
292 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
294 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
295 } else if (isa<PointerType>(CanDerivedReturnType)) {
296 CanDerivedReturnType =
297 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
299 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
301 llvm_unreachable("Unexpected return type!");
304 // We need to compare unqualified types here; consider
305 // const T *Base::foo();
306 // T *Derived::foo();
307 if (CanDerivedReturnType.getUnqualifiedType() ==
308 CanBaseReturnType.getUnqualifiedType()) {
309 // No adjustment needed.
313 const CXXRecordDecl *DerivedRD =
314 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
316 const CXXRecordDecl *BaseRD =
317 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
319 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
323 FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
324 CharUnits OffsetInLayoutClass,
325 SubobjectOffsetMapTy &SubobjectOffsets,
326 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
327 SubobjectCountMapTy &SubobjectCounts) {
328 const CXXRecordDecl *RD = Base.getBase();
330 unsigned SubobjectNumber = 0;
332 SubobjectNumber = ++SubobjectCounts[RD];
334 // Set up the subobject to offset mapping.
335 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
336 && "Subobject offset already exists!");
337 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
338 && "Subobject offset already exists!");
340 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
341 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
344 // Traverse our bases.
345 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
346 E = RD->bases_end(); I != E; ++I) {
347 const CXXRecordDecl *BaseDecl =
348 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
350 CharUnits BaseOffset;
351 CharUnits BaseOffsetInLayoutClass;
352 if (I->isVirtual()) {
353 // Check if we've visited this virtual base before.
354 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
357 const ASTRecordLayout &LayoutClassLayout =
358 Context.getASTRecordLayout(LayoutClass);
360 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
361 BaseOffsetInLayoutClass =
362 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
364 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
365 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
367 BaseOffset = Base.getBaseOffset() + Offset;
368 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
371 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
372 I->isVirtual(), BaseOffsetInLayoutClass,
373 SubobjectOffsets, SubobjectLayoutClassOffsets,
378 void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
379 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
380 const CXXRecordDecl *RD = Base.getBase();
381 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
383 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
384 E = RD->bases_end(); I != E; ++I) {
385 const CXXRecordDecl *BaseDecl =
386 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
388 // Ignore bases that don't have any virtual member functions.
389 if (!BaseDecl->isPolymorphic())
392 CharUnits BaseOffset;
393 if (I->isVirtual()) {
394 if (!VisitedVirtualBases.insert(BaseDecl)) {
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 (" << RD->getQualifiedNameAsString() << ", ";
408 Out << Base.getBaseOffset().getQuantity() << ")\n";
410 // Now dump the overriders for this base subobject.
411 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
412 E = RD->method_end(); I != E; ++I) {
413 const CXXMethodDecl *MD = *I;
415 if (!MD->isVirtual())
418 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
420 Out << " " << MD->getQualifiedNameAsString() << " - (";
421 Out << Overrider.Method->getQualifiedNameAsString();
422 Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
425 if (!Overrider.Method->isPure())
426 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
428 if (!Offset.isEmpty()) {
429 Out << " [ret-adj: ";
430 if (Offset.VirtualBase)
431 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
433 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
440 /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
441 struct VCallOffsetMap {
443 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
445 /// Offsets - Keeps track of methods and their offsets.
446 // FIXME: This should be a real map and not a vector.
447 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
449 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
450 /// can share the same vcall offset.
451 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
452 const CXXMethodDecl *RHS);
455 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
456 /// add was successful, or false if there was already a member function with
457 /// the same signature in the map.
458 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
460 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
461 /// vtable address point) for the given virtual member function.
462 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
464 // empty - Return whether the offset map is empty or not.
465 bool empty() const { return Offsets.empty(); }
468 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
469 const CXXMethodDecl *RHS) {
470 const FunctionProtoType *LT =
471 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
472 const FunctionProtoType *RT =
473 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
475 // Fast-path matches in the canonical types.
476 if (LT == RT) return true;
478 // Force the signatures to match. We can't rely on the overrides
479 // list here because there isn't necessarily an inheritance
480 // relationship between the two methods.
481 if (LT->getTypeQuals() != RT->getTypeQuals() ||
482 LT->getNumArgs() != RT->getNumArgs())
484 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
485 if (LT->getArgType(I) != RT->getArgType(I))
490 bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
491 const CXXMethodDecl *RHS) {
492 assert(LHS->isVirtual() && "LHS must be virtual!");
493 assert(RHS->isVirtual() && "LHS must be virtual!");
495 // A destructor can share a vcall offset with another destructor.
496 if (isa<CXXDestructorDecl>(LHS))
497 return isa<CXXDestructorDecl>(RHS);
499 // FIXME: We need to check more things here.
501 // The methods must have the same name.
502 DeclarationName LHSName = LHS->getDeclName();
503 DeclarationName RHSName = RHS->getDeclName();
504 if (LHSName != RHSName)
507 // And the same signatures.
508 return HasSameVirtualSignature(LHS, RHS);
511 bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
512 CharUnits OffsetOffset) {
513 // Check if we can reuse an offset.
514 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
515 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
520 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
524 CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
525 // Look for an offset.
526 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
527 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
528 return Offsets[I].second;
531 llvm_unreachable("Should always find a vcall offset offset!");
534 /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
535 class VCallAndVBaseOffsetBuilder {
537 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
538 VBaseOffsetOffsetsMapTy;
541 /// MostDerivedClass - The most derived class for which we're building vcall
542 /// and vbase offsets.
543 const CXXRecordDecl *MostDerivedClass;
545 /// LayoutClass - The class we're using for layout information. Will be
546 /// different than the most derived class if we're building a construction
548 const CXXRecordDecl *LayoutClass;
550 /// Context - The ASTContext which we will use for layout information.
553 /// Components - vcall and vbase offset components
554 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
555 VTableComponentVectorTy Components;
557 /// VisitedVirtualBases - Visited virtual bases.
558 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
560 /// VCallOffsets - Keeps track of vcall offsets.
561 VCallOffsetMap VCallOffsets;
564 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
565 /// relative to the address point.
566 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
568 /// FinalOverriders - The final overriders of the most derived class.
569 /// (Can be null when we're not building a vtable of the most derived class).
570 const FinalOverriders *Overriders;
572 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
573 /// given base subobject.
574 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
575 CharUnits RealBaseOffset);
577 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
578 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
580 /// AddVBaseOffsets - Add vbase offsets for the given class.
581 void AddVBaseOffsets(const CXXRecordDecl *Base,
582 CharUnits OffsetInLayoutClass);
584 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
585 /// chars, relative to the vtable address point.
586 CharUnits getCurrentOffsetOffset() const;
589 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
590 const CXXRecordDecl *LayoutClass,
591 const FinalOverriders *Overriders,
592 BaseSubobject Base, bool BaseIsVirtual,
593 CharUnits OffsetInLayoutClass)
594 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
595 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
597 // Add vcall and vbase offsets.
598 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
601 /// Methods for iterating over the components.
602 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
603 const_iterator components_begin() const { return Components.rbegin(); }
604 const_iterator components_end() const { return Components.rend(); }
606 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
607 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
608 return VBaseOffsetOffsets;
613 VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
615 CharUnits RealBaseOffset) {
616 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
618 // Itanium C++ ABI 2.5.2:
619 // ..in classes sharing a virtual table with a primary base class, the vcall
620 // and vbase offsets added by the derived class all come before the vcall
621 // and vbase offsets required by the base class, so that the latter may be
622 // laid out as required by the base class without regard to additions from
623 // the derived class(es).
625 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
626 // emit them for the primary base first).
627 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
628 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
630 CharUnits PrimaryBaseOffset;
632 // Get the base offset of the primary base.
633 if (PrimaryBaseIsVirtual) {
634 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
635 "Primary vbase should have a zero offset!");
637 const ASTRecordLayout &MostDerivedClassLayout =
638 Context.getASTRecordLayout(MostDerivedClass);
641 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
643 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
644 "Primary base should have a zero offset!");
646 PrimaryBaseOffset = Base.getBaseOffset();
649 AddVCallAndVBaseOffsets(
650 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
651 PrimaryBaseIsVirtual, RealBaseOffset);
654 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
656 // We only want to add vcall offsets for virtual bases.
658 AddVCallOffsets(Base, RealBaseOffset);
661 CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
662 // OffsetIndex is the index of this vcall or vbase offset, relative to the
663 // vtable address point. (We subtract 3 to account for the information just
664 // above the address point, the RTTI info, the offset to top, and the
665 // vcall offset itself).
666 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
668 CharUnits PointerWidth =
669 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
670 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
674 void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
675 CharUnits VBaseOffset) {
676 const CXXRecordDecl *RD = Base.getBase();
677 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
679 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
681 // Handle the primary base first.
682 // We only want to add vcall offsets if the base is non-virtual; a virtual
683 // primary base will have its vcall and vbase offsets emitted already.
684 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
685 // Get the base offset of the primary base.
686 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
687 "Primary base should have a zero offset!");
689 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
693 // Add the vcall offsets.
694 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
695 E = RD->method_end(); I != E; ++I) {
696 const CXXMethodDecl *MD = *I;
698 if (!MD->isVirtual())
701 CharUnits OffsetOffset = getCurrentOffsetOffset();
703 // Don't add a vcall offset if we already have one for this member function
705 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
708 CharUnits Offset = CharUnits::Zero();
711 // Get the final overrider.
712 FinalOverriders::OverriderInfo Overrider =
713 Overriders->getOverrider(MD, Base.getBaseOffset());
715 /// The vcall offset is the offset from the virtual base to the object
716 /// where the function was overridden.
717 Offset = Overrider.Offset - VBaseOffset;
720 Components.push_back(
721 VTableComponent::MakeVCallOffset(Offset));
724 // And iterate over all non-virtual bases (ignoring the primary base).
725 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
726 E = RD->bases_end(); I != E; ++I) {
731 const CXXRecordDecl *BaseDecl =
732 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
733 if (BaseDecl == PrimaryBase)
736 // Get the base offset of this base.
737 CharUnits BaseOffset = Base.getBaseOffset() +
738 Layout.getBaseClassOffset(BaseDecl);
740 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
746 VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
747 CharUnits OffsetInLayoutClass) {
748 const ASTRecordLayout &LayoutClassLayout =
749 Context.getASTRecordLayout(LayoutClass);
751 // Add vbase offsets.
752 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
753 E = RD->bases_end(); I != E; ++I) {
754 const CXXRecordDecl *BaseDecl =
755 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
757 // Check if this is a virtual base that we haven't visited before.
758 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
760 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
762 // Add the vbase offset offset.
763 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
764 "vbase offset offset already exists!");
766 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
767 VBaseOffsetOffsets.insert(
768 std::make_pair(BaseDecl, VBaseOffsetOffset));
770 Components.push_back(
771 VTableComponent::MakeVBaseOffset(Offset));
774 // Check the base class looking for more vbase offsets.
775 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
779 /// VTableBuilder - Class for building vtable layout information.
780 class VTableBuilder {
782 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
784 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
785 PrimaryBasesSetVectorTy;
787 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
788 VBaseOffsetOffsetsMapTy;
790 typedef llvm::DenseMap<BaseSubobject, uint64_t>
794 /// VTables - Global vtable information.
795 VTableContext &VTables;
797 /// MostDerivedClass - The most derived class for which we're building this
799 const CXXRecordDecl *MostDerivedClass;
801 /// MostDerivedClassOffset - If we're building a construction vtable, this
802 /// holds the offset from the layout class to the most derived class.
803 const CharUnits MostDerivedClassOffset;
805 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
806 /// base. (This only makes sense when building a construction vtable).
807 bool MostDerivedClassIsVirtual;
809 /// LayoutClass - The class we're using for layout information. Will be
810 /// different than the most derived class if we're building a construction
812 const CXXRecordDecl *LayoutClass;
814 /// Context - The ASTContext which we will use for layout information.
817 /// FinalOverriders - The final overriders of the most derived class.
818 const FinalOverriders Overriders;
820 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
821 /// bases in this vtable.
822 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
824 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
825 /// the most derived class.
826 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
828 /// Components - The components of the vtable being built.
829 SmallVector<VTableComponent, 64> Components;
831 /// AddressPoints - Address points for the vtable being built.
832 AddressPointsMapTy AddressPoints;
834 /// MethodInfo - Contains information about a method in a vtable.
835 /// (Used for computing 'this' pointer adjustment thunks.
837 /// BaseOffset - The base offset of this method.
838 const CharUnits BaseOffset;
840 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
842 const CharUnits BaseOffsetInLayoutClass;
844 /// VTableIndex - The index in the vtable that this method has.
845 /// (For destructors, this is the index of the complete destructor).
846 const uint64_t VTableIndex;
848 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
849 uint64_t VTableIndex)
850 : BaseOffset(BaseOffset),
851 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
852 VTableIndex(VTableIndex) { }
855 : BaseOffset(CharUnits::Zero()),
856 BaseOffsetInLayoutClass(CharUnits::Zero()),
860 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
862 /// MethodInfoMap - The information for all methods in the vtable we're
863 /// currently building.
864 MethodInfoMapTy MethodInfoMap;
866 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
868 /// VTableThunks - The thunks by vtable index in the vtable currently being
870 VTableThunksMapTy VTableThunks;
872 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
873 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
875 /// Thunks - A map that contains all the thunks needed for all methods in the
876 /// most derived class for which the vtable is currently being built.
879 /// AddThunk - Add a thunk for the given method.
880 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
882 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
883 /// part of the vtable we're currently building.
884 void ComputeThisAdjustments();
886 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
888 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
890 VisitedVirtualBasesSetTy PrimaryVirtualBases;
892 /// ComputeReturnAdjustment - Compute the return adjustment given a return
893 /// adjustment base offset.
894 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
896 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
897 /// the 'this' pointer from the base subobject to the derived subobject.
898 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
899 BaseSubobject Derived) const;
901 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
902 /// given virtual member function, its offset in the layout class and its
905 ComputeThisAdjustment(const CXXMethodDecl *MD,
906 CharUnits BaseOffsetInLayoutClass,
907 FinalOverriders::OverriderInfo Overrider);
909 /// AddMethod - Add a single virtual member function to the vtable
910 /// components vector.
911 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
913 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
914 /// part of the vtable.
916 /// Itanium C++ ABI 2.5.2:
918 /// struct A { virtual void f(); };
919 /// struct B : virtual public A { int i; };
920 /// struct C : virtual public A { int j; };
921 /// struct D : public B, public C {};
923 /// When B and C are declared, A is a primary base in each case, so although
924 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
925 /// adjustment is required and no thunk is generated. However, inside D
926 /// objects, A is no longer a primary base of C, so if we allowed calls to
927 /// C::f() to use the copy of A's vtable in the C subobject, we would need
928 /// to adjust this from C* to B::A*, which would require a third-party
929 /// thunk. Since we require that a call to C::f() first convert to A*,
930 /// C-in-D's copy of A's vtable is never referenced, so this is not
932 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
933 CharUnits BaseOffsetInLayoutClass,
934 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
935 CharUnits FirstBaseOffsetInLayoutClass) const;
938 /// AddMethods - Add the methods of this base subobject and all its
939 /// primary bases to the vtable components vector.
940 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
941 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
942 CharUnits FirstBaseOffsetInLayoutClass,
943 PrimaryBasesSetVectorTy &PrimaryBases);
945 // LayoutVTable - Layout the vtable for the given base class, including its
946 // secondary vtables and any vtables for virtual bases.
949 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
950 /// given base subobject, as well as all its secondary vtables.
952 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
953 /// or a direct or indirect base of a virtual base.
955 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
956 /// in the layout class.
957 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
958 bool BaseIsMorallyVirtual,
959 bool BaseIsVirtualInLayoutClass,
960 CharUnits OffsetInLayoutClass);
962 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
965 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
966 /// or a direct or indirect base of a virtual base.
967 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
968 CharUnits OffsetInLayoutClass);
970 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
972 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
973 CharUnits OffsetInLayoutClass,
974 VisitedVirtualBasesSetTy &VBases);
976 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
977 /// given base (excluding any primary bases).
978 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
979 VisitedVirtualBasesSetTy &VBases);
981 /// isBuildingConstructionVTable - Return whether this vtable builder is
982 /// building a construction vtable.
983 bool isBuildingConstructorVTable() const {
984 return MostDerivedClass != LayoutClass;
988 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
989 CharUnits MostDerivedClassOffset,
990 bool MostDerivedClassIsVirtual, const
991 CXXRecordDecl *LayoutClass)
992 : VTables(VTables), MostDerivedClass(MostDerivedClass),
993 MostDerivedClassOffset(MostDerivedClassOffset),
994 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
995 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
996 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1000 if (Context.getLangOpts().DumpVTableLayouts)
1001 dumpLayout(llvm::errs());
1004 uint64_t getNumThunks() const {
1005 return Thunks.size();
1008 ThunksMapTy::const_iterator thunks_begin() const {
1009 return Thunks.begin();
1012 ThunksMapTy::const_iterator thunks_end() const {
1013 return Thunks.end();
1016 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1017 return VBaseOffsetOffsets;
1020 const AddressPointsMapTy &getAddressPoints() const {
1021 return AddressPoints;
1024 /// getNumVTableComponents - Return the number of components in the vtable
1025 /// currently built.
1026 uint64_t getNumVTableComponents() const {
1027 return Components.size();
1030 const VTableComponent *vtable_component_begin() const {
1031 return Components.begin();
1034 const VTableComponent *vtable_component_end() const {
1035 return Components.end();
1038 AddressPointsMapTy::const_iterator address_points_begin() const {
1039 return AddressPoints.begin();
1042 AddressPointsMapTy::const_iterator address_points_end() const {
1043 return AddressPoints.end();
1046 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1047 return VTableThunks.begin();
1050 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1051 return VTableThunks.end();
1054 /// dumpLayout - Dump the vtable layout.
1055 void dumpLayout(raw_ostream&);
1058 void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1059 assert(!isBuildingConstructorVTable() &&
1060 "Can't add thunks for construction vtable");
1062 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1064 // Check if we have this thunk already.
1065 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1069 ThunksVector.push_back(Thunk);
1072 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1074 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1075 /// the overridden methods that the function decl overrides.
1077 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1078 OverriddenMethodsSetTy& OverriddenMethods) {
1079 assert(MD->isVirtual() && "Method is not virtual!");
1081 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1082 E = MD->end_overridden_methods(); I != E; ++I) {
1083 const CXXMethodDecl *OverriddenMD = *I;
1085 OverriddenMethods.insert(OverriddenMD);
1087 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1091 void VTableBuilder::ComputeThisAdjustments() {
1092 // Now go through the method info map and see if any of the methods need
1093 // 'this' pointer adjustments.
1094 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1095 E = MethodInfoMap.end(); I != E; ++I) {
1096 const CXXMethodDecl *MD = I->first;
1097 const MethodInfo &MethodInfo = I->second;
1099 // Ignore adjustments for unused function pointers.
1100 uint64_t VTableIndex = MethodInfo.VTableIndex;
1101 if (Components[VTableIndex].getKind() ==
1102 VTableComponent::CK_UnusedFunctionPointer)
1105 // Get the final overrider for this method.
1106 FinalOverriders::OverriderInfo Overrider =
1107 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1109 // Check if we need an adjustment at all.
1110 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1111 // When a return thunk is needed by a derived class that overrides a
1112 // virtual base, gcc uses a virtual 'this' adjustment as well.
1113 // While the thunk itself might be needed by vtables in subclasses or
1114 // in construction vtables, there doesn't seem to be a reason for using
1115 // the thunk in this vtable. Still, we do so to match gcc.
1116 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1120 ThisAdjustment ThisAdjustment =
1121 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1123 if (ThisAdjustment.isEmpty())
1127 VTableThunks[VTableIndex].This = ThisAdjustment;
1129 if (isa<CXXDestructorDecl>(MD)) {
1130 // Add an adjustment for the deleting destructor as well.
1131 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1135 /// Clear the method info map.
1136 MethodInfoMap.clear();
1138 if (isBuildingConstructorVTable()) {
1139 // We don't need to store thunk information for construction vtables.
1143 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1144 E = VTableThunks.end(); I != E; ++I) {
1145 const VTableComponent &Component = Components[I->first];
1146 const ThunkInfo &Thunk = I->second;
1147 const CXXMethodDecl *MD;
1149 switch (Component.getKind()) {
1151 llvm_unreachable("Unexpected vtable component kind!");
1152 case VTableComponent::CK_FunctionPointer:
1153 MD = Component.getFunctionDecl();
1155 case VTableComponent::CK_CompleteDtorPointer:
1156 MD = Component.getDestructorDecl();
1158 case VTableComponent::CK_DeletingDtorPointer:
1159 // We've already added the thunk when we saw the complete dtor pointer.
1163 if (MD->getParent() == MostDerivedClass)
1164 AddThunk(MD, Thunk);
1168 ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1169 ReturnAdjustment Adjustment;
1171 if (!Offset.isEmpty()) {
1172 if (Offset.VirtualBase) {
1173 // Get the virtual base offset offset.
1174 if (Offset.DerivedClass == MostDerivedClass) {
1175 // We can get the offset offset directly from our map.
1176 Adjustment.VBaseOffsetOffset =
1177 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1179 Adjustment.VBaseOffsetOffset =
1180 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1181 Offset.VirtualBase).getQuantity();
1185 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1192 VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1193 BaseSubobject Derived) const {
1194 const CXXRecordDecl *BaseRD = Base.getBase();
1195 const CXXRecordDecl *DerivedRD = Derived.getBase();
1197 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1198 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1200 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1201 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1202 llvm_unreachable("Class must be derived from the passed in base class!");
1205 // We have to go through all the paths, and see which one leads us to the
1206 // right base subobject.
1207 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1209 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1211 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1213 if (Offset.VirtualBase) {
1214 // If we have a virtual base class, the non-virtual offset is relative
1215 // to the virtual base class offset.
1216 const ASTRecordLayout &LayoutClassLayout =
1217 Context.getASTRecordLayout(LayoutClass);
1219 /// Get the virtual base offset, relative to the most derived class
1221 OffsetToBaseSubobject +=
1222 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1224 // Otherwise, the non-virtual offset is relative to the derived class
1226 OffsetToBaseSubobject += Derived.getBaseOffset();
1229 // Check if this path gives us the right base subobject.
1230 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1231 // Since we're going from the base class _to_ the derived class, we'll
1232 // invert the non-virtual offset here.
1233 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1238 return BaseOffset();
1242 VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1243 CharUnits BaseOffsetInLayoutClass,
1244 FinalOverriders::OverriderInfo Overrider) {
1245 // Ignore adjustments for pure virtual member functions.
1246 if (Overrider.Method->isPure())
1247 return ThisAdjustment();
1249 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1250 BaseOffsetInLayoutClass);
1252 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1255 // Compute the adjustment offset.
1256 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1257 OverriderBaseSubobject);
1258 if (Offset.isEmpty())
1259 return ThisAdjustment();
1261 ThisAdjustment Adjustment;
1263 if (Offset.VirtualBase) {
1264 // Get the vcall offset map for this virtual base.
1265 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1267 if (VCallOffsets.empty()) {
1268 // We don't have vcall offsets for this virtual base, go ahead and
1270 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1271 /*FinalOverriders=*/0,
1272 BaseSubobject(Offset.VirtualBase,
1274 /*BaseIsVirtual=*/true,
1275 /*OffsetInLayoutClass=*/
1278 VCallOffsets = Builder.getVCallOffsets();
1281 Adjustment.VCallOffsetOffset =
1282 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1285 // Set the non-virtual part of the adjustment.
1286 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1292 VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1293 ReturnAdjustment ReturnAdjustment) {
1294 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1295 assert(ReturnAdjustment.isEmpty() &&
1296 "Destructor can't have return adjustment!");
1298 // Add both the complete destructor and the deleting destructor.
1299 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1300 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1302 // Add the return adjustment if necessary.
1303 if (!ReturnAdjustment.isEmpty())
1304 VTableThunks[Components.size()].Return = ReturnAdjustment;
1306 // Add the function.
1307 Components.push_back(VTableComponent::MakeFunction(MD));
1311 /// OverridesIndirectMethodInBase - Return whether the given member function
1312 /// overrides any methods in the set of given bases.
1313 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1314 /// For example, if we have:
1316 /// struct A { virtual void f(); }
1317 /// struct B : A { virtual void f(); }
1318 /// struct C : B { virtual void f(); }
1320 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1321 /// and { A } as the set of bases.
1323 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1324 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1325 if (Bases.count(MD->getParent()))
1328 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1329 E = MD->end_overridden_methods(); I != E; ++I) {
1330 const CXXMethodDecl *OverriddenMD = *I;
1332 // Check "indirect overriders".
1333 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1341 VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1342 CharUnits BaseOffsetInLayoutClass,
1343 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1344 CharUnits FirstBaseOffsetInLayoutClass) const {
1345 // If the base and the first base in the primary base chain have the same
1346 // offsets, then this overrider will be used.
1347 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1350 // We know now that Base (or a direct or indirect base of it) is a primary
1351 // base in part of the class hierarchy, but not a primary base in the most
1354 // If the overrider is the first base in the primary base chain, we know
1355 // that the overrider will be used.
1356 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1359 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1361 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1362 PrimaryBases.insert(RD);
1364 // Now traverse the base chain, starting with the first base, until we find
1365 // the base that is no longer a primary base.
1367 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1368 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1373 if (Layout.isPrimaryBaseVirtual()) {
1374 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1375 "Primary base should always be at offset 0!");
1377 const ASTRecordLayout &LayoutClassLayout =
1378 Context.getASTRecordLayout(LayoutClass);
1380 // Now check if this is the primary base that is not a primary base in the
1381 // most derived class.
1382 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1383 FirstBaseOffsetInLayoutClass) {
1384 // We found it, stop walking the chain.
1388 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1389 "Primary base should always be at offset 0!");
1392 if (!PrimaryBases.insert(PrimaryBase))
1393 llvm_unreachable("Found a duplicate primary base!");
1398 // If the final overrider is an override of one of the primary bases,
1399 // then we know that it will be used.
1400 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1403 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1404 /// from the nearest base. Returns null if no method was found.
1405 static const CXXMethodDecl *
1406 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1407 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1408 OverriddenMethodsSetTy OverriddenMethods;
1409 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1411 for (int I = Bases.size(), E = 0; I != E; --I) {
1412 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1414 // Now check the overriden methods.
1415 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1416 E = OverriddenMethods.end(); I != E; ++I) {
1417 const CXXMethodDecl *OverriddenMD = *I;
1419 // We found our overridden method.
1420 if (OverriddenMD->getParent() == PrimaryBase)
1421 return OverriddenMD;
1429 VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1430 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1431 CharUnits FirstBaseOffsetInLayoutClass,
1432 PrimaryBasesSetVectorTy &PrimaryBases) {
1433 const CXXRecordDecl *RD = Base.getBase();
1434 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1436 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1437 CharUnits PrimaryBaseOffset;
1438 CharUnits PrimaryBaseOffsetInLayoutClass;
1439 if (Layout.isPrimaryBaseVirtual()) {
1440 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1441 "Primary vbase should have a zero offset!");
1443 const ASTRecordLayout &MostDerivedClassLayout =
1444 Context.getASTRecordLayout(MostDerivedClass);
1447 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1449 const ASTRecordLayout &LayoutClassLayout =
1450 Context.getASTRecordLayout(LayoutClass);
1452 PrimaryBaseOffsetInLayoutClass =
1453 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1455 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1456 "Primary base should have a zero offset!");
1458 PrimaryBaseOffset = Base.getBaseOffset();
1459 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1462 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1463 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1464 FirstBaseOffsetInLayoutClass, PrimaryBases);
1466 if (!PrimaryBases.insert(PrimaryBase))
1467 llvm_unreachable("Found a duplicate primary base!");
1470 // Now go through all virtual member functions and add them.
1471 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1472 E = RD->method_end(); I != E; ++I) {
1473 const CXXMethodDecl *MD = *I;
1475 if (!MD->isVirtual())
1478 // Get the final overrider.
1479 FinalOverriders::OverriderInfo Overrider =
1480 Overriders.getOverrider(MD, Base.getBaseOffset());
1482 // Check if this virtual member function overrides a method in a primary
1483 // base. If this is the case, and the return type doesn't require adjustment
1484 // then we can just use the member function from the primary base.
1485 if (const CXXMethodDecl *OverriddenMD =
1486 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1487 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1488 OverriddenMD).isEmpty()) {
1489 // Replace the method info of the overridden method with our own
1491 assert(MethodInfoMap.count(OverriddenMD) &&
1492 "Did not find the overridden method!");
1493 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1495 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1496 OverriddenMethodInfo.VTableIndex);
1498 assert(!MethodInfoMap.count(MD) &&
1499 "Should not have method info for this method yet!");
1501 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1502 MethodInfoMap.erase(OverriddenMD);
1504 // If the overridden method exists in a virtual base class or a direct
1505 // or indirect base class of a virtual base class, we need to emit a
1506 // thunk if we ever have a class hierarchy where the base class is not
1507 // a primary base in the complete object.
1508 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1509 // Compute the this adjustment.
1510 ThisAdjustment ThisAdjustment =
1511 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1514 if (ThisAdjustment.VCallOffsetOffset &&
1515 Overrider.Method->getParent() == MostDerivedClass) {
1517 // There's no return adjustment from OverriddenMD and MD,
1518 // but that doesn't mean there isn't one between MD and
1519 // the final overrider.
1520 BaseOffset ReturnAdjustmentOffset =
1521 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1522 ReturnAdjustment ReturnAdjustment =
1523 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1525 // This is a virtual thunk for the most derived class, add it.
1526 AddThunk(Overrider.Method,
1527 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1535 // Insert the method info for this method.
1536 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1539 assert(!MethodInfoMap.count(MD) &&
1540 "Should not have method info for this method yet!");
1541 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1543 // Check if this overrider is going to be used.
1544 const CXXMethodDecl *OverriderMD = Overrider.Method;
1545 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1546 FirstBaseInPrimaryBaseChain,
1547 FirstBaseOffsetInLayoutClass)) {
1548 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1552 // Check if this overrider needs a return adjustment.
1553 // We don't want to do this for pure virtual member functions.
1554 BaseOffset ReturnAdjustmentOffset;
1555 if (!OverriderMD->isPure()) {
1556 ReturnAdjustmentOffset =
1557 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1560 ReturnAdjustment ReturnAdjustment =
1561 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1563 AddMethod(Overrider.Method, ReturnAdjustment);
1567 void VTableBuilder::LayoutVTable() {
1568 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1570 /*BaseIsMorallyVirtual=*/false,
1571 MostDerivedClassIsVirtual,
1572 MostDerivedClassOffset);
1574 VisitedVirtualBasesSetTy VBases;
1576 // Determine the primary virtual bases.
1577 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1581 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1583 // -fapple-kext adds an extra entry at end of vtbl.
1584 bool IsAppleKext = Context.getLangOpts().AppleKext;
1586 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1590 VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1591 bool BaseIsMorallyVirtual,
1592 bool BaseIsVirtualInLayoutClass,
1593 CharUnits OffsetInLayoutClass) {
1594 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1596 // Add vcall and vbase offsets for this vtable.
1597 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1598 Base, BaseIsVirtualInLayoutClass,
1599 OffsetInLayoutClass);
1600 Components.append(Builder.components_begin(), Builder.components_end());
1602 // Check if we need to add these vcall offsets.
1603 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1604 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1606 if (VCallOffsets.empty())
1607 VCallOffsets = Builder.getVCallOffsets();
1610 // If we're laying out the most derived class we want to keep track of the
1611 // virtual base class offset offsets.
1612 if (Base.getBase() == MostDerivedClass)
1613 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1615 // Add the offset to top.
1616 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1617 Components.push_back(
1618 VTableComponent::MakeOffsetToTop(OffsetToTop));
1620 // Next, add the RTTI.
1621 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1623 uint64_t AddressPoint = Components.size();
1625 // Now go through all virtual member functions and add them.
1626 PrimaryBasesSetVectorTy PrimaryBases;
1627 AddMethods(Base, OffsetInLayoutClass,
1628 Base.getBase(), OffsetInLayoutClass,
1631 // Compute 'this' pointer adjustments.
1632 ComputeThisAdjustments();
1634 // Add all address points.
1635 const CXXRecordDecl *RD = Base.getBase();
1637 AddressPoints.insert(std::make_pair(
1638 BaseSubobject(RD, OffsetInLayoutClass),
1641 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1642 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1647 if (Layout.isPrimaryBaseVirtual()) {
1648 // Check if this virtual primary base is a primary base in the layout
1649 // class. If it's not, we don't want to add it.
1650 const ASTRecordLayout &LayoutClassLayout =
1651 Context.getASTRecordLayout(LayoutClass);
1653 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1654 OffsetInLayoutClass) {
1655 // We don't want to add this class (or any of its primary bases).
1663 // Layout secondary vtables.
1664 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1667 void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1668 bool BaseIsMorallyVirtual,
1669 CharUnits OffsetInLayoutClass) {
1670 // Itanium C++ ABI 2.5.2:
1671 // Following the primary virtual table of a derived class are secondary
1672 // virtual tables for each of its proper base classes, except any primary
1673 // base(s) with which it shares its primary virtual table.
1675 const CXXRecordDecl *RD = Base.getBase();
1676 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1677 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1679 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1680 E = RD->bases_end(); I != E; ++I) {
1681 // Ignore virtual bases, we'll emit them later.
1685 const CXXRecordDecl *BaseDecl =
1686 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1688 // Ignore bases that don't have a vtable.
1689 if (!BaseDecl->isDynamicClass())
1692 if (isBuildingConstructorVTable()) {
1693 // Itanium C++ ABI 2.6.4:
1694 // Some of the base class subobjects may not need construction virtual
1695 // tables, which will therefore not be present in the construction
1696 // virtual table group, even though the subobject virtual tables are
1697 // present in the main virtual table group for the complete object.
1698 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1702 // Get the base offset of this base.
1703 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1704 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1706 CharUnits BaseOffsetInLayoutClass =
1707 OffsetInLayoutClass + RelativeBaseOffset;
1709 // Don't emit a secondary vtable for a primary base. We might however want
1710 // to emit secondary vtables for other bases of this base.
1711 if (BaseDecl == PrimaryBase) {
1712 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1713 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1717 // Layout the primary vtable (and any secondary vtables) for this base.
1718 LayoutPrimaryAndSecondaryVTables(
1719 BaseSubobject(BaseDecl, BaseOffset),
1720 BaseIsMorallyVirtual,
1721 /*BaseIsVirtualInLayoutClass=*/false,
1722 BaseOffsetInLayoutClass);
1727 VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1728 CharUnits OffsetInLayoutClass,
1729 VisitedVirtualBasesSetTy &VBases) {
1730 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1732 // Check if this base has a primary base.
1733 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1735 // Check if it's virtual.
1736 if (Layout.isPrimaryBaseVirtual()) {
1737 bool IsPrimaryVirtualBase = true;
1739 if (isBuildingConstructorVTable()) {
1740 // Check if the base is actually a primary base in the class we use for
1742 const ASTRecordLayout &LayoutClassLayout =
1743 Context.getASTRecordLayout(LayoutClass);
1745 CharUnits PrimaryBaseOffsetInLayoutClass =
1746 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1748 // We know that the base is not a primary base in the layout class if
1749 // the base offsets are different.
1750 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1751 IsPrimaryVirtualBase = false;
1754 if (IsPrimaryVirtualBase)
1755 PrimaryVirtualBases.insert(PrimaryBase);
1759 // Traverse bases, looking for more primary virtual bases.
1760 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1761 E = RD->bases_end(); I != E; ++I) {
1762 const CXXRecordDecl *BaseDecl =
1763 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1765 CharUnits BaseOffsetInLayoutClass;
1767 if (I->isVirtual()) {
1768 if (!VBases.insert(BaseDecl))
1771 const ASTRecordLayout &LayoutClassLayout =
1772 Context.getASTRecordLayout(LayoutClass);
1774 BaseOffsetInLayoutClass =
1775 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1777 BaseOffsetInLayoutClass =
1778 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1781 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1786 VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1787 VisitedVirtualBasesSetTy &VBases) {
1788 // Itanium C++ ABI 2.5.2:
1789 // Then come the virtual base virtual tables, also in inheritance graph
1790 // order, and again excluding primary bases (which share virtual tables with
1791 // the classes for which they are primary).
1792 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1793 E = RD->bases_end(); I != E; ++I) {
1794 const CXXRecordDecl *BaseDecl =
1795 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1797 // Check if this base needs a vtable. (If it's virtual, not a primary base
1798 // of some other class, and we haven't visited it before).
1799 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1800 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1801 const ASTRecordLayout &MostDerivedClassLayout =
1802 Context.getASTRecordLayout(MostDerivedClass);
1803 CharUnits BaseOffset =
1804 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1806 const ASTRecordLayout &LayoutClassLayout =
1807 Context.getASTRecordLayout(LayoutClass);
1808 CharUnits BaseOffsetInLayoutClass =
1809 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1811 LayoutPrimaryAndSecondaryVTables(
1812 BaseSubobject(BaseDecl, BaseOffset),
1813 /*BaseIsMorallyVirtual=*/true,
1814 /*BaseIsVirtualInLayoutClass=*/true,
1815 BaseOffsetInLayoutClass);
1818 // We only need to check the base for virtual base vtables if it actually
1819 // has virtual bases.
1820 if (BaseDecl->getNumVBases())
1821 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1825 /// dumpLayout - Dump the vtable layout.
1826 void VTableBuilder::dumpLayout(raw_ostream& Out) {
1828 if (isBuildingConstructorVTable()) {
1829 Out << "Construction vtable for ('";
1830 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1831 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1832 Out << LayoutClass->getQualifiedNameAsString();
1834 Out << "Vtable for '";
1835 Out << MostDerivedClass->getQualifiedNameAsString();
1837 Out << "' (" << Components.size() << " entries).\n";
1839 // Iterate through the address points and insert them into a new map where
1840 // they are keyed by the index and not the base object.
1841 // Since an address point can be shared by multiple subobjects, we use an
1843 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1844 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1845 E = AddressPoints.end(); I != E; ++I) {
1846 const BaseSubobject& Base = I->first;
1847 uint64_t Index = I->second;
1849 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1852 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1855 Out << llvm::format("%4d | ", I);
1857 const VTableComponent &Component = Components[I];
1859 // Dump the component.
1860 switch (Component.getKind()) {
1862 case VTableComponent::CK_VCallOffset:
1863 Out << "vcall_offset ("
1864 << Component.getVCallOffset().getQuantity()
1868 case VTableComponent::CK_VBaseOffset:
1869 Out << "vbase_offset ("
1870 << Component.getVBaseOffset().getQuantity()
1874 case VTableComponent::CK_OffsetToTop:
1875 Out << "offset_to_top ("
1876 << Component.getOffsetToTop().getQuantity()
1880 case VTableComponent::CK_RTTI:
1881 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1884 case VTableComponent::CK_FunctionPointer: {
1885 const CXXMethodDecl *MD = Component.getFunctionDecl();
1888 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1894 if (MD->isDeleted())
1895 Out << " [deleted]";
1897 ThunkInfo Thunk = VTableThunks.lookup(I);
1898 if (!Thunk.isEmpty()) {
1899 // If this function pointer has a return adjustment, dump it.
1900 if (!Thunk.Return.isEmpty()) {
1901 Out << "\n [return adjustment: ";
1902 Out << Thunk.Return.NonVirtual << " non-virtual";
1904 if (Thunk.Return.VBaseOffsetOffset) {
1905 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1906 Out << " vbase offset offset";
1912 // If this function pointer has a 'this' pointer adjustment, dump it.
1913 if (!Thunk.This.isEmpty()) {
1914 Out << "\n [this adjustment: ";
1915 Out << Thunk.This.NonVirtual << " non-virtual";
1917 if (Thunk.This.VCallOffsetOffset) {
1918 Out << ", " << Thunk.This.VCallOffsetOffset;
1919 Out << " vcall offset offset";
1929 case VTableComponent::CK_CompleteDtorPointer:
1930 case VTableComponent::CK_DeletingDtorPointer: {
1932 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1934 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1936 Out << DD->getQualifiedNameAsString();
1938 Out << "() [complete]";
1940 Out << "() [deleting]";
1945 ThunkInfo Thunk = VTableThunks.lookup(I);
1946 if (!Thunk.isEmpty()) {
1947 // If this destructor has a 'this' pointer adjustment, dump it.
1948 if (!Thunk.This.isEmpty()) {
1949 Out << "\n [this adjustment: ";
1950 Out << Thunk.This.NonVirtual << " non-virtual";
1952 if (Thunk.This.VCallOffsetOffset) {
1953 Out << ", " << Thunk.This.VCallOffsetOffset;
1954 Out << " vcall offset offset";
1964 case VTableComponent::CK_UnusedFunctionPointer: {
1965 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1968 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1970 Out << "[unused] " << Str;
1979 // Dump the next address point.
1980 uint64_t NextIndex = Index + 1;
1981 if (AddressPointsByIndex.count(NextIndex)) {
1982 if (AddressPointsByIndex.count(NextIndex) == 1) {
1983 const BaseSubobject &Base =
1984 AddressPointsByIndex.find(NextIndex)->second;
1986 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
1987 Out << ", " << Base.getBaseOffset().getQuantity();
1988 Out << ") vtable address --\n";
1990 CharUnits BaseOffset =
1991 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
1993 // We store the class names in a set to get a stable order.
1994 std::set<std::string> ClassNames;
1995 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
1996 AddressPointsByIndex.lower_bound(NextIndex), E =
1997 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
1998 assert(I->second.getBaseOffset() == BaseOffset &&
1999 "Invalid base offset!");
2000 const CXXRecordDecl *RD = I->second.getBase();
2001 ClassNames.insert(RD->getQualifiedNameAsString());
2004 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2005 E = ClassNames.end(); I != E; ++I) {
2006 Out << " -- (" << *I;
2007 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2015 if (isBuildingConstructorVTable())
2018 if (MostDerivedClass->getNumVBases()) {
2019 // We store the virtual base class names and their offsets in a map to get
2022 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2023 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2024 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2025 std::string ClassName = I->first->getQualifiedNameAsString();
2026 CharUnits OffsetOffset = I->second;
2027 ClassNamesAndOffsets.insert(
2028 std::make_pair(ClassName, OffsetOffset));
2031 Out << "Virtual base offset offsets for '";
2032 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2033 Out << ClassNamesAndOffsets.size();
2034 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2036 for (std::map<std::string, CharUnits>::const_iterator I =
2037 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2039 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2044 if (!Thunks.empty()) {
2045 // We store the method names in a map to get a stable order.
2046 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2048 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2050 const CXXMethodDecl *MD = I->first;
2051 std::string MethodName =
2052 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2055 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2058 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2059 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2061 const std::string &MethodName = I->first;
2062 const CXXMethodDecl *MD = I->second;
2064 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2065 std::sort(ThunksVector.begin(), ThunksVector.end());
2067 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2068 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2070 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2071 const ThunkInfo &Thunk = ThunksVector[I];
2073 Out << llvm::format("%4d | ", I);
2075 // If this function pointer has a return pointer adjustment, dump it.
2076 if (!Thunk.Return.isEmpty()) {
2077 Out << "return adjustment: " << Thunk.This.NonVirtual;
2078 Out << " non-virtual";
2079 if (Thunk.Return.VBaseOffsetOffset) {
2080 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2081 Out << " vbase offset offset";
2084 if (!Thunk.This.isEmpty())
2088 // If this function pointer has a 'this' pointer adjustment, dump it.
2089 if (!Thunk.This.isEmpty()) {
2090 Out << "this adjustment: ";
2091 Out << Thunk.This.NonVirtual << " non-virtual";
2093 if (Thunk.This.VCallOffsetOffset) {
2094 Out << ", " << Thunk.This.VCallOffsetOffset;
2095 Out << " vcall offset offset";
2106 // Compute the vtable indices for all the member functions.
2107 // Store them in a map keyed by the index so we'll get a sorted table.
2108 std::map<uint64_t, std::string> IndicesMap;
2110 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2111 e = MostDerivedClass->method_end(); i != e; ++i) {
2112 const CXXMethodDecl *MD = *i;
2114 // We only want virtual member functions.
2115 if (!MD->isVirtual())
2118 std::string MethodName =
2119 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2122 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2123 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))] =
2124 MethodName + " [complete]";
2125 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))] =
2126 MethodName + " [deleting]";
2128 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2132 // Print the vtable indices for all the member functions.
2133 if (!IndicesMap.empty()) {
2134 Out << "VTable indices for '";
2135 Out << MostDerivedClass->getQualifiedNameAsString();
2136 Out << "' (" << IndicesMap.size() << " entries).\n";
2138 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2139 E = IndicesMap.end(); I != E; ++I) {
2140 uint64_t VTableIndex = I->first;
2141 const std::string &MethodName = I->second;
2143 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
2153 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2154 const VTableComponent *VTableComponents,
2155 uint64_t NumVTableThunks,
2156 const VTableThunkTy *VTableThunks,
2157 const AddressPointsMapTy &AddressPoints)
2158 : NumVTableComponents(NumVTableComponents),
2159 VTableComponents(new VTableComponent[NumVTableComponents]),
2160 NumVTableThunks(NumVTableThunks),
2161 VTableThunks(new VTableThunkTy[NumVTableThunks]),
2162 AddressPoints(AddressPoints) {
2163 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2164 this->VTableComponents.get());
2165 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2166 this->VTableThunks.get());
2169 VTableLayout::~VTableLayout() { }
2171 VTableContext::~VTableContext() {
2172 llvm::DeleteContainerSeconds(VTableLayouts);
2176 CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2177 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2178 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2179 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2184 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2186 if (!PrimaryBases.insert(PrimaryBase))
2187 llvm_unreachable("Found a duplicate primary base!");
2190 void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2192 // Itanium C++ ABI 2.5.2:
2193 // The order of the virtual function pointers in a virtual table is the
2194 // order of declaration of the corresponding member functions in the class.
2196 // There is an entry for any virtual function declared in a class,
2197 // whether it is a new function or overrides a base class function,
2198 // unless it overrides a function from the primary base, and conversion
2199 // between their return types does not require an adjustment.
2201 int64_t CurrentIndex = 0;
2203 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2204 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2207 assert(PrimaryBase->isCompleteDefinition() &&
2208 "Should have the definition decl of the primary base!");
2210 // Since the record decl shares its vtable pointer with the primary base
2211 // we need to start counting at the end of the primary base's vtable.
2212 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2215 // Collect all the primary bases, so we can check whether methods override
2216 // a method from the base.
2217 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2218 CollectPrimaryBases(RD, Context, PrimaryBases);
2220 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2222 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2223 e = RD->method_end(); i != e; ++i) {
2224 const CXXMethodDecl *MD = *i;
2226 // We only want virtual methods.
2227 if (!MD->isVirtual())
2230 // Check if this method overrides a method in the primary base.
2231 if (const CXXMethodDecl *OverriddenMD =
2232 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2233 // Check if converting from the return type of the method to the
2234 // return type of the overridden method requires conversion.
2235 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2236 OverriddenMD).isEmpty()) {
2237 // This index is shared between the index in the vtable of the primary
2239 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2240 const CXXDestructorDecl *OverriddenDD =
2241 cast<CXXDestructorDecl>(OverriddenMD);
2243 // Add both the complete and deleting entries.
2244 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2245 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2246 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2247 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2249 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2252 // We don't need to add an entry for this method.
2257 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2258 if (MD->isImplicit()) {
2259 assert(!ImplicitVirtualDtor &&
2260 "Did already see an implicit virtual dtor!");
2261 ImplicitVirtualDtor = DD;
2265 // Add the complete dtor.
2266 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2268 // Add the deleting dtor.
2269 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2272 MethodVTableIndices[MD] = CurrentIndex++;
2276 if (ImplicitVirtualDtor) {
2277 // Itanium C++ ABI 2.5.2:
2278 // If a class has an implicitly-defined virtual destructor,
2279 // its entries come after the declared virtual function pointers.
2281 // Add the complete dtor.
2282 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2285 // Add the deleting dtor.
2286 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2290 NumVirtualFunctionPointers[RD] = CurrentIndex;
2293 uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2294 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2295 NumVirtualFunctionPointers.find(RD);
2296 if (I != NumVirtualFunctionPointers.end())
2299 ComputeMethodVTableIndices(RD);
2301 I = NumVirtualFunctionPointers.find(RD);
2302 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2306 uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2307 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2308 if (I != MethodVTableIndices.end())
2311 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2313 ComputeMethodVTableIndices(RD);
2315 I = MethodVTableIndices.find(GD);
2316 assert(I != MethodVTableIndices.end() && "Did not find index!");
2321 VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2322 const CXXRecordDecl *VBase) {
2323 ClassPairTy ClassPair(RD, VBase);
2325 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2326 VirtualBaseClassOffsetOffsets.find(ClassPair);
2327 if (I != VirtualBaseClassOffsetOffsets.end())
2330 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2331 BaseSubobject(RD, CharUnits::Zero()),
2332 /*BaseIsVirtual=*/false,
2333 /*OffsetInLayoutClass=*/CharUnits::Zero());
2335 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2336 Builder.getVBaseOffsetOffsets().begin(),
2337 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2338 // Insert all types.
2339 ClassPairTy ClassPair(RD, I->first);
2341 VirtualBaseClassOffsetOffsets.insert(
2342 std::make_pair(ClassPair, I->second));
2345 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2346 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2351 static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2352 SmallVector<VTableLayout::VTableThunkTy, 1>
2353 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2354 std::sort(VTableThunks.begin(), VTableThunks.end());
2356 return new VTableLayout(Builder.getNumVTableComponents(),
2357 Builder.vtable_component_begin(),
2358 VTableThunks.size(),
2359 VTableThunks.data(),
2360 Builder.getAddressPoints());
2363 void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2364 const VTableLayout *&Entry = VTableLayouts[RD];
2366 // Check if we've computed this information before.
2370 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2371 /*MostDerivedClassIsVirtual=*/0, RD);
2372 Entry = CreateVTableLayout(Builder);
2374 // Add the known thunks.
2375 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2377 // If we don't have the vbase information for this class, insert it.
2378 // getVirtualBaseOffsetOffset will compute it separately without computing
2379 // the rest of the vtable related information.
2380 if (!RD->getNumVBases())
2383 const RecordType *VBaseRT =
2384 RD->vbases_begin()->getType()->getAs<RecordType>();
2385 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2387 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2390 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2391 Builder.getVBaseOffsetOffsets().begin(),
2392 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2393 // Insert all types.
2394 ClassPairTy ClassPair(RD, I->first);
2396 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2400 VTableLayout *VTableContext::createConstructionVTableLayout(
2401 const CXXRecordDecl *MostDerivedClass,
2402 CharUnits MostDerivedClassOffset,
2403 bool MostDerivedClassIsVirtual,
2404 const CXXRecordDecl *LayoutClass) {
2405 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2406 MostDerivedClassIsVirtual, LayoutClass);
2407 return CreateVTableLayout(Builder);