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"
20 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
26 #define DUMP_OVERRIDERS 0
30 /// BaseOffset - Represents an offset from a derived class to a direct or
31 /// indirect base class.
33 /// DerivedClass - The derived class.
34 const CXXRecordDecl *DerivedClass;
36 /// VirtualBase - If the path from the derived class to the base class
37 /// involves a virtual base class, this holds its declaration.
38 const CXXRecordDecl *VirtualBase;
40 /// NonVirtualOffset - The offset from the derived class to the base class.
41 /// (Or the offset from the virtual base class to the base class, if the
42 /// path from the derived class to the base class involves a virtual base
44 CharUnits NonVirtualOffset;
46 BaseOffset() : DerivedClass(0), VirtualBase(0),
47 NonVirtualOffset(CharUnits::Zero()) { }
48 BaseOffset(const CXXRecordDecl *DerivedClass,
49 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
50 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
51 NonVirtualOffset(NonVirtualOffset) { }
53 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
56 /// FinalOverriders - Contains the final overrider member functions for all
57 /// member functions in the base subobjects of a class.
58 class FinalOverriders {
60 /// OverriderInfo - Information about a final overrider.
61 struct OverriderInfo {
62 /// Method - The method decl of the overrider.
63 const CXXMethodDecl *Method;
65 /// Offset - the base offset of the overrider in the layout class.
68 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
72 /// MostDerivedClass - The most derived class for which the final overriders
74 const CXXRecordDecl *MostDerivedClass;
76 /// MostDerivedClassOffset - If we're building final overriders for a
77 /// construction vtable, this holds the offset from the layout class to the
78 /// most derived class.
79 const CharUnits MostDerivedClassOffset;
81 /// LayoutClass - The class we're using for layout information. Will be
82 /// different than the most derived class if the final overriders are for a
83 /// construction vtable.
84 const CXXRecordDecl *LayoutClass;
88 /// MostDerivedClassLayout - the AST record layout of the most derived class.
89 const ASTRecordLayout &MostDerivedClassLayout;
91 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
92 /// in a base subobject.
93 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
95 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
96 OverriderInfo> OverridersMapTy;
98 /// OverridersMap - The final overriders for all virtual member functions of
99 /// all the base subobjects of the most derived class.
100 OverridersMapTy OverridersMap;
102 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
103 /// as a record decl and a subobject number) and its offsets in the most
104 /// derived class as well as the layout class.
105 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
106 CharUnits> SubobjectOffsetMapTy;
108 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
110 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
112 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
113 CharUnits OffsetInLayoutClass,
114 SubobjectOffsetMapTy &SubobjectOffsets,
115 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
116 SubobjectCountMapTy &SubobjectCounts);
118 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
120 /// dump - dump the final overriders for a base subobject, and all its direct
121 /// and indirect base subobjects.
122 void dump(raw_ostream &Out, BaseSubobject Base,
123 VisitedVirtualBasesSetTy& VisitedVirtualBases);
126 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
127 CharUnits MostDerivedClassOffset,
128 const CXXRecordDecl *LayoutClass);
130 /// getOverrider - Get the final overrider for the given method declaration in
131 /// the subobject with the given base offset.
132 OverriderInfo getOverrider(const CXXMethodDecl *MD,
133 CharUnits BaseOffset) const {
134 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
135 "Did not find overrider!");
137 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
140 /// dump - dump the final overriders.
142 VisitedVirtualBasesSetTy VisitedVirtualBases;
143 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
144 VisitedVirtualBases);
149 #define DUMP_OVERRIDERS 0
151 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
152 CharUnits MostDerivedClassOffset,
153 const CXXRecordDecl *LayoutClass)
154 : MostDerivedClass(MostDerivedClass),
155 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
156 Context(MostDerivedClass->getASTContext()),
157 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
159 // Compute base offsets.
160 SubobjectOffsetMapTy SubobjectOffsets;
161 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
162 SubobjectCountMapTy SubobjectCounts;
163 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
165 MostDerivedClassOffset,
166 SubobjectOffsets, SubobjectLayoutClassOffsets,
169 // Get the final overriders.
170 CXXFinalOverriderMap FinalOverriders;
171 MostDerivedClass->getFinalOverriders(FinalOverriders);
173 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
174 E = FinalOverriders.end(); I != E; ++I) {
175 const CXXMethodDecl *MD = I->first;
176 const OverridingMethods& Methods = I->second;
178 for (OverridingMethods::const_iterator I = Methods.begin(),
179 E = Methods.end(); I != E; ++I) {
180 unsigned SubobjectNumber = I->first;
181 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
183 "Did not find subobject offset!");
185 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
188 assert(I->second.size() == 1 && "Final overrider is not unique!");
189 const UniqueVirtualMethod &Method = I->second.front();
191 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
192 assert(SubobjectLayoutClassOffsets.count(
193 std::make_pair(OverriderRD, Method.Subobject))
194 && "Did not find subobject offset!");
195 CharUnits OverriderOffset =
196 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
199 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
200 assert(!Overrider.Method && "Overrider should not exist yet!");
202 Overrider.Offset = OverriderOffset;
203 Overrider.Method = Method.Method;
208 // And dump them (for now).
213 static BaseOffset ComputeBaseOffset(ASTContext &Context,
214 const CXXRecordDecl *DerivedRD,
215 const CXXBasePath &Path) {
216 CharUnits NonVirtualOffset = CharUnits::Zero();
218 unsigned NonVirtualStart = 0;
219 const CXXRecordDecl *VirtualBase = 0;
221 // First, look for the virtual base class.
222 for (unsigned I = 0, E = Path.size(); I != E; ++I) {
223 const CXXBasePathElement &Element = Path[I];
225 if (Element.Base->isVirtual()) {
226 // FIXME: Can we break when we find the first virtual base?
227 // (If we can't, can't we just iterate over the path in reverse order?)
228 NonVirtualStart = I + 1;
229 QualType VBaseType = Element.Base->getType();
231 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
235 // Now compute the non-virtual offset.
236 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
237 const CXXBasePathElement &Element = Path[I];
239 // Check the base class offset.
240 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
242 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
243 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
245 NonVirtualOffset += Layout.getBaseClassOffset(Base);
248 // FIXME: This should probably use CharUnits or something. Maybe we should
249 // even change the base offsets in ASTRecordLayout to be specified in
251 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
255 static BaseOffset ComputeBaseOffset(ASTContext &Context,
256 const CXXRecordDecl *BaseRD,
257 const CXXRecordDecl *DerivedRD) {
258 CXXBasePaths Paths(/*FindAmbiguities=*/false,
259 /*RecordPaths=*/true, /*DetectVirtual=*/false);
261 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
262 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.getVBaseClassOffset(PrimaryBase).isZero() &&
634 "Primary vbase should have a zero offset!");
636 const ASTRecordLayout &MostDerivedClassLayout =
637 Context.getASTRecordLayout(MostDerivedClass);
640 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
642 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
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.getBaseClassOffset(PrimaryBase).isZero() &&
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 bool isMicrosoftABI() const {
1004 return VTables.isMicrosoftABI();
1007 uint64_t getNumThunks() const {
1008 return Thunks.size();
1011 ThunksMapTy::const_iterator thunks_begin() const {
1012 return Thunks.begin();
1015 ThunksMapTy::const_iterator thunks_end() const {
1016 return Thunks.end();
1019 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1020 return VBaseOffsetOffsets;
1023 const AddressPointsMapTy &getAddressPoints() const {
1024 return AddressPoints;
1027 /// getNumVTableComponents - Return the number of components in the vtable
1028 /// currently built.
1029 uint64_t getNumVTableComponents() const {
1030 return Components.size();
1033 const VTableComponent *vtable_component_begin() const {
1034 return Components.begin();
1037 const VTableComponent *vtable_component_end() const {
1038 return Components.end();
1041 AddressPointsMapTy::const_iterator address_points_begin() const {
1042 return AddressPoints.begin();
1045 AddressPointsMapTy::const_iterator address_points_end() const {
1046 return AddressPoints.end();
1049 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1050 return VTableThunks.begin();
1053 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1054 return VTableThunks.end();
1057 /// dumpLayout - Dump the vtable layout.
1058 void dumpLayout(raw_ostream&);
1061 void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1062 assert(!isBuildingConstructorVTable() &&
1063 "Can't add thunks for construction vtable");
1065 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1067 // Check if we have this thunk already.
1068 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1072 ThunksVector.push_back(Thunk);
1075 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1077 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1078 /// the overridden methods that the function decl overrides.
1080 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1081 OverriddenMethodsSetTy& OverriddenMethods) {
1082 assert(MD->isVirtual() && "Method is not virtual!");
1084 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1085 E = MD->end_overridden_methods(); I != E; ++I) {
1086 const CXXMethodDecl *OverriddenMD = *I;
1088 OverriddenMethods.insert(OverriddenMD);
1090 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1094 void VTableBuilder::ComputeThisAdjustments() {
1095 // Now go through the method info map and see if any of the methods need
1096 // 'this' pointer adjustments.
1097 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1098 E = MethodInfoMap.end(); I != E; ++I) {
1099 const CXXMethodDecl *MD = I->first;
1100 const MethodInfo &MethodInfo = I->second;
1102 // Ignore adjustments for unused function pointers.
1103 uint64_t VTableIndex = MethodInfo.VTableIndex;
1104 if (Components[VTableIndex].getKind() ==
1105 VTableComponent::CK_UnusedFunctionPointer)
1108 // Get the final overrider for this method.
1109 FinalOverriders::OverriderInfo Overrider =
1110 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1112 // Check if we need an adjustment at all.
1113 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1114 // When a return thunk is needed by a derived class that overrides a
1115 // virtual base, gcc uses a virtual 'this' adjustment as well.
1116 // While the thunk itself might be needed by vtables in subclasses or
1117 // in construction vtables, there doesn't seem to be a reason for using
1118 // the thunk in this vtable. Still, we do so to match gcc.
1119 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1123 ThisAdjustment ThisAdjustment =
1124 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1126 if (ThisAdjustment.isEmpty())
1130 VTableThunks[VTableIndex].This = ThisAdjustment;
1132 if (isa<CXXDestructorDecl>(MD)) {
1133 // Add an adjustment for the deleting destructor as well.
1134 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1138 /// Clear the method info map.
1139 MethodInfoMap.clear();
1141 if (isBuildingConstructorVTable()) {
1142 // We don't need to store thunk information for construction vtables.
1146 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1147 E = VTableThunks.end(); I != E; ++I) {
1148 const VTableComponent &Component = Components[I->first];
1149 const ThunkInfo &Thunk = I->second;
1150 const CXXMethodDecl *MD;
1152 switch (Component.getKind()) {
1154 llvm_unreachable("Unexpected vtable component kind!");
1155 case VTableComponent::CK_FunctionPointer:
1156 MD = Component.getFunctionDecl();
1158 case VTableComponent::CK_CompleteDtorPointer:
1159 MD = Component.getDestructorDecl();
1161 case VTableComponent::CK_DeletingDtorPointer:
1162 // We've already added the thunk when we saw the complete dtor pointer.
1163 // FIXME: check how this works in the Microsoft ABI
1164 // while working on the multiple inheritance patch.
1168 if (MD->getParent() == MostDerivedClass)
1169 AddThunk(MD, Thunk);
1173 ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1174 ReturnAdjustment Adjustment;
1176 if (!Offset.isEmpty()) {
1177 if (Offset.VirtualBase) {
1178 // Get the virtual base offset offset.
1179 if (Offset.DerivedClass == MostDerivedClass) {
1180 // We can get the offset offset directly from our map.
1181 Adjustment.VBaseOffsetOffset =
1182 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1184 Adjustment.VBaseOffsetOffset =
1185 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1186 Offset.VirtualBase).getQuantity();
1190 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1197 VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1198 BaseSubobject Derived) const {
1199 const CXXRecordDecl *BaseRD = Base.getBase();
1200 const CXXRecordDecl *DerivedRD = Derived.getBase();
1202 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1203 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1205 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1206 llvm_unreachable("Class must be derived from the passed in base class!");
1208 // We have to go through all the paths, and see which one leads us to the
1209 // right base subobject.
1210 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1212 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1214 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1216 if (Offset.VirtualBase) {
1217 // If we have a virtual base class, the non-virtual offset is relative
1218 // to the virtual base class offset.
1219 const ASTRecordLayout &LayoutClassLayout =
1220 Context.getASTRecordLayout(LayoutClass);
1222 /// Get the virtual base offset, relative to the most derived class
1224 OffsetToBaseSubobject +=
1225 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1227 // Otherwise, the non-virtual offset is relative to the derived class
1229 OffsetToBaseSubobject += Derived.getBaseOffset();
1232 // Check if this path gives us the right base subobject.
1233 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1234 // Since we're going from the base class _to_ the derived class, we'll
1235 // invert the non-virtual offset here.
1236 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1241 return BaseOffset();
1245 VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1246 CharUnits BaseOffsetInLayoutClass,
1247 FinalOverriders::OverriderInfo Overrider) {
1248 // Ignore adjustments for pure virtual member functions.
1249 if (Overrider.Method->isPure())
1250 return ThisAdjustment();
1252 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1253 BaseOffsetInLayoutClass);
1255 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1258 // Compute the adjustment offset.
1259 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1260 OverriderBaseSubobject);
1261 if (Offset.isEmpty())
1262 return ThisAdjustment();
1264 ThisAdjustment Adjustment;
1266 if (Offset.VirtualBase) {
1267 // Get the vcall offset map for this virtual base.
1268 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1270 if (VCallOffsets.empty()) {
1271 // We don't have vcall offsets for this virtual base, go ahead and
1273 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1274 /*FinalOverriders=*/0,
1275 BaseSubobject(Offset.VirtualBase,
1277 /*BaseIsVirtual=*/true,
1278 /*OffsetInLayoutClass=*/
1281 VCallOffsets = Builder.getVCallOffsets();
1284 Adjustment.VCallOffsetOffset =
1285 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1288 // Set the non-virtual part of the adjustment.
1289 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1295 VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1296 ReturnAdjustment ReturnAdjustment) {
1297 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1298 assert(ReturnAdjustment.isEmpty() &&
1299 "Destructor can't have return adjustment!");
1301 // FIXME: Should probably add a layer of abstraction for vtable generation.
1302 if (!isMicrosoftABI()) {
1303 // Add both the complete destructor and the deleting destructor.
1304 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1305 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1307 // Add the scalar deleting destructor.
1308 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1311 // Add the return adjustment if necessary.
1312 if (!ReturnAdjustment.isEmpty())
1313 VTableThunks[Components.size()].Return = ReturnAdjustment;
1315 // Add the function.
1316 Components.push_back(VTableComponent::MakeFunction(MD));
1320 /// OverridesIndirectMethodInBase - Return whether the given member function
1321 /// overrides any methods in the set of given bases.
1322 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1323 /// For example, if we have:
1325 /// struct A { virtual void f(); }
1326 /// struct B : A { virtual void f(); }
1327 /// struct C : B { virtual void f(); }
1329 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1330 /// and { A } as the set of bases.
1332 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1333 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1334 if (Bases.count(MD->getParent()))
1337 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1338 E = MD->end_overridden_methods(); I != E; ++I) {
1339 const CXXMethodDecl *OverriddenMD = *I;
1341 // Check "indirect overriders".
1342 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1350 VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1351 CharUnits BaseOffsetInLayoutClass,
1352 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1353 CharUnits FirstBaseOffsetInLayoutClass) const {
1354 // If the base and the first base in the primary base chain have the same
1355 // offsets, then this overrider will be used.
1356 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1359 // We know now that Base (or a direct or indirect base of it) is a primary
1360 // base in part of the class hierarchy, but not a primary base in the most
1363 // If the overrider is the first base in the primary base chain, we know
1364 // that the overrider will be used.
1365 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1368 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1370 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1371 PrimaryBases.insert(RD);
1373 // Now traverse the base chain, starting with the first base, until we find
1374 // the base that is no longer a primary base.
1376 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1377 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1382 if (Layout.isPrimaryBaseVirtual()) {
1383 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1384 "Primary base should always be at offset 0!");
1386 const ASTRecordLayout &LayoutClassLayout =
1387 Context.getASTRecordLayout(LayoutClass);
1389 // Now check if this is the primary base that is not a primary base in the
1390 // most derived class.
1391 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1392 FirstBaseOffsetInLayoutClass) {
1393 // We found it, stop walking the chain.
1397 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1398 "Primary base should always be at offset 0!");
1401 if (!PrimaryBases.insert(PrimaryBase))
1402 llvm_unreachable("Found a duplicate primary base!");
1407 // If the final overrider is an override of one of the primary bases,
1408 // then we know that it will be used.
1409 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1412 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1413 /// from the nearest base. Returns null if no method was found.
1414 static const CXXMethodDecl *
1415 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1416 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1417 OverriddenMethodsSetTy OverriddenMethods;
1418 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1420 for (int I = Bases.size(), E = 0; I != E; --I) {
1421 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1423 // Now check the overriden methods.
1424 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1425 E = OverriddenMethods.end(); I != E; ++I) {
1426 const CXXMethodDecl *OverriddenMD = *I;
1428 // We found our overridden method.
1429 if (OverriddenMD->getParent() == PrimaryBase)
1430 return OverriddenMD;
1438 VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1439 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1440 CharUnits FirstBaseOffsetInLayoutClass,
1441 PrimaryBasesSetVectorTy &PrimaryBases) {
1442 const CXXRecordDecl *RD = Base.getBase();
1443 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1445 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1446 CharUnits PrimaryBaseOffset;
1447 CharUnits PrimaryBaseOffsetInLayoutClass;
1448 if (Layout.isPrimaryBaseVirtual()) {
1449 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1450 "Primary vbase should have a zero offset!");
1452 const ASTRecordLayout &MostDerivedClassLayout =
1453 Context.getASTRecordLayout(MostDerivedClass);
1456 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1458 const ASTRecordLayout &LayoutClassLayout =
1459 Context.getASTRecordLayout(LayoutClass);
1461 PrimaryBaseOffsetInLayoutClass =
1462 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1464 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1465 "Primary base should have a zero offset!");
1467 PrimaryBaseOffset = Base.getBaseOffset();
1468 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1471 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1472 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1473 FirstBaseOffsetInLayoutClass, PrimaryBases);
1475 if (!PrimaryBases.insert(PrimaryBase))
1476 llvm_unreachable("Found a duplicate primary base!");
1479 // Now go through all virtual member functions and add them.
1480 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1481 E = RD->method_end(); I != E; ++I) {
1482 const CXXMethodDecl *MD = *I;
1484 if (!MD->isVirtual())
1487 // Get the final overrider.
1488 FinalOverriders::OverriderInfo Overrider =
1489 Overriders.getOverrider(MD, Base.getBaseOffset());
1491 // Check if this virtual member function overrides a method in a primary
1492 // base. If this is the case, and the return type doesn't require adjustment
1493 // then we can just use the member function from the primary base.
1494 if (const CXXMethodDecl *OverriddenMD =
1495 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1496 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1497 OverriddenMD).isEmpty()) {
1498 // Replace the method info of the overridden method with our own
1500 assert(MethodInfoMap.count(OverriddenMD) &&
1501 "Did not find the overridden method!");
1502 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1504 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1505 OverriddenMethodInfo.VTableIndex);
1507 assert(!MethodInfoMap.count(MD) &&
1508 "Should not have method info for this method yet!");
1510 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1511 MethodInfoMap.erase(OverriddenMD);
1513 // If the overridden method exists in a virtual base class or a direct
1514 // or indirect base class of a virtual base class, we need to emit a
1515 // thunk if we ever have a class hierarchy where the base class is not
1516 // a primary base in the complete object.
1517 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1518 // Compute the this adjustment.
1519 ThisAdjustment ThisAdjustment =
1520 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1523 if (ThisAdjustment.VCallOffsetOffset &&
1524 Overrider.Method->getParent() == MostDerivedClass) {
1526 // There's no return adjustment from OverriddenMD and MD,
1527 // but that doesn't mean there isn't one between MD and
1528 // the final overrider.
1529 BaseOffset ReturnAdjustmentOffset =
1530 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1531 ReturnAdjustment ReturnAdjustment =
1532 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1534 // This is a virtual thunk for the most derived class, add it.
1535 AddThunk(Overrider.Method,
1536 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1544 // Insert the method info for this method.
1545 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1548 assert(!MethodInfoMap.count(MD) &&
1549 "Should not have method info for this method yet!");
1550 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1552 // Check if this overrider is going to be used.
1553 const CXXMethodDecl *OverriderMD = Overrider.Method;
1554 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1555 FirstBaseInPrimaryBaseChain,
1556 FirstBaseOffsetInLayoutClass)) {
1557 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1561 // Check if this overrider needs a return adjustment.
1562 // We don't want to do this for pure virtual member functions.
1563 BaseOffset ReturnAdjustmentOffset;
1564 if (!OverriderMD->isPure()) {
1565 ReturnAdjustmentOffset =
1566 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1569 ReturnAdjustment ReturnAdjustment =
1570 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1572 AddMethod(Overrider.Method, ReturnAdjustment);
1576 void VTableBuilder::LayoutVTable() {
1577 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1579 /*BaseIsMorallyVirtual=*/false,
1580 MostDerivedClassIsVirtual,
1581 MostDerivedClassOffset);
1583 VisitedVirtualBasesSetTy VBases;
1585 // Determine the primary virtual bases.
1586 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1590 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1592 // -fapple-kext adds an extra entry at end of vtbl.
1593 bool IsAppleKext = Context.getLangOpts().AppleKext;
1595 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1599 VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1600 bool BaseIsMorallyVirtual,
1601 bool BaseIsVirtualInLayoutClass,
1602 CharUnits OffsetInLayoutClass) {
1603 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1605 // Add vcall and vbase offsets for this vtable.
1606 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1607 Base, BaseIsVirtualInLayoutClass,
1608 OffsetInLayoutClass);
1609 Components.append(Builder.components_begin(), Builder.components_end());
1611 // Check if we need to add these vcall offsets.
1612 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1613 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1615 if (VCallOffsets.empty())
1616 VCallOffsets = Builder.getVCallOffsets();
1619 // If we're laying out the most derived class we want to keep track of the
1620 // virtual base class offset offsets.
1621 if (Base.getBase() == MostDerivedClass)
1622 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1624 // FIXME: Should probably add a layer of abstraction for vtable generation.
1625 if (!isMicrosoftABI()) {
1626 // Add the offset to top.
1627 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1628 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1630 // Next, add the RTTI.
1631 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1633 // FIXME: unclear what to do with RTTI in MS ABI as emitting it anywhere
1634 // breaks the vftable layout. Just skip RTTI for now, can't mangle anyway.
1637 uint64_t AddressPoint = Components.size();
1639 // Now go through all virtual member functions and add them.
1640 PrimaryBasesSetVectorTy PrimaryBases;
1641 AddMethods(Base, OffsetInLayoutClass,
1642 Base.getBase(), OffsetInLayoutClass,
1645 // Compute 'this' pointer adjustments.
1646 ComputeThisAdjustments();
1648 // Add all address points.
1649 const CXXRecordDecl *RD = Base.getBase();
1651 AddressPoints.insert(std::make_pair(
1652 BaseSubobject(RD, OffsetInLayoutClass),
1655 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1656 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1661 if (Layout.isPrimaryBaseVirtual()) {
1662 // Check if this virtual primary base is a primary base in the layout
1663 // class. If it's not, we don't want to add it.
1664 const ASTRecordLayout &LayoutClassLayout =
1665 Context.getASTRecordLayout(LayoutClass);
1667 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1668 OffsetInLayoutClass) {
1669 // We don't want to add this class (or any of its primary bases).
1677 // Layout secondary vtables.
1678 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1681 void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1682 bool BaseIsMorallyVirtual,
1683 CharUnits OffsetInLayoutClass) {
1684 // Itanium C++ ABI 2.5.2:
1685 // Following the primary virtual table of a derived class are secondary
1686 // virtual tables for each of its proper base classes, except any primary
1687 // base(s) with which it shares its primary virtual table.
1689 const CXXRecordDecl *RD = Base.getBase();
1690 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1691 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1693 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1694 E = RD->bases_end(); I != E; ++I) {
1695 // Ignore virtual bases, we'll emit them later.
1699 const CXXRecordDecl *BaseDecl =
1700 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1702 // Ignore bases that don't have a vtable.
1703 if (!BaseDecl->isDynamicClass())
1706 if (isBuildingConstructorVTable()) {
1707 // Itanium C++ ABI 2.6.4:
1708 // Some of the base class subobjects may not need construction virtual
1709 // tables, which will therefore not be present in the construction
1710 // virtual table group, even though the subobject virtual tables are
1711 // present in the main virtual table group for the complete object.
1712 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1716 // Get the base offset of this base.
1717 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1718 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1720 CharUnits BaseOffsetInLayoutClass =
1721 OffsetInLayoutClass + RelativeBaseOffset;
1723 // Don't emit a secondary vtable for a primary base. We might however want
1724 // to emit secondary vtables for other bases of this base.
1725 if (BaseDecl == PrimaryBase) {
1726 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1727 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1731 // Layout the primary vtable (and any secondary vtables) for this base.
1732 LayoutPrimaryAndSecondaryVTables(
1733 BaseSubobject(BaseDecl, BaseOffset),
1734 BaseIsMorallyVirtual,
1735 /*BaseIsVirtualInLayoutClass=*/false,
1736 BaseOffsetInLayoutClass);
1741 VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1742 CharUnits OffsetInLayoutClass,
1743 VisitedVirtualBasesSetTy &VBases) {
1744 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1746 // Check if this base has a primary base.
1747 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1749 // Check if it's virtual.
1750 if (Layout.isPrimaryBaseVirtual()) {
1751 bool IsPrimaryVirtualBase = true;
1753 if (isBuildingConstructorVTable()) {
1754 // Check if the base is actually a primary base in the class we use for
1756 const ASTRecordLayout &LayoutClassLayout =
1757 Context.getASTRecordLayout(LayoutClass);
1759 CharUnits PrimaryBaseOffsetInLayoutClass =
1760 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1762 // We know that the base is not a primary base in the layout class if
1763 // the base offsets are different.
1764 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1765 IsPrimaryVirtualBase = false;
1768 if (IsPrimaryVirtualBase)
1769 PrimaryVirtualBases.insert(PrimaryBase);
1773 // Traverse bases, looking for more primary virtual bases.
1774 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1775 E = RD->bases_end(); I != E; ++I) {
1776 const CXXRecordDecl *BaseDecl =
1777 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1779 CharUnits BaseOffsetInLayoutClass;
1781 if (I->isVirtual()) {
1782 if (!VBases.insert(BaseDecl))
1785 const ASTRecordLayout &LayoutClassLayout =
1786 Context.getASTRecordLayout(LayoutClass);
1788 BaseOffsetInLayoutClass =
1789 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1791 BaseOffsetInLayoutClass =
1792 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1795 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1800 VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1801 VisitedVirtualBasesSetTy &VBases) {
1802 // Itanium C++ ABI 2.5.2:
1803 // Then come the virtual base virtual tables, also in inheritance graph
1804 // order, and again excluding primary bases (which share virtual tables with
1805 // the classes for which they are primary).
1806 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1807 E = RD->bases_end(); I != E; ++I) {
1808 const CXXRecordDecl *BaseDecl =
1809 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1811 // Check if this base needs a vtable. (If it's virtual, not a primary base
1812 // of some other class, and we haven't visited it before).
1813 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1814 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1815 const ASTRecordLayout &MostDerivedClassLayout =
1816 Context.getASTRecordLayout(MostDerivedClass);
1817 CharUnits BaseOffset =
1818 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1820 const ASTRecordLayout &LayoutClassLayout =
1821 Context.getASTRecordLayout(LayoutClass);
1822 CharUnits BaseOffsetInLayoutClass =
1823 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1825 LayoutPrimaryAndSecondaryVTables(
1826 BaseSubobject(BaseDecl, BaseOffset),
1827 /*BaseIsMorallyVirtual=*/true,
1828 /*BaseIsVirtualInLayoutClass=*/true,
1829 BaseOffsetInLayoutClass);
1832 // We only need to check the base for virtual base vtables if it actually
1833 // has virtual bases.
1834 if (BaseDecl->getNumVBases())
1835 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1839 /// dumpLayout - Dump the vtable layout.
1840 void VTableBuilder::dumpLayout(raw_ostream& Out) {
1842 if (isBuildingConstructorVTable()) {
1843 Out << "Construction vtable for ('";
1844 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1845 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1846 Out << LayoutClass->getQualifiedNameAsString();
1848 Out << "Vtable for '";
1849 Out << MostDerivedClass->getQualifiedNameAsString();
1851 Out << "' (" << Components.size() << " entries).\n";
1853 // Iterate through the address points and insert them into a new map where
1854 // they are keyed by the index and not the base object.
1855 // Since an address point can be shared by multiple subobjects, we use an
1857 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1858 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1859 E = AddressPoints.end(); I != E; ++I) {
1860 const BaseSubobject& Base = I->first;
1861 uint64_t Index = I->second;
1863 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1866 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1869 Out << llvm::format("%4d | ", I);
1871 const VTableComponent &Component = Components[I];
1873 // Dump the component.
1874 switch (Component.getKind()) {
1876 case VTableComponent::CK_VCallOffset:
1877 Out << "vcall_offset ("
1878 << Component.getVCallOffset().getQuantity()
1882 case VTableComponent::CK_VBaseOffset:
1883 Out << "vbase_offset ("
1884 << Component.getVBaseOffset().getQuantity()
1888 case VTableComponent::CK_OffsetToTop:
1889 Out << "offset_to_top ("
1890 << Component.getOffsetToTop().getQuantity()
1894 case VTableComponent::CK_RTTI:
1895 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1898 case VTableComponent::CK_FunctionPointer: {
1899 const CXXMethodDecl *MD = Component.getFunctionDecl();
1902 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1908 if (MD->isDeleted())
1909 Out << " [deleted]";
1911 ThunkInfo Thunk = VTableThunks.lookup(I);
1912 if (!Thunk.isEmpty()) {
1913 // If this function pointer has a return adjustment, dump it.
1914 if (!Thunk.Return.isEmpty()) {
1915 Out << "\n [return adjustment: ";
1916 Out << Thunk.Return.NonVirtual << " non-virtual";
1918 if (Thunk.Return.VBaseOffsetOffset) {
1919 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1920 Out << " vbase offset offset";
1926 // If this function pointer has a 'this' pointer adjustment, dump it.
1927 if (!Thunk.This.isEmpty()) {
1928 Out << "\n [this adjustment: ";
1929 Out << Thunk.This.NonVirtual << " non-virtual";
1931 if (Thunk.This.VCallOffsetOffset) {
1932 Out << ", " << Thunk.This.VCallOffsetOffset;
1933 Out << " vcall offset offset";
1943 case VTableComponent::CK_CompleteDtorPointer:
1944 case VTableComponent::CK_DeletingDtorPointer: {
1946 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1948 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1950 Out << DD->getQualifiedNameAsString();
1952 Out << "() [complete]";
1953 else if (isMicrosoftABI())
1954 Out << "() [scalar deleting]";
1956 Out << "() [deleting]";
1961 ThunkInfo Thunk = VTableThunks.lookup(I);
1962 if (!Thunk.isEmpty()) {
1963 // If this destructor has a 'this' pointer adjustment, dump it.
1964 if (!Thunk.This.isEmpty()) {
1965 Out << "\n [this adjustment: ";
1966 Out << Thunk.This.NonVirtual << " non-virtual";
1968 if (Thunk.This.VCallOffsetOffset) {
1969 Out << ", " << Thunk.This.VCallOffsetOffset;
1970 Out << " vcall offset offset";
1980 case VTableComponent::CK_UnusedFunctionPointer: {
1981 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1984 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1986 Out << "[unused] " << Str;
1995 // Dump the next address point.
1996 uint64_t NextIndex = Index + 1;
1997 if (AddressPointsByIndex.count(NextIndex)) {
1998 if (AddressPointsByIndex.count(NextIndex) == 1) {
1999 const BaseSubobject &Base =
2000 AddressPointsByIndex.find(NextIndex)->second;
2002 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2003 Out << ", " << Base.getBaseOffset().getQuantity();
2004 Out << ") vtable address --\n";
2006 CharUnits BaseOffset =
2007 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2009 // We store the class names in a set to get a stable order.
2010 std::set<std::string> ClassNames;
2011 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2012 AddressPointsByIndex.lower_bound(NextIndex), E =
2013 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2014 assert(I->second.getBaseOffset() == BaseOffset &&
2015 "Invalid base offset!");
2016 const CXXRecordDecl *RD = I->second.getBase();
2017 ClassNames.insert(RD->getQualifiedNameAsString());
2020 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2021 E = ClassNames.end(); I != E; ++I) {
2022 Out << " -- (" << *I;
2023 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2031 if (isBuildingConstructorVTable())
2034 if (MostDerivedClass->getNumVBases()) {
2035 // We store the virtual base class names and their offsets in a map to get
2038 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2039 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2040 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2041 std::string ClassName = I->first->getQualifiedNameAsString();
2042 CharUnits OffsetOffset = I->second;
2043 ClassNamesAndOffsets.insert(
2044 std::make_pair(ClassName, OffsetOffset));
2047 Out << "Virtual base offset offsets for '";
2048 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2049 Out << ClassNamesAndOffsets.size();
2050 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2052 for (std::map<std::string, CharUnits>::const_iterator I =
2053 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2055 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2060 if (!Thunks.empty()) {
2061 // We store the method names in a map to get a stable order.
2062 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2064 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2066 const CXXMethodDecl *MD = I->first;
2067 std::string MethodName =
2068 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2071 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2074 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2075 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2077 const std::string &MethodName = I->first;
2078 const CXXMethodDecl *MD = I->second;
2080 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2081 std::sort(ThunksVector.begin(), ThunksVector.end());
2083 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2084 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2086 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2087 const ThunkInfo &Thunk = ThunksVector[I];
2089 Out << llvm::format("%4d | ", I);
2091 // If this function pointer has a return pointer adjustment, dump it.
2092 if (!Thunk.Return.isEmpty()) {
2093 Out << "return adjustment: " << Thunk.This.NonVirtual;
2094 Out << " non-virtual";
2095 if (Thunk.Return.VBaseOffsetOffset) {
2096 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2097 Out << " vbase offset offset";
2100 if (!Thunk.This.isEmpty())
2104 // If this function pointer has a 'this' pointer adjustment, dump it.
2105 if (!Thunk.This.isEmpty()) {
2106 Out << "this adjustment: ";
2107 Out << Thunk.This.NonVirtual << " non-virtual";
2109 if (Thunk.This.VCallOffsetOffset) {
2110 Out << ", " << Thunk.This.VCallOffsetOffset;
2111 Out << " vcall offset offset";
2122 // Compute the vtable indices for all the member functions.
2123 // Store them in a map keyed by the index so we'll get a sorted table.
2124 std::map<uint64_t, std::string> IndicesMap;
2126 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2127 e = MostDerivedClass->method_end(); i != e; ++i) {
2128 const CXXMethodDecl *MD = *i;
2130 // We only want virtual member functions.
2131 if (!MD->isVirtual())
2134 std::string MethodName =
2135 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2138 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2139 // FIXME: Should add a layer of abstraction for vtable generation.
2140 if (!isMicrosoftABI()) {
2141 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))]
2142 = MethodName + " [complete]";
2143 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2144 = MethodName + " [deleting]";
2146 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2147 = MethodName + " [scalar deleting]";
2150 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2154 // Print the vtable indices for all the member functions.
2155 if (!IndicesMap.empty()) {
2156 Out << "VTable indices for '";
2157 Out << MostDerivedClass->getQualifiedNameAsString();
2158 Out << "' (" << IndicesMap.size() << " entries).\n";
2160 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2161 E = IndicesMap.end(); I != E; ++I) {
2162 uint64_t VTableIndex = I->first;
2163 const std::string &MethodName = I->second;
2165 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
2175 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2176 const VTableComponent *VTableComponents,
2177 uint64_t NumVTableThunks,
2178 const VTableThunkTy *VTableThunks,
2179 const AddressPointsMapTy &AddressPoints,
2180 bool IsMicrosoftABI)
2181 : NumVTableComponents(NumVTableComponents),
2182 VTableComponents(new VTableComponent[NumVTableComponents]),
2183 NumVTableThunks(NumVTableThunks),
2184 VTableThunks(new VTableThunkTy[NumVTableThunks]),
2185 AddressPoints(AddressPoints),
2186 IsMicrosoftABI(IsMicrosoftABI) {
2187 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2188 this->VTableComponents.get());
2189 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2190 this->VTableThunks.get());
2193 VTableLayout::~VTableLayout() { }
2195 VTableContext::VTableContext(ASTContext &Context)
2197 IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2200 VTableContext::~VTableContext() {
2201 llvm::DeleteContainerSeconds(VTableLayouts);
2205 CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2206 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2207 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2208 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2213 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2215 if (!PrimaryBases.insert(PrimaryBase))
2216 llvm_unreachable("Found a duplicate primary base!");
2219 void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2221 // Itanium C++ ABI 2.5.2:
2222 // The order of the virtual function pointers in a virtual table is the
2223 // order of declaration of the corresponding member functions in the class.
2225 // There is an entry for any virtual function declared in a class,
2226 // whether it is a new function or overrides a base class function,
2227 // unless it overrides a function from the primary base, and conversion
2228 // between their return types does not require an adjustment.
2230 int64_t CurrentIndex = 0;
2232 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2233 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2236 assert(PrimaryBase->isCompleteDefinition() &&
2237 "Should have the definition decl of the primary base!");
2239 // Since the record decl shares its vtable pointer with the primary base
2240 // we need to start counting at the end of the primary base's vtable.
2241 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2244 // Collect all the primary bases, so we can check whether methods override
2245 // a method from the base.
2246 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2247 CollectPrimaryBases(RD, Context, PrimaryBases);
2249 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2251 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2252 e = RD->method_end(); i != e; ++i) {
2253 const CXXMethodDecl *MD = *i;
2255 // We only want virtual methods.
2256 if (!MD->isVirtual())
2259 // Check if this method overrides a method in the primary base.
2260 if (const CXXMethodDecl *OverriddenMD =
2261 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2262 // Check if converting from the return type of the method to the
2263 // return type of the overridden method requires conversion.
2264 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2265 OverriddenMD).isEmpty()) {
2266 // This index is shared between the index in the vtable of the primary
2268 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2269 const CXXDestructorDecl *OverriddenDD =
2270 cast<CXXDestructorDecl>(OverriddenMD);
2272 if (!isMicrosoftABI()) {
2273 // Add both the complete and deleting entries.
2274 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2275 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2276 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2277 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2279 // Add the scalar deleting destructor.
2280 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2281 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2284 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2287 // We don't need to add an entry for this method.
2292 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2293 if (MD->isImplicit()) {
2294 assert(!ImplicitVirtualDtor &&
2295 "Did already see an implicit virtual dtor!");
2296 ImplicitVirtualDtor = DD;
2300 if (!isMicrosoftABI()) {
2301 // Add the complete dtor.
2302 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2304 // Add the deleting dtor.
2305 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2307 // Add the scalar deleting dtor.
2308 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2312 MethodVTableIndices[MD] = CurrentIndex++;
2316 if (ImplicitVirtualDtor) {
2317 // Itanium C++ ABI 2.5.2:
2318 // If a class has an implicitly-defined virtual destructor,
2319 // its entries come after the declared virtual function pointers.
2321 if (isMicrosoftABI()) {
2322 ErrorUnsupported("implicit virtual destructor in the Microsoft ABI",
2323 ImplicitVirtualDtor->getLocation());
2326 // Add the complete dtor.
2327 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2330 // Add the deleting dtor.
2331 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2335 NumVirtualFunctionPointers[RD] = CurrentIndex;
2338 uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2339 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2340 NumVirtualFunctionPointers.find(RD);
2341 if (I != NumVirtualFunctionPointers.end())
2344 ComputeMethodVTableIndices(RD);
2346 I = NumVirtualFunctionPointers.find(RD);
2347 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2351 uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2352 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2353 if (I != MethodVTableIndices.end())
2356 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2358 ComputeMethodVTableIndices(RD);
2360 I = MethodVTableIndices.find(GD);
2361 assert(I != MethodVTableIndices.end() && "Did not find index!");
2366 VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2367 const CXXRecordDecl *VBase) {
2368 ClassPairTy ClassPair(RD, VBase);
2370 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2371 VirtualBaseClassOffsetOffsets.find(ClassPair);
2372 if (I != VirtualBaseClassOffsetOffsets.end())
2375 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2376 BaseSubobject(RD, CharUnits::Zero()),
2377 /*BaseIsVirtual=*/false,
2378 /*OffsetInLayoutClass=*/CharUnits::Zero());
2380 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2381 Builder.getVBaseOffsetOffsets().begin(),
2382 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2383 // Insert all types.
2384 ClassPairTy ClassPair(RD, I->first);
2386 VirtualBaseClassOffsetOffsets.insert(
2387 std::make_pair(ClassPair, I->second));
2390 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2391 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2396 static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2397 SmallVector<VTableLayout::VTableThunkTy, 1>
2398 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2399 std::sort(VTableThunks.begin(), VTableThunks.end());
2401 return new VTableLayout(Builder.getNumVTableComponents(),
2402 Builder.vtable_component_begin(),
2403 VTableThunks.size(),
2404 VTableThunks.data(),
2405 Builder.getAddressPoints(),
2406 Builder.isMicrosoftABI());
2409 void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2410 const VTableLayout *&Entry = VTableLayouts[RD];
2412 // Check if we've computed this information before.
2416 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2417 /*MostDerivedClassIsVirtual=*/0, RD);
2418 Entry = CreateVTableLayout(Builder);
2420 // Add the known thunks.
2421 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2423 // If we don't have the vbase information for this class, insert it.
2424 // getVirtualBaseOffsetOffset will compute it separately without computing
2425 // the rest of the vtable related information.
2426 if (!RD->getNumVBases())
2429 const RecordType *VBaseRT =
2430 RD->vbases_begin()->getType()->getAs<RecordType>();
2431 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2433 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2436 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2437 Builder.getVBaseOffsetOffsets().begin(),
2438 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2439 // Insert all types.
2440 ClassPairTy ClassPair(RD, I->first);
2442 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2446 void VTableContext::ErrorUnsupported(StringRef Feature,
2447 SourceLocation Location) {
2448 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2449 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2450 "v-table layout for %0 is not supported yet");
2451 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2454 VTableLayout *VTableContext::createConstructionVTableLayout(
2455 const CXXRecordDecl *MostDerivedClass,
2456 CharUnits MostDerivedClassOffset,
2457 bool MostDerivedClassIsVirtual,
2458 const CXXRecordDecl *LayoutClass) {
2459 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2460 MostDerivedClassIsVirtual, LayoutClass);
2461 return CreateVTableLayout(Builder);