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/CXXInheritance.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "llvm/Support/Format.h"
22 using namespace clang;
24 #define DUMP_OVERRIDERS 0
28 /// BaseOffset - Represents an offset from a derived class to a direct or
29 /// indirect base class.
31 /// DerivedClass - The derived class.
32 const CXXRecordDecl *DerivedClass;
34 /// VirtualBase - If the path from the derived class to the base class
35 /// involves a virtual base class, this holds its declaration.
36 const CXXRecordDecl *VirtualBase;
38 /// NonVirtualOffset - The offset from the derived class to the base class.
39 /// (Or the offset from the virtual base class to the base class, if the
40 /// path from the derived class to the base class involves a virtual base
42 CharUnits NonVirtualOffset;
44 BaseOffset() : DerivedClass(0), VirtualBase(0),
45 NonVirtualOffset(CharUnits::Zero()) { }
46 BaseOffset(const CXXRecordDecl *DerivedClass,
47 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
48 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
49 NonVirtualOffset(NonVirtualOffset) { }
51 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
54 /// FinalOverriders - Contains the final overrider member functions for all
55 /// member functions in the base subobjects of a class.
56 class FinalOverriders {
58 /// OverriderInfo - Information about a final overrider.
59 struct OverriderInfo {
60 /// Method - The method decl of the overrider.
61 const CXXMethodDecl *Method;
63 /// Offset - the base offset of the overrider in the layout class.
66 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
70 /// MostDerivedClass - The most derived class for which the final overriders
72 const CXXRecordDecl *MostDerivedClass;
74 /// MostDerivedClassOffset - If we're building final overriders for a
75 /// construction vtable, this holds the offset from the layout class to the
76 /// most derived class.
77 const CharUnits MostDerivedClassOffset;
79 /// LayoutClass - The class we're using for layout information. Will be
80 /// different than the most derived class if the final overriders are for a
81 /// construction vtable.
82 const CXXRecordDecl *LayoutClass;
86 /// MostDerivedClassLayout - the AST record layout of the most derived class.
87 const ASTRecordLayout &MostDerivedClassLayout;
89 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
90 /// in a base subobject.
91 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
93 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
94 OverriderInfo> OverridersMapTy;
96 /// OverridersMap - The final overriders for all virtual member functions of
97 /// all the base subobjects of the most derived class.
98 OverridersMapTy OverridersMap;
100 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
101 /// as a record decl and a subobject number) and its offsets in the most
102 /// derived class as well as the layout class.
103 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
104 CharUnits> SubobjectOffsetMapTy;
106 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
108 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
110 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
111 CharUnits OffsetInLayoutClass,
112 SubobjectOffsetMapTy &SubobjectOffsets,
113 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
114 SubobjectCountMapTy &SubobjectCounts);
116 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
118 /// dump - dump the final overriders for a base subobject, and all its direct
119 /// and indirect base subobjects.
120 void dump(raw_ostream &Out, BaseSubobject Base,
121 VisitedVirtualBasesSetTy& VisitedVirtualBases);
124 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
125 CharUnits MostDerivedClassOffset,
126 const CXXRecordDecl *LayoutClass);
128 /// getOverrider - Get the final overrider for the given method declaration in
129 /// the subobject with the given base offset.
130 OverriderInfo getOverrider(const CXXMethodDecl *MD,
131 CharUnits BaseOffset) const {
132 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
133 "Did not find overrider!");
135 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
138 /// dump - dump the final overriders.
140 VisitedVirtualBasesSetTy VisitedVirtualBases;
141 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
142 VisitedVirtualBases);
147 #define DUMP_OVERRIDERS 0
149 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
150 CharUnits MostDerivedClassOffset,
151 const CXXRecordDecl *LayoutClass)
152 : MostDerivedClass(MostDerivedClass),
153 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
154 Context(MostDerivedClass->getASTContext()),
155 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
157 // Compute base offsets.
158 SubobjectOffsetMapTy SubobjectOffsets;
159 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
160 SubobjectCountMapTy SubobjectCounts;
161 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
163 MostDerivedClassOffset,
164 SubobjectOffsets, SubobjectLayoutClassOffsets,
167 // Get the the final overriders.
168 CXXFinalOverriderMap FinalOverriders;
169 MostDerivedClass->getFinalOverriders(FinalOverriders);
171 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
172 E = FinalOverriders.end(); I != E; ++I) {
173 const CXXMethodDecl *MD = I->first;
174 const OverridingMethods& Methods = I->second;
176 for (OverridingMethods::const_iterator I = Methods.begin(),
177 E = Methods.end(); I != E; ++I) {
178 unsigned SubobjectNumber = I->first;
179 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
181 "Did not find subobject offset!");
183 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
186 assert(I->second.size() == 1 && "Final overrider is not unique!");
187 const UniqueVirtualMethod &Method = I->second.front();
189 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
190 assert(SubobjectLayoutClassOffsets.count(
191 std::make_pair(OverriderRD, Method.Subobject))
192 && "Did not find subobject offset!");
193 CharUnits OverriderOffset =
194 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
197 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
198 assert(!Overrider.Method && "Overrider should not exist yet!");
200 Overrider.Offset = OverriderOffset;
201 Overrider.Method = Method.Method;
206 // And dump them (for now).
211 static BaseOffset ComputeBaseOffset(ASTContext &Context,
212 const CXXRecordDecl *DerivedRD,
213 const CXXBasePath &Path) {
214 CharUnits NonVirtualOffset = CharUnits::Zero();
216 unsigned NonVirtualStart = 0;
217 const CXXRecordDecl *VirtualBase = 0;
219 // First, look for the virtual base class.
220 for (unsigned I = 0, E = Path.size(); I != E; ++I) {
221 const CXXBasePathElement &Element = Path[I];
223 if (Element.Base->isVirtual()) {
224 // FIXME: Can we break when we find the first virtual base?
225 // (If we can't, can't we just iterate over the path in reverse order?)
226 NonVirtualStart = I + 1;
227 QualType VBaseType = Element.Base->getType();
229 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
233 // Now compute the non-virtual offset.
234 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
235 const CXXBasePathElement &Element = Path[I];
237 // Check the base class offset.
238 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
240 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
241 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
243 NonVirtualOffset += Layout.getBaseClassOffset(Base);
246 // FIXME: This should probably use CharUnits or something. Maybe we should
247 // even change the base offsets in ASTRecordLayout to be specified in
249 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
253 static BaseOffset ComputeBaseOffset(ASTContext &Context,
254 const CXXRecordDecl *BaseRD,
255 const CXXRecordDecl *DerivedRD) {
256 CXXBasePaths Paths(/*FindAmbiguities=*/false,
257 /*RecordPaths=*/true, /*DetectVirtual=*/false);
259 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
260 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
261 llvm_unreachable("Class must be derived from the passed in base class!");
264 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
268 ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
269 const CXXMethodDecl *DerivedMD,
270 const CXXMethodDecl *BaseMD) {
271 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
272 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
274 // Canonicalize the return types.
275 CanQualType CanDerivedReturnType =
276 Context.getCanonicalType(DerivedFT->getResultType());
277 CanQualType CanBaseReturnType =
278 Context.getCanonicalType(BaseFT->getResultType());
280 assert(CanDerivedReturnType->getTypeClass() ==
281 CanBaseReturnType->getTypeClass() &&
282 "Types must have same type class!");
284 if (CanDerivedReturnType == CanBaseReturnType) {
285 // No adjustment needed.
289 if (isa<ReferenceType>(CanDerivedReturnType)) {
290 CanDerivedReturnType =
291 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
293 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
294 } else if (isa<PointerType>(CanDerivedReturnType)) {
295 CanDerivedReturnType =
296 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
298 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
300 llvm_unreachable("Unexpected return type!");
303 // We need to compare unqualified types here; consider
304 // const T *Base::foo();
305 // T *Derived::foo();
306 if (CanDerivedReturnType.getUnqualifiedType() ==
307 CanBaseReturnType.getUnqualifiedType()) {
308 // No adjustment needed.
312 const CXXRecordDecl *DerivedRD =
313 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
315 const CXXRecordDecl *BaseRD =
316 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
318 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
322 FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
323 CharUnits OffsetInLayoutClass,
324 SubobjectOffsetMapTy &SubobjectOffsets,
325 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
326 SubobjectCountMapTy &SubobjectCounts) {
327 const CXXRecordDecl *RD = Base.getBase();
329 unsigned SubobjectNumber = 0;
331 SubobjectNumber = ++SubobjectCounts[RD];
333 // Set up the subobject to offset mapping.
334 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
335 && "Subobject offset already exists!");
336 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
337 && "Subobject offset already exists!");
339 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
340 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
343 // Traverse our bases.
344 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
345 E = RD->bases_end(); I != E; ++I) {
346 const CXXRecordDecl *BaseDecl =
347 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
349 CharUnits BaseOffset;
350 CharUnits BaseOffsetInLayoutClass;
351 if (I->isVirtual()) {
352 // Check if we've visited this virtual base before.
353 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
356 const ASTRecordLayout &LayoutClassLayout =
357 Context.getASTRecordLayout(LayoutClass);
359 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
360 BaseOffsetInLayoutClass =
361 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
363 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
364 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
366 BaseOffset = Base.getBaseOffset() + Offset;
367 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
370 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
371 I->isVirtual(), BaseOffsetInLayoutClass,
372 SubobjectOffsets, SubobjectLayoutClassOffsets,
377 void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
378 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
379 const CXXRecordDecl *RD = Base.getBase();
380 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
382 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
383 E = RD->bases_end(); I != E; ++I) {
384 const CXXRecordDecl *BaseDecl =
385 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
387 // Ignore bases that don't have any virtual member functions.
388 if (!BaseDecl->isPolymorphic())
391 CharUnits BaseOffset;
392 if (I->isVirtual()) {
393 if (!VisitedVirtualBases.insert(BaseDecl)) {
394 // We've visited this base before.
398 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
400 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
403 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
406 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
407 Out << Base.getBaseOffset().getQuantity() << ")\n";
409 // Now dump the overriders for this base subobject.
410 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
411 E = RD->method_end(); I != E; ++I) {
412 const CXXMethodDecl *MD = *I;
414 if (!MD->isVirtual())
417 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
419 Out << " " << MD->getQualifiedNameAsString() << " - (";
420 Out << Overrider.Method->getQualifiedNameAsString();
421 Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
424 if (!Overrider.Method->isPure())
425 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
427 if (!Offset.isEmpty()) {
428 Out << " [ret-adj: ";
429 if (Offset.VirtualBase)
430 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
432 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
439 /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
440 struct VCallOffsetMap {
442 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
444 /// Offsets - Keeps track of methods and their offsets.
445 // FIXME: This should be a real map and not a vector.
446 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
448 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
449 /// can share the same vcall offset.
450 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
451 const CXXMethodDecl *RHS);
454 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
455 /// add was successful, or false if there was already a member function with
456 /// the same signature in the map.
457 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
459 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
460 /// vtable address point) for the given virtual member function.
461 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
463 // empty - Return whether the offset map is empty or not.
464 bool empty() const { return Offsets.empty(); }
467 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
468 const CXXMethodDecl *RHS) {
469 const FunctionProtoType *LT =
470 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
471 const FunctionProtoType *RT =
472 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
474 // Fast-path matches in the canonical types.
475 if (LT == RT) return true;
477 // Force the signatures to match. We can't rely on the overrides
478 // list here because there isn't necessarily an inheritance
479 // relationship between the two methods.
480 if (LT->getTypeQuals() != RT->getTypeQuals() ||
481 LT->getNumArgs() != RT->getNumArgs())
483 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
484 if (LT->getArgType(I) != RT->getArgType(I))
489 bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
490 const CXXMethodDecl *RHS) {
491 assert(LHS->isVirtual() && "LHS must be virtual!");
492 assert(RHS->isVirtual() && "LHS must be virtual!");
494 // A destructor can share a vcall offset with another destructor.
495 if (isa<CXXDestructorDecl>(LHS))
496 return isa<CXXDestructorDecl>(RHS);
498 // FIXME: We need to check more things here.
500 // The methods must have the same name.
501 DeclarationName LHSName = LHS->getDeclName();
502 DeclarationName RHSName = RHS->getDeclName();
503 if (LHSName != RHSName)
506 // And the same signatures.
507 return HasSameVirtualSignature(LHS, RHS);
510 bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
511 CharUnits OffsetOffset) {
512 // Check if we can reuse an offset.
513 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
514 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
519 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
523 CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
524 // Look for an offset.
525 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
526 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
527 return Offsets[I].second;
530 llvm_unreachable("Should always find a vcall offset offset!");
533 /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
534 class VCallAndVBaseOffsetBuilder {
536 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
537 VBaseOffsetOffsetsMapTy;
540 /// MostDerivedClass - The most derived class for which we're building vcall
541 /// and vbase offsets.
542 const CXXRecordDecl *MostDerivedClass;
544 /// LayoutClass - The class we're using for layout information. Will be
545 /// different than the most derived class if we're building a construction
547 const CXXRecordDecl *LayoutClass;
549 /// Context - The ASTContext which we will use for layout information.
552 /// Components - vcall and vbase offset components
553 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
554 VTableComponentVectorTy Components;
556 /// VisitedVirtualBases - Visited virtual bases.
557 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
559 /// VCallOffsets - Keeps track of vcall offsets.
560 VCallOffsetMap VCallOffsets;
563 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
564 /// relative to the address point.
565 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
567 /// FinalOverriders - The final overriders of the most derived class.
568 /// (Can be null when we're not building a vtable of the most derived class).
569 const FinalOverriders *Overriders;
571 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
572 /// given base subobject.
573 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
574 CharUnits RealBaseOffset);
576 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
577 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
579 /// AddVBaseOffsets - Add vbase offsets for the given class.
580 void AddVBaseOffsets(const CXXRecordDecl *Base,
581 CharUnits OffsetInLayoutClass);
583 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
584 /// chars, relative to the vtable address point.
585 CharUnits getCurrentOffsetOffset() const;
588 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
589 const CXXRecordDecl *LayoutClass,
590 const FinalOverriders *Overriders,
591 BaseSubobject Base, bool BaseIsVirtual,
592 CharUnits OffsetInLayoutClass)
593 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
594 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
596 // Add vcall and vbase offsets.
597 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
600 /// Methods for iterating over the components.
601 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
602 const_iterator components_begin() const { return Components.rbegin(); }
603 const_iterator components_end() const { return Components.rend(); }
605 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
606 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
607 return VBaseOffsetOffsets;
612 VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
614 CharUnits RealBaseOffset) {
615 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
617 // Itanium C++ ABI 2.5.2:
618 // ..in classes sharing a virtual table with a primary base class, the vcall
619 // and vbase offsets added by the derived class all come before the vcall
620 // and vbase offsets required by the base class, so that the latter may be
621 // laid out as required by the base class without regard to additions from
622 // the derived class(es).
624 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
625 // emit them for the primary base first).
626 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
627 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
629 CharUnits PrimaryBaseOffset;
631 // Get the base offset of the primary base.
632 if (PrimaryBaseIsVirtual) {
633 assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
634 "Primary vbase should have a zero offset!");
636 const ASTRecordLayout &MostDerivedClassLayout =
637 Context.getASTRecordLayout(MostDerivedClass);
640 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
642 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
643 "Primary base should have a zero offset!");
645 PrimaryBaseOffset = Base.getBaseOffset();
648 AddVCallAndVBaseOffsets(
649 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
650 PrimaryBaseIsVirtual, RealBaseOffset);
653 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
655 // We only want to add vcall offsets for virtual bases.
657 AddVCallOffsets(Base, RealBaseOffset);
660 CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
661 // OffsetIndex is the index of this vcall or vbase offset, relative to the
662 // vtable address point. (We subtract 3 to account for the information just
663 // above the address point, the RTTI info, the offset to top, and the
664 // vcall offset itself).
665 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
667 CharUnits PointerWidth =
668 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
669 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
673 void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
674 CharUnits VBaseOffset) {
675 const CXXRecordDecl *RD = Base.getBase();
676 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
678 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
680 // Handle the primary base first.
681 // We only want to add vcall offsets if the base is non-virtual; a virtual
682 // primary base will have its vcall and vbase offsets emitted already.
683 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
684 // Get the base offset of the primary base.
685 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
686 "Primary base should have a zero offset!");
688 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
692 // Add the vcall offsets.
693 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
694 E = RD->method_end(); I != E; ++I) {
695 const CXXMethodDecl *MD = *I;
697 if (!MD->isVirtual())
700 CharUnits OffsetOffset = getCurrentOffsetOffset();
702 // Don't add a vcall offset if we already have one for this member function
704 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
707 CharUnits Offset = CharUnits::Zero();
710 // Get the final overrider.
711 FinalOverriders::OverriderInfo Overrider =
712 Overriders->getOverrider(MD, Base.getBaseOffset());
714 /// The vcall offset is the offset from the virtual base to the object
715 /// where the function was overridden.
716 Offset = Overrider.Offset - VBaseOffset;
719 Components.push_back(
720 VTableComponent::MakeVCallOffset(Offset));
723 // And iterate over all non-virtual bases (ignoring the primary base).
724 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
725 E = RD->bases_end(); I != E; ++I) {
730 const CXXRecordDecl *BaseDecl =
731 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
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 (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
752 E = RD->bases_end(); I != E; ++I) {
753 const CXXRecordDecl *BaseDecl =
754 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
756 // Check if this is a virtual base that we haven't visited before.
757 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
759 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
761 // Add the vbase offset offset.
762 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
763 "vbase offset offset already exists!");
765 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
766 VBaseOffsetOffsets.insert(
767 std::make_pair(BaseDecl, VBaseOffsetOffset));
769 Components.push_back(
770 VTableComponent::MakeVBaseOffset(Offset));
773 // Check the base class looking for more vbase offsets.
774 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
778 /// VTableBuilder - Class for building vtable layout information.
779 class VTableBuilder {
781 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
783 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
784 PrimaryBasesSetVectorTy;
786 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
787 VBaseOffsetOffsetsMapTy;
789 typedef llvm::DenseMap<BaseSubobject, uint64_t>
793 /// VTables - Global vtable information.
794 VTableContext &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 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
867 /// VTableThunks - The thunks by vtable index in the vtable currently being
869 VTableThunksMapTy VTableThunks;
871 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
872 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
874 /// Thunks - A map that contains all the thunks needed for all methods in the
875 /// most derived class for which the vtable is currently being built.
878 /// AddThunk - Add a thunk for the given method.
879 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
881 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
882 /// part of the vtable we're currently building.
883 void ComputeThisAdjustments();
885 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
887 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
889 VisitedVirtualBasesSetTy PrimaryVirtualBases;
891 /// ComputeReturnAdjustment - Compute the return adjustment given a return
892 /// adjustment base offset.
893 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
895 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
896 /// the 'this' pointer from the base subobject to the derived subobject.
897 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
898 BaseSubobject Derived) const;
900 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
901 /// given virtual member function, its offset in the layout class and its
904 ComputeThisAdjustment(const CXXMethodDecl *MD,
905 CharUnits BaseOffsetInLayoutClass,
906 FinalOverriders::OverriderInfo Overrider);
908 /// AddMethod - Add a single virtual member function to the vtable
909 /// components vector.
910 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
912 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
913 /// part of the vtable.
915 /// Itanium C++ ABI 2.5.2:
917 /// struct A { virtual void f(); };
918 /// struct B : virtual public A { int i; };
919 /// struct C : virtual public A { int j; };
920 /// struct D : public B, public C {};
922 /// When B and C are declared, A is a primary base in each case, so although
923 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
924 /// adjustment is required and no thunk is generated. However, inside D
925 /// objects, A is no longer a primary base of C, so if we allowed calls to
926 /// C::f() to use the copy of A's vtable in the C subobject, we would need
927 /// to adjust this from C* to B::A*, which would require a third-party
928 /// thunk. Since we require that a call to C::f() first convert to A*,
929 /// C-in-D's copy of A's vtable is never referenced, so this is not
931 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
932 CharUnits BaseOffsetInLayoutClass,
933 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
934 CharUnits FirstBaseOffsetInLayoutClass) const;
937 /// AddMethods - Add the methods of this base subobject and all its
938 /// primary bases to the vtable components vector.
939 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
940 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
941 CharUnits FirstBaseOffsetInLayoutClass,
942 PrimaryBasesSetVectorTy &PrimaryBases);
944 // LayoutVTable - Layout the vtable for the given base class, including its
945 // secondary vtables and any vtables for virtual bases.
948 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
949 /// given base subobject, as well as all its secondary vtables.
951 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
952 /// or a direct or indirect base of a virtual base.
954 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
955 /// in the layout class.
956 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
957 bool BaseIsMorallyVirtual,
958 bool BaseIsVirtualInLayoutClass,
959 CharUnits OffsetInLayoutClass);
961 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
964 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
965 /// or a direct or indirect base of a virtual base.
966 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
967 CharUnits OffsetInLayoutClass);
969 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
971 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
972 CharUnits OffsetInLayoutClass,
973 VisitedVirtualBasesSetTy &VBases);
975 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
976 /// given base (excluding any primary bases).
977 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
978 VisitedVirtualBasesSetTy &VBases);
980 /// isBuildingConstructionVTable - Return whether this vtable builder is
981 /// building a construction vtable.
982 bool isBuildingConstructorVTable() const {
983 return MostDerivedClass != LayoutClass;
987 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
988 CharUnits MostDerivedClassOffset,
989 bool MostDerivedClassIsVirtual, const
990 CXXRecordDecl *LayoutClass)
991 : VTables(VTables), MostDerivedClass(MostDerivedClass),
992 MostDerivedClassOffset(MostDerivedClassOffset),
993 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
994 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
995 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
999 if (Context.getLangOpts().DumpVTableLayouts)
1000 dumpLayout(llvm::errs());
1003 uint64_t getNumThunks() const {
1004 return Thunks.size();
1007 ThunksMapTy::const_iterator thunks_begin() const {
1008 return Thunks.begin();
1011 ThunksMapTy::const_iterator thunks_end() const {
1012 return Thunks.end();
1015 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1016 return VBaseOffsetOffsets;
1019 const AddressPointsMapTy &getAddressPoints() const {
1020 return AddressPoints;
1023 /// getNumVTableComponents - Return the number of components in the vtable
1024 /// currently built.
1025 uint64_t getNumVTableComponents() const {
1026 return Components.size();
1029 const VTableComponent *vtable_component_begin() const {
1030 return Components.begin();
1033 const VTableComponent *vtable_component_end() const {
1034 return Components.end();
1037 AddressPointsMapTy::const_iterator address_points_begin() const {
1038 return AddressPoints.begin();
1041 AddressPointsMapTy::const_iterator address_points_end() const {
1042 return AddressPoints.end();
1045 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1046 return VTableThunks.begin();
1049 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1050 return VTableThunks.end();
1053 /// dumpLayout - Dump the vtable layout.
1054 void dumpLayout(raw_ostream&);
1057 void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1058 assert(!isBuildingConstructorVTable() &&
1059 "Can't add thunks for construction vtable");
1061 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1063 // Check if we have this thunk already.
1064 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1068 ThunksVector.push_back(Thunk);
1071 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1073 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1074 /// the overridden methods that the function decl overrides.
1076 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1077 OverriddenMethodsSetTy& OverriddenMethods) {
1078 assert(MD->isVirtual() && "Method is not virtual!");
1080 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1081 E = MD->end_overridden_methods(); I != E; ++I) {
1082 const CXXMethodDecl *OverriddenMD = *I;
1084 OverriddenMethods.insert(OverriddenMD);
1086 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1090 void VTableBuilder::ComputeThisAdjustments() {
1091 // Now go through the method info map and see if any of the methods need
1092 // 'this' pointer adjustments.
1093 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1094 E = MethodInfoMap.end(); I != E; ++I) {
1095 const CXXMethodDecl *MD = I->first;
1096 const MethodInfo &MethodInfo = I->second;
1098 // Ignore adjustments for unused function pointers.
1099 uint64_t VTableIndex = MethodInfo.VTableIndex;
1100 if (Components[VTableIndex].getKind() ==
1101 VTableComponent::CK_UnusedFunctionPointer)
1104 // Get the final overrider for this method.
1105 FinalOverriders::OverriderInfo Overrider =
1106 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1108 // Check if we need an adjustment at all.
1109 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1110 // When a return thunk is needed by a derived class that overrides a
1111 // virtual base, gcc uses a virtual 'this' adjustment as well.
1112 // While the thunk itself might be needed by vtables in subclasses or
1113 // in construction vtables, there doesn't seem to be a reason for using
1114 // the thunk in this vtable. Still, we do so to match gcc.
1115 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1119 ThisAdjustment ThisAdjustment =
1120 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1122 if (ThisAdjustment.isEmpty())
1126 VTableThunks[VTableIndex].This = ThisAdjustment;
1128 if (isa<CXXDestructorDecl>(MD)) {
1129 // Add an adjustment for the deleting destructor as well.
1130 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1134 /// Clear the method info map.
1135 MethodInfoMap.clear();
1137 if (isBuildingConstructorVTable()) {
1138 // We don't need to store thunk information for construction vtables.
1142 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1143 E = VTableThunks.end(); I != E; ++I) {
1144 const VTableComponent &Component = Components[I->first];
1145 const ThunkInfo &Thunk = I->second;
1146 const CXXMethodDecl *MD;
1148 switch (Component.getKind()) {
1150 llvm_unreachable("Unexpected vtable component kind!");
1151 case VTableComponent::CK_FunctionPointer:
1152 MD = Component.getFunctionDecl();
1154 case VTableComponent::CK_CompleteDtorPointer:
1155 MD = Component.getDestructorDecl();
1157 case VTableComponent::CK_DeletingDtorPointer:
1158 // We've already added the thunk when we saw the complete dtor pointer.
1162 if (MD->getParent() == MostDerivedClass)
1163 AddThunk(MD, Thunk);
1167 ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1168 ReturnAdjustment Adjustment;
1170 if (!Offset.isEmpty()) {
1171 if (Offset.VirtualBase) {
1172 // Get the virtual base offset offset.
1173 if (Offset.DerivedClass == MostDerivedClass) {
1174 // We can get the offset offset directly from our map.
1175 Adjustment.VBaseOffsetOffset =
1176 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1178 Adjustment.VBaseOffsetOffset =
1179 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1180 Offset.VirtualBase).getQuantity();
1184 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1191 VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1192 BaseSubobject Derived) const {
1193 const CXXRecordDecl *BaseRD = Base.getBase();
1194 const CXXRecordDecl *DerivedRD = Derived.getBase();
1196 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1197 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1199 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1200 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1201 llvm_unreachable("Class must be derived from the passed in base class!");
1204 // We have to go through all the paths, and see which one leads us to the
1205 // right base subobject.
1206 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1208 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1210 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1212 if (Offset.VirtualBase) {
1213 // If we have a virtual base class, the non-virtual offset is relative
1214 // to the virtual base class offset.
1215 const ASTRecordLayout &LayoutClassLayout =
1216 Context.getASTRecordLayout(LayoutClass);
1218 /// Get the virtual base offset, relative to the most derived class
1220 OffsetToBaseSubobject +=
1221 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1223 // Otherwise, the non-virtual offset is relative to the derived class
1225 OffsetToBaseSubobject += Derived.getBaseOffset();
1228 // Check if this path gives us the right base subobject.
1229 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1230 // Since we're going from the base class _to_ the derived class, we'll
1231 // invert the non-virtual offset here.
1232 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1237 return BaseOffset();
1241 VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1242 CharUnits BaseOffsetInLayoutClass,
1243 FinalOverriders::OverriderInfo Overrider) {
1244 // Ignore adjustments for pure virtual member functions.
1245 if (Overrider.Method->isPure())
1246 return ThisAdjustment();
1248 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1249 BaseOffsetInLayoutClass);
1251 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1254 // Compute the adjustment offset.
1255 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1256 OverriderBaseSubobject);
1257 if (Offset.isEmpty())
1258 return ThisAdjustment();
1260 ThisAdjustment Adjustment;
1262 if (Offset.VirtualBase) {
1263 // Get the vcall offset map for this virtual base.
1264 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1266 if (VCallOffsets.empty()) {
1267 // We don't have vcall offsets for this virtual base, go ahead and
1269 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1270 /*FinalOverriders=*/0,
1271 BaseSubobject(Offset.VirtualBase,
1273 /*BaseIsVirtual=*/true,
1274 /*OffsetInLayoutClass=*/
1277 VCallOffsets = Builder.getVCallOffsets();
1280 Adjustment.VCallOffsetOffset =
1281 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1284 // Set the non-virtual part of the adjustment.
1285 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1291 VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1292 ReturnAdjustment ReturnAdjustment) {
1293 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1294 assert(ReturnAdjustment.isEmpty() &&
1295 "Destructor can't have return adjustment!");
1297 // Add both the complete destructor and the deleting destructor.
1298 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1299 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1301 // Add the return adjustment if necessary.
1302 if (!ReturnAdjustment.isEmpty())
1303 VTableThunks[Components.size()].Return = ReturnAdjustment;
1305 // Add the function.
1306 Components.push_back(VTableComponent::MakeFunction(MD));
1310 /// OverridesIndirectMethodInBase - Return whether the given member function
1311 /// overrides any methods in the set of given bases.
1312 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1313 /// For example, if we have:
1315 /// struct A { virtual void f(); }
1316 /// struct B : A { virtual void f(); }
1317 /// struct C : B { virtual void f(); }
1319 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1320 /// and { A } as the set of bases.
1322 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1323 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1324 if (Bases.count(MD->getParent()))
1327 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1328 E = MD->end_overridden_methods(); I != E; ++I) {
1329 const CXXMethodDecl *OverriddenMD = *I;
1331 // Check "indirect overriders".
1332 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1340 VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1341 CharUnits BaseOffsetInLayoutClass,
1342 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1343 CharUnits FirstBaseOffsetInLayoutClass) const {
1344 // If the base and the first base in the primary base chain have the same
1345 // offsets, then this overrider will be used.
1346 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1349 // We know now that Base (or a direct or indirect base of it) is a primary
1350 // base in part of the class hierarchy, but not a primary base in the most
1353 // If the overrider is the first base in the primary base chain, we know
1354 // that the overrider will be used.
1355 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1358 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1360 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1361 PrimaryBases.insert(RD);
1363 // Now traverse the base chain, starting with the first base, until we find
1364 // the base that is no longer a primary base.
1366 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1367 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1372 if (Layout.isPrimaryBaseVirtual()) {
1373 assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1374 "Primary base should always be at offset 0!");
1376 const ASTRecordLayout &LayoutClassLayout =
1377 Context.getASTRecordLayout(LayoutClass);
1379 // Now check if this is the primary base that is not a primary base in the
1380 // most derived class.
1381 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1382 FirstBaseOffsetInLayoutClass) {
1383 // We found it, stop walking the chain.
1387 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1388 "Primary base should always be at offset 0!");
1391 if (!PrimaryBases.insert(PrimaryBase))
1392 llvm_unreachable("Found a duplicate primary base!");
1397 // If the final overrider is an override of one of the primary bases,
1398 // then we know that it will be used.
1399 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1402 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1403 /// from the nearest base. Returns null if no method was found.
1404 static const CXXMethodDecl *
1405 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1406 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1407 OverriddenMethodsSetTy OverriddenMethods;
1408 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1410 for (int I = Bases.size(), E = 0; I != E; --I) {
1411 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1413 // Now check the overriden methods.
1414 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1415 E = OverriddenMethods.end(); I != E; ++I) {
1416 const CXXMethodDecl *OverriddenMD = *I;
1418 // We found our overridden method.
1419 if (OverriddenMD->getParent() == PrimaryBase)
1420 return OverriddenMD;
1428 VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1429 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1430 CharUnits FirstBaseOffsetInLayoutClass,
1431 PrimaryBasesSetVectorTy &PrimaryBases) {
1432 const CXXRecordDecl *RD = Base.getBase();
1433 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1435 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1436 CharUnits PrimaryBaseOffset;
1437 CharUnits PrimaryBaseOffsetInLayoutClass;
1438 if (Layout.isPrimaryBaseVirtual()) {
1439 assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1440 "Primary vbase should have a zero offset!");
1442 const ASTRecordLayout &MostDerivedClassLayout =
1443 Context.getASTRecordLayout(MostDerivedClass);
1446 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1448 const ASTRecordLayout &LayoutClassLayout =
1449 Context.getASTRecordLayout(LayoutClass);
1451 PrimaryBaseOffsetInLayoutClass =
1452 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1454 assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1455 "Primary base should have a zero offset!");
1457 PrimaryBaseOffset = Base.getBaseOffset();
1458 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1461 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1462 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1463 FirstBaseOffsetInLayoutClass, PrimaryBases);
1465 if (!PrimaryBases.insert(PrimaryBase))
1466 llvm_unreachable("Found a duplicate primary base!");
1469 // Now go through all virtual member functions and add them.
1470 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1471 E = RD->method_end(); I != E; ++I) {
1472 const CXXMethodDecl *MD = *I;
1474 if (!MD->isVirtual())
1477 // Get the final overrider.
1478 FinalOverriders::OverriderInfo Overrider =
1479 Overriders.getOverrider(MD, Base.getBaseOffset());
1481 // Check if this virtual member function overrides a method in a primary
1482 // base. If this is the case, and the return type doesn't require adjustment
1483 // then we can just use the member function from the primary base.
1484 if (const CXXMethodDecl *OverriddenMD =
1485 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1486 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1487 OverriddenMD).isEmpty()) {
1488 // Replace the method info of the overridden method with our own
1490 assert(MethodInfoMap.count(OverriddenMD) &&
1491 "Did not find the overridden method!");
1492 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1494 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1495 OverriddenMethodInfo.VTableIndex);
1497 assert(!MethodInfoMap.count(MD) &&
1498 "Should not have method info for this method yet!");
1500 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1501 MethodInfoMap.erase(OverriddenMD);
1503 // If the overridden method exists in a virtual base class or a direct
1504 // or indirect base class of a virtual base class, we need to emit a
1505 // thunk if we ever have a class hierarchy where the base class is not
1506 // a primary base in the complete object.
1507 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1508 // Compute the this adjustment.
1509 ThisAdjustment ThisAdjustment =
1510 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1513 if (ThisAdjustment.VCallOffsetOffset &&
1514 Overrider.Method->getParent() == MostDerivedClass) {
1516 // There's no return adjustment from OverriddenMD and MD,
1517 // but that doesn't mean there isn't one between MD and
1518 // the final overrider.
1519 BaseOffset ReturnAdjustmentOffset =
1520 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1521 ReturnAdjustment ReturnAdjustment =
1522 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1524 // This is a virtual thunk for the most derived class, add it.
1525 AddThunk(Overrider.Method,
1526 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1534 // Insert the method info for this method.
1535 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1538 assert(!MethodInfoMap.count(MD) &&
1539 "Should not have method info for this method yet!");
1540 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1542 // Check if this overrider is going to be used.
1543 const CXXMethodDecl *OverriderMD = Overrider.Method;
1544 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1545 FirstBaseInPrimaryBaseChain,
1546 FirstBaseOffsetInLayoutClass)) {
1547 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1551 // Check if this overrider needs a return adjustment.
1552 // We don't want to do this for pure virtual member functions.
1553 BaseOffset ReturnAdjustmentOffset;
1554 if (!OverriderMD->isPure()) {
1555 ReturnAdjustmentOffset =
1556 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1559 ReturnAdjustment ReturnAdjustment =
1560 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1562 AddMethod(Overrider.Method, ReturnAdjustment);
1566 void VTableBuilder::LayoutVTable() {
1567 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1569 /*BaseIsMorallyVirtual=*/false,
1570 MostDerivedClassIsVirtual,
1571 MostDerivedClassOffset);
1573 VisitedVirtualBasesSetTy VBases;
1575 // Determine the primary virtual bases.
1576 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1580 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1582 // -fapple-kext adds an extra entry at end of vtbl.
1583 bool IsAppleKext = Context.getLangOpts().AppleKext;
1585 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1589 VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1590 bool BaseIsMorallyVirtual,
1591 bool BaseIsVirtualInLayoutClass,
1592 CharUnits OffsetInLayoutClass) {
1593 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1595 // Add vcall and vbase offsets for this vtable.
1596 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1597 Base, BaseIsVirtualInLayoutClass,
1598 OffsetInLayoutClass);
1599 Components.append(Builder.components_begin(), Builder.components_end());
1601 // Check if we need to add these vcall offsets.
1602 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1603 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1605 if (VCallOffsets.empty())
1606 VCallOffsets = Builder.getVCallOffsets();
1609 // If we're laying out the most derived class we want to keep track of the
1610 // virtual base class offset offsets.
1611 if (Base.getBase() == MostDerivedClass)
1612 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1614 // Add the offset to top.
1615 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1616 Components.push_back(
1617 VTableComponent::MakeOffsetToTop(OffsetToTop));
1619 // Next, add the RTTI.
1620 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1622 uint64_t AddressPoint = Components.size();
1624 // Now go through all virtual member functions and add them.
1625 PrimaryBasesSetVectorTy PrimaryBases;
1626 AddMethods(Base, OffsetInLayoutClass,
1627 Base.getBase(), OffsetInLayoutClass,
1630 // Compute 'this' pointer adjustments.
1631 ComputeThisAdjustments();
1633 // Add all address points.
1634 const CXXRecordDecl *RD = Base.getBase();
1636 AddressPoints.insert(std::make_pair(
1637 BaseSubobject(RD, OffsetInLayoutClass),
1640 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1641 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1646 if (Layout.isPrimaryBaseVirtual()) {
1647 // Check if this virtual primary base is a primary base in the layout
1648 // class. If it's not, we don't want to add it.
1649 const ASTRecordLayout &LayoutClassLayout =
1650 Context.getASTRecordLayout(LayoutClass);
1652 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1653 OffsetInLayoutClass) {
1654 // We don't want to add this class (or any of its primary bases).
1662 // Layout secondary vtables.
1663 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1666 void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1667 bool BaseIsMorallyVirtual,
1668 CharUnits OffsetInLayoutClass) {
1669 // Itanium C++ ABI 2.5.2:
1670 // Following the primary virtual table of a derived class are secondary
1671 // virtual tables for each of its proper base classes, except any primary
1672 // base(s) with which it shares its primary virtual table.
1674 const CXXRecordDecl *RD = Base.getBase();
1675 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1676 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1678 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1679 E = RD->bases_end(); I != E; ++I) {
1680 // Ignore virtual bases, we'll emit them later.
1684 const CXXRecordDecl *BaseDecl =
1685 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1687 // Ignore bases that don't have a vtable.
1688 if (!BaseDecl->isDynamicClass())
1691 if (isBuildingConstructorVTable()) {
1692 // Itanium C++ ABI 2.6.4:
1693 // Some of the base class subobjects may not need construction virtual
1694 // tables, which will therefore not be present in the construction
1695 // virtual table group, even though the subobject virtual tables are
1696 // present in the main virtual table group for the complete object.
1697 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1701 // Get the base offset of this base.
1702 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1703 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1705 CharUnits BaseOffsetInLayoutClass =
1706 OffsetInLayoutClass + RelativeBaseOffset;
1708 // Don't emit a secondary vtable for a primary base. We might however want
1709 // to emit secondary vtables for other bases of this base.
1710 if (BaseDecl == PrimaryBase) {
1711 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1712 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1716 // Layout the primary vtable (and any secondary vtables) for this base.
1717 LayoutPrimaryAndSecondaryVTables(
1718 BaseSubobject(BaseDecl, BaseOffset),
1719 BaseIsMorallyVirtual,
1720 /*BaseIsVirtualInLayoutClass=*/false,
1721 BaseOffsetInLayoutClass);
1726 VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1727 CharUnits OffsetInLayoutClass,
1728 VisitedVirtualBasesSetTy &VBases) {
1729 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1731 // Check if this base has a primary base.
1732 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1734 // Check if it's virtual.
1735 if (Layout.isPrimaryBaseVirtual()) {
1736 bool IsPrimaryVirtualBase = true;
1738 if (isBuildingConstructorVTable()) {
1739 // Check if the base is actually a primary base in the class we use for
1741 const ASTRecordLayout &LayoutClassLayout =
1742 Context.getASTRecordLayout(LayoutClass);
1744 CharUnits PrimaryBaseOffsetInLayoutClass =
1745 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1747 // We know that the base is not a primary base in the layout class if
1748 // the base offsets are different.
1749 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1750 IsPrimaryVirtualBase = false;
1753 if (IsPrimaryVirtualBase)
1754 PrimaryVirtualBases.insert(PrimaryBase);
1758 // Traverse bases, looking for more primary virtual bases.
1759 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1760 E = RD->bases_end(); I != E; ++I) {
1761 const CXXRecordDecl *BaseDecl =
1762 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1764 CharUnits BaseOffsetInLayoutClass;
1766 if (I->isVirtual()) {
1767 if (!VBases.insert(BaseDecl))
1770 const ASTRecordLayout &LayoutClassLayout =
1771 Context.getASTRecordLayout(LayoutClass);
1773 BaseOffsetInLayoutClass =
1774 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1776 BaseOffsetInLayoutClass =
1777 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1780 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1785 VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1786 VisitedVirtualBasesSetTy &VBases) {
1787 // Itanium C++ ABI 2.5.2:
1788 // Then come the virtual base virtual tables, also in inheritance graph
1789 // order, and again excluding primary bases (which share virtual tables with
1790 // the classes for which they are primary).
1791 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1792 E = RD->bases_end(); I != E; ++I) {
1793 const CXXRecordDecl *BaseDecl =
1794 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1796 // Check if this base needs a vtable. (If it's virtual, not a primary base
1797 // of some other class, and we haven't visited it before).
1798 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1799 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1800 const ASTRecordLayout &MostDerivedClassLayout =
1801 Context.getASTRecordLayout(MostDerivedClass);
1802 CharUnits BaseOffset =
1803 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1805 const ASTRecordLayout &LayoutClassLayout =
1806 Context.getASTRecordLayout(LayoutClass);
1807 CharUnits BaseOffsetInLayoutClass =
1808 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1810 LayoutPrimaryAndSecondaryVTables(
1811 BaseSubobject(BaseDecl, BaseOffset),
1812 /*BaseIsMorallyVirtual=*/true,
1813 /*BaseIsVirtualInLayoutClass=*/true,
1814 BaseOffsetInLayoutClass);
1817 // We only need to check the base for virtual base vtables if it actually
1818 // has virtual bases.
1819 if (BaseDecl->getNumVBases())
1820 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1824 /// dumpLayout - Dump the vtable layout.
1825 void VTableBuilder::dumpLayout(raw_ostream& Out) {
1827 if (isBuildingConstructorVTable()) {
1828 Out << "Construction vtable for ('";
1829 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1830 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1831 Out << LayoutClass->getQualifiedNameAsString();
1833 Out << "Vtable for '";
1834 Out << MostDerivedClass->getQualifiedNameAsString();
1836 Out << "' (" << Components.size() << " entries).\n";
1838 // Iterate through the address points and insert them into a new map where
1839 // they are keyed by the index and not the base object.
1840 // Since an address point can be shared by multiple subobjects, we use an
1842 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1843 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1844 E = AddressPoints.end(); I != E; ++I) {
1845 const BaseSubobject& Base = I->first;
1846 uint64_t Index = I->second;
1848 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1851 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1854 Out << llvm::format("%4d | ", I);
1856 const VTableComponent &Component = Components[I];
1858 // Dump the component.
1859 switch (Component.getKind()) {
1861 case VTableComponent::CK_VCallOffset:
1862 Out << "vcall_offset ("
1863 << Component.getVCallOffset().getQuantity()
1867 case VTableComponent::CK_VBaseOffset:
1868 Out << "vbase_offset ("
1869 << Component.getVBaseOffset().getQuantity()
1873 case VTableComponent::CK_OffsetToTop:
1874 Out << "offset_to_top ("
1875 << Component.getOffsetToTop().getQuantity()
1879 case VTableComponent::CK_RTTI:
1880 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1883 case VTableComponent::CK_FunctionPointer: {
1884 const CXXMethodDecl *MD = Component.getFunctionDecl();
1887 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1893 ThunkInfo Thunk = VTableThunks.lookup(I);
1894 if (!Thunk.isEmpty()) {
1895 // If this function pointer has a return adjustment, dump it.
1896 if (!Thunk.Return.isEmpty()) {
1897 Out << "\n [return adjustment: ";
1898 Out << Thunk.Return.NonVirtual << " non-virtual";
1900 if (Thunk.Return.VBaseOffsetOffset) {
1901 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1902 Out << " vbase offset offset";
1908 // If this function pointer has a 'this' pointer adjustment, dump it.
1909 if (!Thunk.This.isEmpty()) {
1910 Out << "\n [this adjustment: ";
1911 Out << Thunk.This.NonVirtual << " non-virtual";
1913 if (Thunk.This.VCallOffsetOffset) {
1914 Out << ", " << Thunk.This.VCallOffsetOffset;
1915 Out << " vcall offset offset";
1925 case VTableComponent::CK_CompleteDtorPointer:
1926 case VTableComponent::CK_DeletingDtorPointer: {
1928 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1930 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1932 Out << DD->getQualifiedNameAsString();
1934 Out << "() [complete]";
1936 Out << "() [deleting]";
1941 ThunkInfo Thunk = VTableThunks.lookup(I);
1942 if (!Thunk.isEmpty()) {
1943 // If this destructor has a 'this' pointer adjustment, dump it.
1944 if (!Thunk.This.isEmpty()) {
1945 Out << "\n [this adjustment: ";
1946 Out << Thunk.This.NonVirtual << " non-virtual";
1948 if (Thunk.This.VCallOffsetOffset) {
1949 Out << ", " << Thunk.This.VCallOffsetOffset;
1950 Out << " vcall offset offset";
1960 case VTableComponent::CK_UnusedFunctionPointer: {
1961 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1964 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1966 Out << "[unused] " << Str;
1975 // Dump the next address point.
1976 uint64_t NextIndex = Index + 1;
1977 if (AddressPointsByIndex.count(NextIndex)) {
1978 if (AddressPointsByIndex.count(NextIndex) == 1) {
1979 const BaseSubobject &Base =
1980 AddressPointsByIndex.find(NextIndex)->second;
1982 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
1983 Out << ", " << Base.getBaseOffset().getQuantity();
1984 Out << ") vtable address --\n";
1986 CharUnits BaseOffset =
1987 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
1989 // We store the class names in a set to get a stable order.
1990 std::set<std::string> ClassNames;
1991 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
1992 AddressPointsByIndex.lower_bound(NextIndex), E =
1993 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
1994 assert(I->second.getBaseOffset() == BaseOffset &&
1995 "Invalid base offset!");
1996 const CXXRecordDecl *RD = I->second.getBase();
1997 ClassNames.insert(RD->getQualifiedNameAsString());
2000 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2001 E = ClassNames.end(); I != E; ++I) {
2002 Out << " -- (" << *I;
2003 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2011 if (isBuildingConstructorVTable())
2014 if (MostDerivedClass->getNumVBases()) {
2015 // We store the virtual base class names and their offsets in a map to get
2018 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2019 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2020 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2021 std::string ClassName = I->first->getQualifiedNameAsString();
2022 CharUnits OffsetOffset = I->second;
2023 ClassNamesAndOffsets.insert(
2024 std::make_pair(ClassName, OffsetOffset));
2027 Out << "Virtual base offset offsets for '";
2028 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2029 Out << ClassNamesAndOffsets.size();
2030 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2032 for (std::map<std::string, CharUnits>::const_iterator I =
2033 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2035 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2040 if (!Thunks.empty()) {
2041 // We store the method names in a map to get a stable order.
2042 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2044 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2046 const CXXMethodDecl *MD = I->first;
2047 std::string MethodName =
2048 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2051 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2054 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2055 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2057 const std::string &MethodName = I->first;
2058 const CXXMethodDecl *MD = I->second;
2060 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2061 std::sort(ThunksVector.begin(), ThunksVector.end());
2063 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2064 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2066 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2067 const ThunkInfo &Thunk = ThunksVector[I];
2069 Out << llvm::format("%4d | ", I);
2071 // If this function pointer has a return pointer adjustment, dump it.
2072 if (!Thunk.Return.isEmpty()) {
2073 Out << "return adjustment: " << Thunk.This.NonVirtual;
2074 Out << " non-virtual";
2075 if (Thunk.Return.VBaseOffsetOffset) {
2076 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2077 Out << " vbase offset offset";
2080 if (!Thunk.This.isEmpty())
2084 // If this function pointer has a 'this' pointer adjustment, dump it.
2085 if (!Thunk.This.isEmpty()) {
2086 Out << "this adjustment: ";
2087 Out << Thunk.This.NonVirtual << " non-virtual";
2089 if (Thunk.This.VCallOffsetOffset) {
2090 Out << ", " << Thunk.This.VCallOffsetOffset;
2091 Out << " vcall offset offset";
2102 // Compute the vtable indices for all the member functions.
2103 // Store them in a map keyed by the index so we'll get a sorted table.
2104 std::map<uint64_t, std::string> IndicesMap;
2106 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2107 e = MostDerivedClass->method_end(); i != e; ++i) {
2108 const CXXMethodDecl *MD = *i;
2110 // We only want virtual member functions.
2111 if (!MD->isVirtual())
2114 std::string MethodName =
2115 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2118 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2119 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))] =
2120 MethodName + " [complete]";
2121 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))] =
2122 MethodName + " [deleting]";
2124 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2128 // Print the vtable indices for all the member functions.
2129 if (!IndicesMap.empty()) {
2130 Out << "VTable indices for '";
2131 Out << MostDerivedClass->getQualifiedNameAsString();
2132 Out << "' (" << IndicesMap.size() << " entries).\n";
2134 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2135 E = IndicesMap.end(); I != E; ++I) {
2136 uint64_t VTableIndex = I->first;
2137 const std::string &MethodName = I->second;
2139 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
2149 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2150 const VTableComponent *VTableComponents,
2151 uint64_t NumVTableThunks,
2152 const VTableThunkTy *VTableThunks,
2153 const AddressPointsMapTy &AddressPoints)
2154 : NumVTableComponents(NumVTableComponents),
2155 VTableComponents(new VTableComponent[NumVTableComponents]),
2156 NumVTableThunks(NumVTableThunks),
2157 VTableThunks(new VTableThunkTy[NumVTableThunks]),
2158 AddressPoints(AddressPoints) {
2159 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2160 this->VTableComponents.get());
2161 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2162 this->VTableThunks.get());
2165 VTableLayout::~VTableLayout() { }
2167 VTableContext::~VTableContext() {
2168 llvm::DeleteContainerSeconds(VTableLayouts);
2172 CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2173 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2174 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2175 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2180 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2182 if (!PrimaryBases.insert(PrimaryBase))
2183 llvm_unreachable("Found a duplicate primary base!");
2186 void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2188 // Itanium C++ ABI 2.5.2:
2189 // The order of the virtual function pointers in a virtual table is the
2190 // order of declaration of the corresponding member functions in the class.
2192 // There is an entry for any virtual function declared in a class,
2193 // whether it is a new function or overrides a base class function,
2194 // unless it overrides a function from the primary base, and conversion
2195 // between their return types does not require an adjustment.
2197 int64_t CurrentIndex = 0;
2199 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2200 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2203 assert(PrimaryBase->isCompleteDefinition() &&
2204 "Should have the definition decl of the primary base!");
2206 // Since the record decl shares its vtable pointer with the primary base
2207 // we need to start counting at the end of the primary base's vtable.
2208 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2211 // Collect all the primary bases, so we can check whether methods override
2212 // a method from the base.
2213 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2214 CollectPrimaryBases(RD, Context, PrimaryBases);
2216 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2218 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2219 e = RD->method_end(); i != e; ++i) {
2220 const CXXMethodDecl *MD = *i;
2222 // We only want virtual methods.
2223 if (!MD->isVirtual())
2226 // Check if this method overrides a method in the primary base.
2227 if (const CXXMethodDecl *OverriddenMD =
2228 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2229 // Check if converting from the return type of the method to the
2230 // return type of the overridden method requires conversion.
2231 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2232 OverriddenMD).isEmpty()) {
2233 // This index is shared between the index in the vtable of the primary
2235 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2236 const CXXDestructorDecl *OverriddenDD =
2237 cast<CXXDestructorDecl>(OverriddenMD);
2239 // Add both the complete and deleting entries.
2240 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2241 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2242 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2243 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2245 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2248 // We don't need to add an entry for this method.
2253 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2254 if (MD->isImplicit()) {
2255 assert(!ImplicitVirtualDtor &&
2256 "Did already see an implicit virtual dtor!");
2257 ImplicitVirtualDtor = DD;
2261 // Add the complete dtor.
2262 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2264 // Add the deleting dtor.
2265 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2268 MethodVTableIndices[MD] = CurrentIndex++;
2272 if (ImplicitVirtualDtor) {
2273 // Itanium C++ ABI 2.5.2:
2274 // If a class has an implicitly-defined virtual destructor,
2275 // its entries come after the declared virtual function pointers.
2277 // Add the complete dtor.
2278 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2281 // Add the deleting dtor.
2282 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2286 NumVirtualFunctionPointers[RD] = CurrentIndex;
2289 uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2290 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2291 NumVirtualFunctionPointers.find(RD);
2292 if (I != NumVirtualFunctionPointers.end())
2295 ComputeMethodVTableIndices(RD);
2297 I = NumVirtualFunctionPointers.find(RD);
2298 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2302 uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2303 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2304 if (I != MethodVTableIndices.end())
2307 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2309 ComputeMethodVTableIndices(RD);
2311 I = MethodVTableIndices.find(GD);
2312 assert(I != MethodVTableIndices.end() && "Did not find index!");
2317 VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2318 const CXXRecordDecl *VBase) {
2319 ClassPairTy ClassPair(RD, VBase);
2321 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2322 VirtualBaseClassOffsetOffsets.find(ClassPair);
2323 if (I != VirtualBaseClassOffsetOffsets.end())
2326 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2327 BaseSubobject(RD, CharUnits::Zero()),
2328 /*BaseIsVirtual=*/false,
2329 /*OffsetInLayoutClass=*/CharUnits::Zero());
2331 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2332 Builder.getVBaseOffsetOffsets().begin(),
2333 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2334 // Insert all types.
2335 ClassPairTy ClassPair(RD, I->first);
2337 VirtualBaseClassOffsetOffsets.insert(
2338 std::make_pair(ClassPair, I->second));
2341 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2342 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2347 static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2348 SmallVector<VTableLayout::VTableThunkTy, 1>
2349 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2350 std::sort(VTableThunks.begin(), VTableThunks.end());
2352 return new VTableLayout(Builder.getNumVTableComponents(),
2353 Builder.vtable_component_begin(),
2354 VTableThunks.size(),
2355 VTableThunks.data(),
2356 Builder.getAddressPoints());
2359 void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2360 const VTableLayout *&Entry = VTableLayouts[RD];
2362 // Check if we've computed this information before.
2366 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2367 /*MostDerivedClassIsVirtual=*/0, RD);
2368 Entry = CreateVTableLayout(Builder);
2370 // Add the known thunks.
2371 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2373 // If we don't have the vbase information for this class, insert it.
2374 // getVirtualBaseOffsetOffset will compute it separately without computing
2375 // the rest of the vtable related information.
2376 if (!RD->getNumVBases())
2379 const RecordType *VBaseRT =
2380 RD->vbases_begin()->getType()->getAs<RecordType>();
2381 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2383 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2386 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2387 Builder.getVBaseOffsetOffsets().begin(),
2388 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2389 // Insert all types.
2390 ClassPairTy ClassPair(RD, I->first);
2392 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2396 VTableLayout *VTableContext::createConstructionVTableLayout(
2397 const CXXRecordDecl *MostDerivedClass,
2398 CharUnits MostDerivedClassOffset,
2399 bool MostDerivedClassIsVirtual,
2400 const CXXRecordDecl *LayoutClass) {
2401 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2402 MostDerivedClassIsVirtual, LayoutClass);
2403 return CreateVTableLayout(Builder);