1e5dd7070Spatrick //===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code dealing with generation of the layout of virtual tables.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick
13e5dd7070Spatrick #include "clang/AST/VTableBuilder.h"
14e5dd7070Spatrick #include "clang/AST/ASTContext.h"
15e5dd7070Spatrick #include "clang/AST/ASTDiagnostic.h"
16e5dd7070Spatrick #include "clang/AST/CXXInheritance.h"
17e5dd7070Spatrick #include "clang/AST/RecordLayout.h"
18e5dd7070Spatrick #include "clang/Basic/TargetInfo.h"
19e5dd7070Spatrick #include "llvm/ADT/SetOperations.h"
20*12c85518Srobert #include "llvm/ADT/SetVector.h"
21e5dd7070Spatrick #include "llvm/ADT/SmallPtrSet.h"
22e5dd7070Spatrick #include "llvm/Support/Format.h"
23e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
24e5dd7070Spatrick #include <algorithm>
25e5dd7070Spatrick #include <cstdio>
26e5dd7070Spatrick
27e5dd7070Spatrick using namespace clang;
28e5dd7070Spatrick
29e5dd7070Spatrick #define DUMP_OVERRIDERS 0
30e5dd7070Spatrick
31e5dd7070Spatrick namespace {
32e5dd7070Spatrick
33e5dd7070Spatrick /// BaseOffset - Represents an offset from a derived class to a direct or
34e5dd7070Spatrick /// indirect base class.
35e5dd7070Spatrick struct BaseOffset {
36e5dd7070Spatrick /// DerivedClass - The derived class.
37e5dd7070Spatrick const CXXRecordDecl *DerivedClass;
38e5dd7070Spatrick
39e5dd7070Spatrick /// VirtualBase - If the path from the derived class to the base class
40e5dd7070Spatrick /// involves virtual base classes, this holds the declaration of the last
41e5dd7070Spatrick /// virtual base in this path (i.e. closest to the base class).
42e5dd7070Spatrick const CXXRecordDecl *VirtualBase;
43e5dd7070Spatrick
44e5dd7070Spatrick /// NonVirtualOffset - The offset from the derived class to the base class.
45e5dd7070Spatrick /// (Or the offset from the virtual base class to the base class, if the
46e5dd7070Spatrick /// path from the derived class to the base class involves a virtual base
47e5dd7070Spatrick /// class.
48e5dd7070Spatrick CharUnits NonVirtualOffset;
49e5dd7070Spatrick
BaseOffset__anon8b019dcd0111::BaseOffset50e5dd7070Spatrick BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
51e5dd7070Spatrick NonVirtualOffset(CharUnits::Zero()) { }
BaseOffset__anon8b019dcd0111::BaseOffset52e5dd7070Spatrick BaseOffset(const CXXRecordDecl *DerivedClass,
53e5dd7070Spatrick const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
54e5dd7070Spatrick : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
55e5dd7070Spatrick NonVirtualOffset(NonVirtualOffset) { }
56e5dd7070Spatrick
isEmpty__anon8b019dcd0111::BaseOffset57e5dd7070Spatrick bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
58e5dd7070Spatrick };
59e5dd7070Spatrick
60e5dd7070Spatrick /// FinalOverriders - Contains the final overrider member functions for all
61e5dd7070Spatrick /// member functions in the base subobjects of a class.
62e5dd7070Spatrick class FinalOverriders {
63e5dd7070Spatrick public:
64e5dd7070Spatrick /// OverriderInfo - Information about a final overrider.
65e5dd7070Spatrick struct OverriderInfo {
66e5dd7070Spatrick /// Method - The method decl of the overrider.
67e5dd7070Spatrick const CXXMethodDecl *Method;
68e5dd7070Spatrick
69e5dd7070Spatrick /// VirtualBase - The virtual base class subobject of this overrider.
70e5dd7070Spatrick /// Note that this records the closest derived virtual base class subobject.
71e5dd7070Spatrick const CXXRecordDecl *VirtualBase;
72e5dd7070Spatrick
73e5dd7070Spatrick /// Offset - the base offset of the overrider's parent in the layout class.
74e5dd7070Spatrick CharUnits Offset;
75e5dd7070Spatrick
OverriderInfo__anon8b019dcd0111::FinalOverriders::OverriderInfo76e5dd7070Spatrick OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
77e5dd7070Spatrick Offset(CharUnits::Zero()) { }
78e5dd7070Spatrick };
79e5dd7070Spatrick
80e5dd7070Spatrick private:
81e5dd7070Spatrick /// MostDerivedClass - The most derived class for which the final overriders
82e5dd7070Spatrick /// are stored.
83e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass;
84e5dd7070Spatrick
85e5dd7070Spatrick /// MostDerivedClassOffset - If we're building final overriders for a
86e5dd7070Spatrick /// construction vtable, this holds the offset from the layout class to the
87e5dd7070Spatrick /// most derived class.
88e5dd7070Spatrick const CharUnits MostDerivedClassOffset;
89e5dd7070Spatrick
90e5dd7070Spatrick /// LayoutClass - The class we're using for layout information. Will be
91e5dd7070Spatrick /// different than the most derived class if the final overriders are for a
92e5dd7070Spatrick /// construction vtable.
93e5dd7070Spatrick const CXXRecordDecl *LayoutClass;
94e5dd7070Spatrick
95e5dd7070Spatrick ASTContext &Context;
96e5dd7070Spatrick
97e5dd7070Spatrick /// MostDerivedClassLayout - the AST record layout of the most derived class.
98e5dd7070Spatrick const ASTRecordLayout &MostDerivedClassLayout;
99e5dd7070Spatrick
100e5dd7070Spatrick /// MethodBaseOffsetPairTy - Uniquely identifies a member function
101e5dd7070Spatrick /// in a base subobject.
102e5dd7070Spatrick typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
103e5dd7070Spatrick
104e5dd7070Spatrick typedef llvm::DenseMap<MethodBaseOffsetPairTy,
105e5dd7070Spatrick OverriderInfo> OverridersMapTy;
106e5dd7070Spatrick
107e5dd7070Spatrick /// OverridersMap - The final overriders for all virtual member functions of
108e5dd7070Spatrick /// all the base subobjects of the most derived class.
109e5dd7070Spatrick OverridersMapTy OverridersMap;
110e5dd7070Spatrick
111e5dd7070Spatrick /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
112e5dd7070Spatrick /// as a record decl and a subobject number) and its offsets in the most
113e5dd7070Spatrick /// derived class as well as the layout class.
114e5dd7070Spatrick typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
115e5dd7070Spatrick CharUnits> SubobjectOffsetMapTy;
116e5dd7070Spatrick
117e5dd7070Spatrick typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
118e5dd7070Spatrick
119e5dd7070Spatrick /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
120e5dd7070Spatrick /// given base.
121e5dd7070Spatrick void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
122e5dd7070Spatrick CharUnits OffsetInLayoutClass,
123e5dd7070Spatrick SubobjectOffsetMapTy &SubobjectOffsets,
124e5dd7070Spatrick SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
125e5dd7070Spatrick SubobjectCountMapTy &SubobjectCounts);
126e5dd7070Spatrick
127e5dd7070Spatrick typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
128e5dd7070Spatrick
129e5dd7070Spatrick /// dump - dump the final overriders for a base subobject, and all its direct
130e5dd7070Spatrick /// and indirect base subobjects.
131e5dd7070Spatrick void dump(raw_ostream &Out, BaseSubobject Base,
132e5dd7070Spatrick VisitedVirtualBasesSetTy& VisitedVirtualBases);
133e5dd7070Spatrick
134e5dd7070Spatrick public:
135e5dd7070Spatrick FinalOverriders(const CXXRecordDecl *MostDerivedClass,
136e5dd7070Spatrick CharUnits MostDerivedClassOffset,
137e5dd7070Spatrick const CXXRecordDecl *LayoutClass);
138e5dd7070Spatrick
139e5dd7070Spatrick /// getOverrider - Get the final overrider for the given method declaration in
140e5dd7070Spatrick /// the subobject with the given base offset.
getOverrider(const CXXMethodDecl * MD,CharUnits BaseOffset) const141e5dd7070Spatrick OverriderInfo getOverrider(const CXXMethodDecl *MD,
142e5dd7070Spatrick CharUnits BaseOffset) const {
143e5dd7070Spatrick assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
144e5dd7070Spatrick "Did not find overrider!");
145e5dd7070Spatrick
146e5dd7070Spatrick return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
147e5dd7070Spatrick }
148e5dd7070Spatrick
149e5dd7070Spatrick /// dump - dump the final overriders.
dump()150e5dd7070Spatrick void dump() {
151e5dd7070Spatrick VisitedVirtualBasesSetTy VisitedVirtualBases;
152e5dd7070Spatrick dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
153e5dd7070Spatrick VisitedVirtualBases);
154e5dd7070Spatrick }
155e5dd7070Spatrick
156e5dd7070Spatrick };
157e5dd7070Spatrick
FinalOverriders(const CXXRecordDecl * MostDerivedClass,CharUnits MostDerivedClassOffset,const CXXRecordDecl * LayoutClass)158e5dd7070Spatrick FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
159e5dd7070Spatrick CharUnits MostDerivedClassOffset,
160e5dd7070Spatrick const CXXRecordDecl *LayoutClass)
161e5dd7070Spatrick : MostDerivedClass(MostDerivedClass),
162e5dd7070Spatrick MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
163e5dd7070Spatrick Context(MostDerivedClass->getASTContext()),
164e5dd7070Spatrick MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
165e5dd7070Spatrick
166e5dd7070Spatrick // Compute base offsets.
167e5dd7070Spatrick SubobjectOffsetMapTy SubobjectOffsets;
168e5dd7070Spatrick SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
169e5dd7070Spatrick SubobjectCountMapTy SubobjectCounts;
170e5dd7070Spatrick ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
171e5dd7070Spatrick /*IsVirtual=*/false,
172e5dd7070Spatrick MostDerivedClassOffset,
173e5dd7070Spatrick SubobjectOffsets, SubobjectLayoutClassOffsets,
174e5dd7070Spatrick SubobjectCounts);
175e5dd7070Spatrick
176e5dd7070Spatrick // Get the final overriders.
177e5dd7070Spatrick CXXFinalOverriderMap FinalOverriders;
178e5dd7070Spatrick MostDerivedClass->getFinalOverriders(FinalOverriders);
179e5dd7070Spatrick
180e5dd7070Spatrick for (const auto &Overrider : FinalOverriders) {
181e5dd7070Spatrick const CXXMethodDecl *MD = Overrider.first;
182e5dd7070Spatrick const OverridingMethods &Methods = Overrider.second;
183e5dd7070Spatrick
184e5dd7070Spatrick for (const auto &M : Methods) {
185e5dd7070Spatrick unsigned SubobjectNumber = M.first;
186e5dd7070Spatrick assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
187e5dd7070Spatrick SubobjectNumber)) &&
188e5dd7070Spatrick "Did not find subobject offset!");
189e5dd7070Spatrick
190e5dd7070Spatrick CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
191e5dd7070Spatrick SubobjectNumber)];
192e5dd7070Spatrick
193e5dd7070Spatrick assert(M.second.size() == 1 && "Final overrider is not unique!");
194e5dd7070Spatrick const UniqueVirtualMethod &Method = M.second.front();
195e5dd7070Spatrick
196e5dd7070Spatrick const CXXRecordDecl *OverriderRD = Method.Method->getParent();
197e5dd7070Spatrick assert(SubobjectLayoutClassOffsets.count(
198e5dd7070Spatrick std::make_pair(OverriderRD, Method.Subobject))
199e5dd7070Spatrick && "Did not find subobject offset!");
200e5dd7070Spatrick CharUnits OverriderOffset =
201e5dd7070Spatrick SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
202e5dd7070Spatrick Method.Subobject)];
203e5dd7070Spatrick
204e5dd7070Spatrick OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
205e5dd7070Spatrick assert(!Overrider.Method && "Overrider should not exist yet!");
206e5dd7070Spatrick
207e5dd7070Spatrick Overrider.Offset = OverriderOffset;
208e5dd7070Spatrick Overrider.Method = Method.Method;
209e5dd7070Spatrick Overrider.VirtualBase = Method.InVirtualSubobject;
210e5dd7070Spatrick }
211e5dd7070Spatrick }
212e5dd7070Spatrick
213e5dd7070Spatrick #if DUMP_OVERRIDERS
214e5dd7070Spatrick // And dump them (for now).
215e5dd7070Spatrick dump();
216e5dd7070Spatrick #endif
217e5dd7070Spatrick }
218e5dd7070Spatrick
ComputeBaseOffset(const ASTContext & Context,const CXXRecordDecl * DerivedRD,const CXXBasePath & Path)219e5dd7070Spatrick static BaseOffset ComputeBaseOffset(const ASTContext &Context,
220e5dd7070Spatrick const CXXRecordDecl *DerivedRD,
221e5dd7070Spatrick const CXXBasePath &Path) {
222e5dd7070Spatrick CharUnits NonVirtualOffset = CharUnits::Zero();
223e5dd7070Spatrick
224e5dd7070Spatrick unsigned NonVirtualStart = 0;
225e5dd7070Spatrick const CXXRecordDecl *VirtualBase = nullptr;
226e5dd7070Spatrick
227e5dd7070Spatrick // First, look for the virtual base class.
228e5dd7070Spatrick for (int I = Path.size(), E = 0; I != E; --I) {
229e5dd7070Spatrick const CXXBasePathElement &Element = Path[I - 1];
230e5dd7070Spatrick
231e5dd7070Spatrick if (Element.Base->isVirtual()) {
232e5dd7070Spatrick NonVirtualStart = I;
233e5dd7070Spatrick QualType VBaseType = Element.Base->getType();
234e5dd7070Spatrick VirtualBase = VBaseType->getAsCXXRecordDecl();
235e5dd7070Spatrick break;
236e5dd7070Spatrick }
237e5dd7070Spatrick }
238e5dd7070Spatrick
239e5dd7070Spatrick // Now compute the non-virtual offset.
240e5dd7070Spatrick for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
241e5dd7070Spatrick const CXXBasePathElement &Element = Path[I];
242e5dd7070Spatrick
243e5dd7070Spatrick // Check the base class offset.
244e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
245e5dd7070Spatrick
246e5dd7070Spatrick const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
247e5dd7070Spatrick
248e5dd7070Spatrick NonVirtualOffset += Layout.getBaseClassOffset(Base);
249e5dd7070Spatrick }
250e5dd7070Spatrick
251e5dd7070Spatrick // FIXME: This should probably use CharUnits or something. Maybe we should
252e5dd7070Spatrick // even change the base offsets in ASTRecordLayout to be specified in
253e5dd7070Spatrick // CharUnits.
254e5dd7070Spatrick return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
255e5dd7070Spatrick
256e5dd7070Spatrick }
257e5dd7070Spatrick
ComputeBaseOffset(const ASTContext & Context,const CXXRecordDecl * BaseRD,const CXXRecordDecl * DerivedRD)258e5dd7070Spatrick static BaseOffset ComputeBaseOffset(const ASTContext &Context,
259e5dd7070Spatrick const CXXRecordDecl *BaseRD,
260e5dd7070Spatrick const CXXRecordDecl *DerivedRD) {
261e5dd7070Spatrick CXXBasePaths Paths(/*FindAmbiguities=*/false,
262e5dd7070Spatrick /*RecordPaths=*/true, /*DetectVirtual=*/false);
263e5dd7070Spatrick
264e5dd7070Spatrick if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
265e5dd7070Spatrick llvm_unreachable("Class must be derived from the passed in base class!");
266e5dd7070Spatrick
267e5dd7070Spatrick return ComputeBaseOffset(Context, DerivedRD, Paths.front());
268e5dd7070Spatrick }
269e5dd7070Spatrick
270e5dd7070Spatrick static BaseOffset
ComputeReturnAdjustmentBaseOffset(ASTContext & Context,const CXXMethodDecl * DerivedMD,const CXXMethodDecl * BaseMD)271e5dd7070Spatrick ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
272e5dd7070Spatrick const CXXMethodDecl *DerivedMD,
273e5dd7070Spatrick const CXXMethodDecl *BaseMD) {
274e5dd7070Spatrick const auto *BaseFT = BaseMD->getType()->castAs<FunctionType>();
275e5dd7070Spatrick const auto *DerivedFT = DerivedMD->getType()->castAs<FunctionType>();
276e5dd7070Spatrick
277e5dd7070Spatrick // Canonicalize the return types.
278e5dd7070Spatrick CanQualType CanDerivedReturnType =
279e5dd7070Spatrick Context.getCanonicalType(DerivedFT->getReturnType());
280e5dd7070Spatrick CanQualType CanBaseReturnType =
281e5dd7070Spatrick Context.getCanonicalType(BaseFT->getReturnType());
282e5dd7070Spatrick
283e5dd7070Spatrick assert(CanDerivedReturnType->getTypeClass() ==
284e5dd7070Spatrick CanBaseReturnType->getTypeClass() &&
285e5dd7070Spatrick "Types must have same type class!");
286e5dd7070Spatrick
287e5dd7070Spatrick if (CanDerivedReturnType == CanBaseReturnType) {
288e5dd7070Spatrick // No adjustment needed.
289e5dd7070Spatrick return BaseOffset();
290e5dd7070Spatrick }
291e5dd7070Spatrick
292e5dd7070Spatrick if (isa<ReferenceType>(CanDerivedReturnType)) {
293e5dd7070Spatrick CanDerivedReturnType =
294e5dd7070Spatrick CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
295e5dd7070Spatrick CanBaseReturnType =
296e5dd7070Spatrick CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
297e5dd7070Spatrick } else if (isa<PointerType>(CanDerivedReturnType)) {
298e5dd7070Spatrick CanDerivedReturnType =
299e5dd7070Spatrick CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
300e5dd7070Spatrick CanBaseReturnType =
301e5dd7070Spatrick CanBaseReturnType->getAs<PointerType>()->getPointeeType();
302e5dd7070Spatrick } else {
303e5dd7070Spatrick llvm_unreachable("Unexpected return type!");
304e5dd7070Spatrick }
305e5dd7070Spatrick
306e5dd7070Spatrick // We need to compare unqualified types here; consider
307e5dd7070Spatrick // const T *Base::foo();
308e5dd7070Spatrick // T *Derived::foo();
309e5dd7070Spatrick if (CanDerivedReturnType.getUnqualifiedType() ==
310e5dd7070Spatrick CanBaseReturnType.getUnqualifiedType()) {
311e5dd7070Spatrick // No adjustment needed.
312e5dd7070Spatrick return BaseOffset();
313e5dd7070Spatrick }
314e5dd7070Spatrick
315e5dd7070Spatrick const CXXRecordDecl *DerivedRD =
316e5dd7070Spatrick cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
317e5dd7070Spatrick
318e5dd7070Spatrick const CXXRecordDecl *BaseRD =
319e5dd7070Spatrick cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
320e5dd7070Spatrick
321e5dd7070Spatrick return ComputeBaseOffset(Context, BaseRD, DerivedRD);
322e5dd7070Spatrick }
323e5dd7070Spatrick
324e5dd7070Spatrick void
ComputeBaseOffsets(BaseSubobject Base,bool IsVirtual,CharUnits OffsetInLayoutClass,SubobjectOffsetMapTy & SubobjectOffsets,SubobjectOffsetMapTy & SubobjectLayoutClassOffsets,SubobjectCountMapTy & SubobjectCounts)325e5dd7070Spatrick FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
326e5dd7070Spatrick CharUnits OffsetInLayoutClass,
327e5dd7070Spatrick SubobjectOffsetMapTy &SubobjectOffsets,
328e5dd7070Spatrick SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
329e5dd7070Spatrick SubobjectCountMapTy &SubobjectCounts) {
330e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
331e5dd7070Spatrick
332e5dd7070Spatrick unsigned SubobjectNumber = 0;
333e5dd7070Spatrick if (!IsVirtual)
334e5dd7070Spatrick SubobjectNumber = ++SubobjectCounts[RD];
335e5dd7070Spatrick
336e5dd7070Spatrick // Set up the subobject to offset mapping.
337e5dd7070Spatrick assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
338e5dd7070Spatrick && "Subobject offset already exists!");
339e5dd7070Spatrick assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
340e5dd7070Spatrick && "Subobject offset already exists!");
341e5dd7070Spatrick
342e5dd7070Spatrick SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
343e5dd7070Spatrick SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
344e5dd7070Spatrick OffsetInLayoutClass;
345e5dd7070Spatrick
346e5dd7070Spatrick // Traverse our bases.
347e5dd7070Spatrick for (const auto &B : RD->bases()) {
348e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
349e5dd7070Spatrick
350e5dd7070Spatrick CharUnits BaseOffset;
351e5dd7070Spatrick CharUnits BaseOffsetInLayoutClass;
352e5dd7070Spatrick if (B.isVirtual()) {
353e5dd7070Spatrick // Check if we've visited this virtual base before.
354e5dd7070Spatrick if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
355e5dd7070Spatrick continue;
356e5dd7070Spatrick
357e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
358e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
359e5dd7070Spatrick
360e5dd7070Spatrick BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
361e5dd7070Spatrick BaseOffsetInLayoutClass =
362e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(BaseDecl);
363e5dd7070Spatrick } else {
364e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
365e5dd7070Spatrick CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
366e5dd7070Spatrick
367e5dd7070Spatrick BaseOffset = Base.getBaseOffset() + Offset;
368e5dd7070Spatrick BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
369e5dd7070Spatrick }
370e5dd7070Spatrick
371e5dd7070Spatrick ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
372e5dd7070Spatrick B.isVirtual(), BaseOffsetInLayoutClass,
373e5dd7070Spatrick SubobjectOffsets, SubobjectLayoutClassOffsets,
374e5dd7070Spatrick SubobjectCounts);
375e5dd7070Spatrick }
376e5dd7070Spatrick }
377e5dd7070Spatrick
dump(raw_ostream & Out,BaseSubobject Base,VisitedVirtualBasesSetTy & VisitedVirtualBases)378e5dd7070Spatrick void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
379e5dd7070Spatrick VisitedVirtualBasesSetTy &VisitedVirtualBases) {
380e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
381e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
382e5dd7070Spatrick
383e5dd7070Spatrick for (const auto &B : RD->bases()) {
384e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
385e5dd7070Spatrick
386e5dd7070Spatrick // Ignore bases that don't have any virtual member functions.
387e5dd7070Spatrick if (!BaseDecl->isPolymorphic())
388e5dd7070Spatrick continue;
389e5dd7070Spatrick
390e5dd7070Spatrick CharUnits BaseOffset;
391e5dd7070Spatrick if (B.isVirtual()) {
392e5dd7070Spatrick if (!VisitedVirtualBases.insert(BaseDecl).second) {
393e5dd7070Spatrick // We've visited this base before.
394e5dd7070Spatrick continue;
395e5dd7070Spatrick }
396e5dd7070Spatrick
397e5dd7070Spatrick BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
398e5dd7070Spatrick } else {
399e5dd7070Spatrick BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
400e5dd7070Spatrick }
401e5dd7070Spatrick
402e5dd7070Spatrick dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
403e5dd7070Spatrick }
404e5dd7070Spatrick
405e5dd7070Spatrick Out << "Final overriders for (";
406e5dd7070Spatrick RD->printQualifiedName(Out);
407e5dd7070Spatrick Out << ", ";
408e5dd7070Spatrick Out << Base.getBaseOffset().getQuantity() << ")\n";
409e5dd7070Spatrick
410e5dd7070Spatrick // Now dump the overriders for this base subobject.
411e5dd7070Spatrick for (const auto *MD : RD->methods()) {
412ec727ea7Spatrick if (!VTableContextBase::hasVtableSlot(MD))
413e5dd7070Spatrick continue;
414e5dd7070Spatrick MD = MD->getCanonicalDecl();
415e5dd7070Spatrick
416e5dd7070Spatrick OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
417e5dd7070Spatrick
418e5dd7070Spatrick Out << " ";
419e5dd7070Spatrick MD->printQualifiedName(Out);
420e5dd7070Spatrick Out << " - (";
421e5dd7070Spatrick Overrider.Method->printQualifiedName(Out);
422e5dd7070Spatrick Out << ", " << Overrider.Offset.getQuantity() << ')';
423e5dd7070Spatrick
424e5dd7070Spatrick BaseOffset Offset;
425e5dd7070Spatrick if (!Overrider.Method->isPure())
426e5dd7070Spatrick Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
427e5dd7070Spatrick
428e5dd7070Spatrick if (!Offset.isEmpty()) {
429e5dd7070Spatrick Out << " [ret-adj: ";
430e5dd7070Spatrick if (Offset.VirtualBase) {
431e5dd7070Spatrick Offset.VirtualBase->printQualifiedName(Out);
432e5dd7070Spatrick Out << " vbase, ";
433e5dd7070Spatrick }
434e5dd7070Spatrick
435e5dd7070Spatrick Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
436e5dd7070Spatrick }
437e5dd7070Spatrick
438e5dd7070Spatrick Out << "\n";
439e5dd7070Spatrick }
440e5dd7070Spatrick }
441e5dd7070Spatrick
442e5dd7070Spatrick /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
443e5dd7070Spatrick struct VCallOffsetMap {
444e5dd7070Spatrick
445e5dd7070Spatrick typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
446e5dd7070Spatrick
447e5dd7070Spatrick /// Offsets - Keeps track of methods and their offsets.
448e5dd7070Spatrick // FIXME: This should be a real map and not a vector.
449e5dd7070Spatrick SmallVector<MethodAndOffsetPairTy, 16> Offsets;
450e5dd7070Spatrick
451e5dd7070Spatrick /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
452e5dd7070Spatrick /// can share the same vcall offset.
453e5dd7070Spatrick static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
454e5dd7070Spatrick const CXXMethodDecl *RHS);
455e5dd7070Spatrick
456e5dd7070Spatrick public:
457e5dd7070Spatrick /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
458e5dd7070Spatrick /// add was successful, or false if there was already a member function with
459e5dd7070Spatrick /// the same signature in the map.
460e5dd7070Spatrick bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
461e5dd7070Spatrick
462e5dd7070Spatrick /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
463e5dd7070Spatrick /// vtable address point) for the given virtual member function.
464e5dd7070Spatrick CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
465e5dd7070Spatrick
466e5dd7070Spatrick // empty - Return whether the offset map is empty or not.
empty__anon8b019dcd0111::VCallOffsetMap467e5dd7070Spatrick bool empty() const { return Offsets.empty(); }
468e5dd7070Spatrick };
469e5dd7070Spatrick
HasSameVirtualSignature(const CXXMethodDecl * LHS,const CXXMethodDecl * RHS)470e5dd7070Spatrick static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
471e5dd7070Spatrick const CXXMethodDecl *RHS) {
472e5dd7070Spatrick const FunctionProtoType *LT =
473e5dd7070Spatrick cast<FunctionProtoType>(LHS->getType().getCanonicalType());
474e5dd7070Spatrick const FunctionProtoType *RT =
475e5dd7070Spatrick cast<FunctionProtoType>(RHS->getType().getCanonicalType());
476e5dd7070Spatrick
477e5dd7070Spatrick // Fast-path matches in the canonical types.
478e5dd7070Spatrick if (LT == RT) return true;
479e5dd7070Spatrick
480e5dd7070Spatrick // Force the signatures to match. We can't rely on the overrides
481e5dd7070Spatrick // list here because there isn't necessarily an inheritance
482e5dd7070Spatrick // relationship between the two methods.
483e5dd7070Spatrick if (LT->getMethodQuals() != RT->getMethodQuals())
484e5dd7070Spatrick return false;
485e5dd7070Spatrick return LT->getParamTypes() == RT->getParamTypes();
486e5dd7070Spatrick }
487e5dd7070Spatrick
MethodsCanShareVCallOffset(const CXXMethodDecl * LHS,const CXXMethodDecl * RHS)488e5dd7070Spatrick bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
489e5dd7070Spatrick const CXXMethodDecl *RHS) {
490ec727ea7Spatrick assert(VTableContextBase::hasVtableSlot(LHS) && "LHS must be virtual!");
491a9ac8606Spatrick assert(VTableContextBase::hasVtableSlot(RHS) && "RHS must be virtual!");
492e5dd7070Spatrick
493e5dd7070Spatrick // A destructor can share a vcall offset with another destructor.
494e5dd7070Spatrick if (isa<CXXDestructorDecl>(LHS))
495e5dd7070Spatrick return isa<CXXDestructorDecl>(RHS);
496e5dd7070Spatrick
497e5dd7070Spatrick // FIXME: We need to check more things here.
498e5dd7070Spatrick
499e5dd7070Spatrick // The methods must have the same name.
500e5dd7070Spatrick DeclarationName LHSName = LHS->getDeclName();
501e5dd7070Spatrick DeclarationName RHSName = RHS->getDeclName();
502e5dd7070Spatrick if (LHSName != RHSName)
503e5dd7070Spatrick return false;
504e5dd7070Spatrick
505e5dd7070Spatrick // And the same signatures.
506e5dd7070Spatrick return HasSameVirtualSignature(LHS, RHS);
507e5dd7070Spatrick }
508e5dd7070Spatrick
AddVCallOffset(const CXXMethodDecl * MD,CharUnits OffsetOffset)509e5dd7070Spatrick bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
510e5dd7070Spatrick CharUnits OffsetOffset) {
511e5dd7070Spatrick // Check if we can reuse an offset.
512e5dd7070Spatrick for (const auto &OffsetPair : Offsets) {
513e5dd7070Spatrick if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
514e5dd7070Spatrick return false;
515e5dd7070Spatrick }
516e5dd7070Spatrick
517e5dd7070Spatrick // Add the offset.
518e5dd7070Spatrick Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
519e5dd7070Spatrick return true;
520e5dd7070Spatrick }
521e5dd7070Spatrick
getVCallOffsetOffset(const CXXMethodDecl * MD)522e5dd7070Spatrick CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
523e5dd7070Spatrick // Look for an offset.
524e5dd7070Spatrick for (const auto &OffsetPair : Offsets) {
525e5dd7070Spatrick if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
526e5dd7070Spatrick return OffsetPair.second;
527e5dd7070Spatrick }
528e5dd7070Spatrick
529e5dd7070Spatrick llvm_unreachable("Should always find a vcall offset offset!");
530e5dd7070Spatrick }
531e5dd7070Spatrick
532e5dd7070Spatrick /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
533e5dd7070Spatrick class VCallAndVBaseOffsetBuilder {
534e5dd7070Spatrick public:
535e5dd7070Spatrick typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
536e5dd7070Spatrick VBaseOffsetOffsetsMapTy;
537e5dd7070Spatrick
538e5dd7070Spatrick private:
539ec727ea7Spatrick const ItaniumVTableContext &VTables;
540ec727ea7Spatrick
541e5dd7070Spatrick /// MostDerivedClass - The most derived class for which we're building vcall
542e5dd7070Spatrick /// and vbase offsets.
543e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass;
544e5dd7070Spatrick
545e5dd7070Spatrick /// LayoutClass - The class we're using for layout information. Will be
546e5dd7070Spatrick /// different than the most derived class if we're building a construction
547e5dd7070Spatrick /// vtable.
548e5dd7070Spatrick const CXXRecordDecl *LayoutClass;
549e5dd7070Spatrick
550e5dd7070Spatrick /// Context - The ASTContext which we will use for layout information.
551e5dd7070Spatrick ASTContext &Context;
552e5dd7070Spatrick
553e5dd7070Spatrick /// Components - vcall and vbase offset components
554e5dd7070Spatrick typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
555e5dd7070Spatrick VTableComponentVectorTy Components;
556e5dd7070Spatrick
557e5dd7070Spatrick /// VisitedVirtualBases - Visited virtual bases.
558e5dd7070Spatrick llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
559e5dd7070Spatrick
560e5dd7070Spatrick /// VCallOffsets - Keeps track of vcall offsets.
561e5dd7070Spatrick VCallOffsetMap VCallOffsets;
562e5dd7070Spatrick
563e5dd7070Spatrick
564e5dd7070Spatrick /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
565e5dd7070Spatrick /// relative to the address point.
566e5dd7070Spatrick VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
567e5dd7070Spatrick
568e5dd7070Spatrick /// FinalOverriders - The final overriders of the most derived class.
569e5dd7070Spatrick /// (Can be null when we're not building a vtable of the most derived class).
570e5dd7070Spatrick const FinalOverriders *Overriders;
571e5dd7070Spatrick
572e5dd7070Spatrick /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
573e5dd7070Spatrick /// given base subobject.
574e5dd7070Spatrick void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
575e5dd7070Spatrick CharUnits RealBaseOffset);
576e5dd7070Spatrick
577e5dd7070Spatrick /// AddVCallOffsets - Add vcall offsets for the given base subobject.
578e5dd7070Spatrick void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
579e5dd7070Spatrick
580e5dd7070Spatrick /// AddVBaseOffsets - Add vbase offsets for the given class.
581e5dd7070Spatrick void AddVBaseOffsets(const CXXRecordDecl *Base,
582e5dd7070Spatrick CharUnits OffsetInLayoutClass);
583e5dd7070Spatrick
584e5dd7070Spatrick /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
585e5dd7070Spatrick /// chars, relative to the vtable address point.
586e5dd7070Spatrick CharUnits getCurrentOffsetOffset() const;
587e5dd7070Spatrick
588e5dd7070Spatrick public:
VCallAndVBaseOffsetBuilder(const ItaniumVTableContext & VTables,const CXXRecordDecl * MostDerivedClass,const CXXRecordDecl * LayoutClass,const FinalOverriders * Overriders,BaseSubobject Base,bool BaseIsVirtual,CharUnits OffsetInLayoutClass)589ec727ea7Spatrick VCallAndVBaseOffsetBuilder(const ItaniumVTableContext &VTables,
590ec727ea7Spatrick const CXXRecordDecl *MostDerivedClass,
591e5dd7070Spatrick const CXXRecordDecl *LayoutClass,
592e5dd7070Spatrick const FinalOverriders *Overriders,
593e5dd7070Spatrick BaseSubobject Base, bool BaseIsVirtual,
594e5dd7070Spatrick CharUnits OffsetInLayoutClass)
595ec727ea7Spatrick : VTables(VTables), MostDerivedClass(MostDerivedClass),
596ec727ea7Spatrick LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
597ec727ea7Spatrick Overriders(Overriders) {
598e5dd7070Spatrick
599e5dd7070Spatrick // Add vcall and vbase offsets.
600e5dd7070Spatrick AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
601e5dd7070Spatrick }
602e5dd7070Spatrick
603e5dd7070Spatrick /// Methods for iterating over the components.
604e5dd7070Spatrick typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
components_begin() const605e5dd7070Spatrick const_iterator components_begin() const { return Components.rbegin(); }
components_end() const606e5dd7070Spatrick const_iterator components_end() const { return Components.rend(); }
607e5dd7070Spatrick
getVCallOffsets() const608e5dd7070Spatrick const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
getVBaseOffsetOffsets() const609e5dd7070Spatrick const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
610e5dd7070Spatrick return VBaseOffsetOffsets;
611e5dd7070Spatrick }
612e5dd7070Spatrick };
613e5dd7070Spatrick
614e5dd7070Spatrick void
AddVCallAndVBaseOffsets(BaseSubobject Base,bool BaseIsVirtual,CharUnits RealBaseOffset)615e5dd7070Spatrick VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
616e5dd7070Spatrick bool BaseIsVirtual,
617e5dd7070Spatrick CharUnits RealBaseOffset) {
618e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
619e5dd7070Spatrick
620e5dd7070Spatrick // Itanium C++ ABI 2.5.2:
621e5dd7070Spatrick // ..in classes sharing a virtual table with a primary base class, the vcall
622e5dd7070Spatrick // and vbase offsets added by the derived class all come before the vcall
623e5dd7070Spatrick // and vbase offsets required by the base class, so that the latter may be
624e5dd7070Spatrick // laid out as required by the base class without regard to additions from
625e5dd7070Spatrick // the derived class(es).
626e5dd7070Spatrick
627e5dd7070Spatrick // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
628e5dd7070Spatrick // emit them for the primary base first).
629e5dd7070Spatrick if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
630e5dd7070Spatrick bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
631e5dd7070Spatrick
632e5dd7070Spatrick CharUnits PrimaryBaseOffset;
633e5dd7070Spatrick
634e5dd7070Spatrick // Get the base offset of the primary base.
635e5dd7070Spatrick if (PrimaryBaseIsVirtual) {
636e5dd7070Spatrick assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
637e5dd7070Spatrick "Primary vbase should have a zero offset!");
638e5dd7070Spatrick
639e5dd7070Spatrick const ASTRecordLayout &MostDerivedClassLayout =
640e5dd7070Spatrick Context.getASTRecordLayout(MostDerivedClass);
641e5dd7070Spatrick
642e5dd7070Spatrick PrimaryBaseOffset =
643e5dd7070Spatrick MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
644e5dd7070Spatrick } else {
645e5dd7070Spatrick assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
646e5dd7070Spatrick "Primary base should have a zero offset!");
647e5dd7070Spatrick
648e5dd7070Spatrick PrimaryBaseOffset = Base.getBaseOffset();
649e5dd7070Spatrick }
650e5dd7070Spatrick
651e5dd7070Spatrick AddVCallAndVBaseOffsets(
652e5dd7070Spatrick BaseSubobject(PrimaryBase,PrimaryBaseOffset),
653e5dd7070Spatrick PrimaryBaseIsVirtual, RealBaseOffset);
654e5dd7070Spatrick }
655e5dd7070Spatrick
656e5dd7070Spatrick AddVBaseOffsets(Base.getBase(), RealBaseOffset);
657e5dd7070Spatrick
658e5dd7070Spatrick // We only want to add vcall offsets for virtual bases.
659e5dd7070Spatrick if (BaseIsVirtual)
660e5dd7070Spatrick AddVCallOffsets(Base, RealBaseOffset);
661e5dd7070Spatrick }
662e5dd7070Spatrick
getCurrentOffsetOffset() const663e5dd7070Spatrick CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
664e5dd7070Spatrick // OffsetIndex is the index of this vcall or vbase offset, relative to the
665e5dd7070Spatrick // vtable address point. (We subtract 3 to account for the information just
666e5dd7070Spatrick // above the address point, the RTTI info, the offset to top, and the
667e5dd7070Spatrick // vcall offset itself).
668e5dd7070Spatrick int64_t OffsetIndex = -(int64_t)(3 + Components.size());
669e5dd7070Spatrick
670ec727ea7Spatrick // Under the relative ABI, the offset widths are 32-bit ints instead of
671ec727ea7Spatrick // pointer widths.
672ec727ea7Spatrick CharUnits OffsetWidth = Context.toCharUnitsFromBits(
673*12c85518Srobert VTables.isRelativeLayout()
674*12c85518Srobert ? 32
675*12c85518Srobert : Context.getTargetInfo().getPointerWidth(LangAS::Default));
676ec727ea7Spatrick CharUnits OffsetOffset = OffsetWidth * OffsetIndex;
677ec727ea7Spatrick
678e5dd7070Spatrick return OffsetOffset;
679e5dd7070Spatrick }
680e5dd7070Spatrick
AddVCallOffsets(BaseSubobject Base,CharUnits VBaseOffset)681e5dd7070Spatrick void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
682e5dd7070Spatrick CharUnits VBaseOffset) {
683e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
684e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
685e5dd7070Spatrick
686e5dd7070Spatrick const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
687e5dd7070Spatrick
688e5dd7070Spatrick // Handle the primary base first.
689e5dd7070Spatrick // We only want to add vcall offsets if the base is non-virtual; a virtual
690e5dd7070Spatrick // primary base will have its vcall and vbase offsets emitted already.
691e5dd7070Spatrick if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
692e5dd7070Spatrick // Get the base offset of the primary base.
693e5dd7070Spatrick assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
694e5dd7070Spatrick "Primary base should have a zero offset!");
695e5dd7070Spatrick
696e5dd7070Spatrick AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
697e5dd7070Spatrick VBaseOffset);
698e5dd7070Spatrick }
699e5dd7070Spatrick
700e5dd7070Spatrick // Add the vcall offsets.
701e5dd7070Spatrick for (const auto *MD : RD->methods()) {
702ec727ea7Spatrick if (!VTableContextBase::hasVtableSlot(MD))
703e5dd7070Spatrick continue;
704e5dd7070Spatrick MD = MD->getCanonicalDecl();
705e5dd7070Spatrick
706e5dd7070Spatrick CharUnits OffsetOffset = getCurrentOffsetOffset();
707e5dd7070Spatrick
708e5dd7070Spatrick // Don't add a vcall offset if we already have one for this member function
709e5dd7070Spatrick // signature.
710e5dd7070Spatrick if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
711e5dd7070Spatrick continue;
712e5dd7070Spatrick
713e5dd7070Spatrick CharUnits Offset = CharUnits::Zero();
714e5dd7070Spatrick
715e5dd7070Spatrick if (Overriders) {
716e5dd7070Spatrick // Get the final overrider.
717e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider =
718e5dd7070Spatrick Overriders->getOverrider(MD, Base.getBaseOffset());
719e5dd7070Spatrick
720e5dd7070Spatrick /// The vcall offset is the offset from the virtual base to the object
721e5dd7070Spatrick /// where the function was overridden.
722e5dd7070Spatrick Offset = Overrider.Offset - VBaseOffset;
723e5dd7070Spatrick }
724e5dd7070Spatrick
725e5dd7070Spatrick Components.push_back(
726e5dd7070Spatrick VTableComponent::MakeVCallOffset(Offset));
727e5dd7070Spatrick }
728e5dd7070Spatrick
729e5dd7070Spatrick // And iterate over all non-virtual bases (ignoring the primary base).
730e5dd7070Spatrick for (const auto &B : RD->bases()) {
731e5dd7070Spatrick if (B.isVirtual())
732e5dd7070Spatrick continue;
733e5dd7070Spatrick
734e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
735e5dd7070Spatrick if (BaseDecl == PrimaryBase)
736e5dd7070Spatrick continue;
737e5dd7070Spatrick
738e5dd7070Spatrick // Get the base offset of this base.
739e5dd7070Spatrick CharUnits BaseOffset = Base.getBaseOffset() +
740e5dd7070Spatrick Layout.getBaseClassOffset(BaseDecl);
741e5dd7070Spatrick
742e5dd7070Spatrick AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
743e5dd7070Spatrick VBaseOffset);
744e5dd7070Spatrick }
745e5dd7070Spatrick }
746e5dd7070Spatrick
747e5dd7070Spatrick void
AddVBaseOffsets(const CXXRecordDecl * RD,CharUnits OffsetInLayoutClass)748e5dd7070Spatrick VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
749e5dd7070Spatrick CharUnits OffsetInLayoutClass) {
750e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
751e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
752e5dd7070Spatrick
753e5dd7070Spatrick // Add vbase offsets.
754e5dd7070Spatrick for (const auto &B : RD->bases()) {
755e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
756e5dd7070Spatrick
757e5dd7070Spatrick // Check if this is a virtual base that we haven't visited before.
758e5dd7070Spatrick if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
759e5dd7070Spatrick CharUnits Offset =
760e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
761e5dd7070Spatrick
762e5dd7070Spatrick // Add the vbase offset offset.
763e5dd7070Spatrick assert(!VBaseOffsetOffsets.count(BaseDecl) &&
764e5dd7070Spatrick "vbase offset offset already exists!");
765e5dd7070Spatrick
766e5dd7070Spatrick CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
767e5dd7070Spatrick VBaseOffsetOffsets.insert(
768e5dd7070Spatrick std::make_pair(BaseDecl, VBaseOffsetOffset));
769e5dd7070Spatrick
770e5dd7070Spatrick Components.push_back(
771e5dd7070Spatrick VTableComponent::MakeVBaseOffset(Offset));
772e5dd7070Spatrick }
773e5dd7070Spatrick
774e5dd7070Spatrick // Check the base class looking for more vbase offsets.
775e5dd7070Spatrick AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
776e5dd7070Spatrick }
777e5dd7070Spatrick }
778e5dd7070Spatrick
779e5dd7070Spatrick /// ItaniumVTableBuilder - Class for building vtable layout information.
780e5dd7070Spatrick class ItaniumVTableBuilder {
781e5dd7070Spatrick public:
782e5dd7070Spatrick /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
783e5dd7070Spatrick /// primary bases.
784e5dd7070Spatrick typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
785e5dd7070Spatrick PrimaryBasesSetVectorTy;
786e5dd7070Spatrick
787e5dd7070Spatrick typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
788e5dd7070Spatrick VBaseOffsetOffsetsMapTy;
789e5dd7070Spatrick
790e5dd7070Spatrick typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
791e5dd7070Spatrick
792e5dd7070Spatrick typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
793e5dd7070Spatrick
794e5dd7070Spatrick private:
795e5dd7070Spatrick /// VTables - Global vtable information.
796e5dd7070Spatrick ItaniumVTableContext &VTables;
797e5dd7070Spatrick
798e5dd7070Spatrick /// MostDerivedClass - The most derived class for which we're building this
799e5dd7070Spatrick /// vtable.
800e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass;
801e5dd7070Spatrick
802e5dd7070Spatrick /// MostDerivedClassOffset - If we're building a construction vtable, this
803e5dd7070Spatrick /// holds the offset from the layout class to the most derived class.
804e5dd7070Spatrick const CharUnits MostDerivedClassOffset;
805e5dd7070Spatrick
806e5dd7070Spatrick /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
807e5dd7070Spatrick /// base. (This only makes sense when building a construction vtable).
808e5dd7070Spatrick bool MostDerivedClassIsVirtual;
809e5dd7070Spatrick
810e5dd7070Spatrick /// LayoutClass - The class we're using for layout information. Will be
811e5dd7070Spatrick /// different than the most derived class if we're building a construction
812e5dd7070Spatrick /// vtable.
813e5dd7070Spatrick const CXXRecordDecl *LayoutClass;
814e5dd7070Spatrick
815e5dd7070Spatrick /// Context - The ASTContext which we will use for layout information.
816e5dd7070Spatrick ASTContext &Context;
817e5dd7070Spatrick
818e5dd7070Spatrick /// FinalOverriders - The final overriders of the most derived class.
819e5dd7070Spatrick const FinalOverriders Overriders;
820e5dd7070Spatrick
821e5dd7070Spatrick /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
822e5dd7070Spatrick /// bases in this vtable.
823e5dd7070Spatrick llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
824e5dd7070Spatrick
825e5dd7070Spatrick /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
826e5dd7070Spatrick /// the most derived class.
827e5dd7070Spatrick VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
828e5dd7070Spatrick
829e5dd7070Spatrick /// Components - The components of the vtable being built.
830e5dd7070Spatrick SmallVector<VTableComponent, 64> Components;
831e5dd7070Spatrick
832e5dd7070Spatrick /// AddressPoints - Address points for the vtable being built.
833e5dd7070Spatrick AddressPointsMapTy AddressPoints;
834e5dd7070Spatrick
835e5dd7070Spatrick /// MethodInfo - Contains information about a method in a vtable.
836e5dd7070Spatrick /// (Used for computing 'this' pointer adjustment thunks.
837e5dd7070Spatrick struct MethodInfo {
838e5dd7070Spatrick /// BaseOffset - The base offset of this method.
839e5dd7070Spatrick const CharUnits BaseOffset;
840e5dd7070Spatrick
841e5dd7070Spatrick /// BaseOffsetInLayoutClass - The base offset in the layout class of this
842e5dd7070Spatrick /// method.
843e5dd7070Spatrick const CharUnits BaseOffsetInLayoutClass;
844e5dd7070Spatrick
845e5dd7070Spatrick /// VTableIndex - The index in the vtable that this method has.
846e5dd7070Spatrick /// (For destructors, this is the index of the complete destructor).
847e5dd7070Spatrick const uint64_t VTableIndex;
848e5dd7070Spatrick
MethodInfo__anon8b019dcd0111::ItaniumVTableBuilder::MethodInfo849e5dd7070Spatrick MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
850e5dd7070Spatrick uint64_t VTableIndex)
851e5dd7070Spatrick : BaseOffset(BaseOffset),
852e5dd7070Spatrick BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
853e5dd7070Spatrick VTableIndex(VTableIndex) { }
854e5dd7070Spatrick
MethodInfo__anon8b019dcd0111::ItaniumVTableBuilder::MethodInfo855e5dd7070Spatrick MethodInfo()
856e5dd7070Spatrick : BaseOffset(CharUnits::Zero()),
857e5dd7070Spatrick BaseOffsetInLayoutClass(CharUnits::Zero()),
858e5dd7070Spatrick VTableIndex(0) { }
859e5dd7070Spatrick
860e5dd7070Spatrick MethodInfo(MethodInfo const&) = default;
861e5dd7070Spatrick };
862e5dd7070Spatrick
863e5dd7070Spatrick typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
864e5dd7070Spatrick
865e5dd7070Spatrick /// MethodInfoMap - The information for all methods in the vtable we're
866e5dd7070Spatrick /// currently building.
867e5dd7070Spatrick MethodInfoMapTy MethodInfoMap;
868e5dd7070Spatrick
869e5dd7070Spatrick /// MethodVTableIndices - Contains the index (relative to the vtable address
870e5dd7070Spatrick /// point) where the function pointer for a virtual function is stored.
871e5dd7070Spatrick MethodVTableIndicesTy MethodVTableIndices;
872e5dd7070Spatrick
873e5dd7070Spatrick typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
874e5dd7070Spatrick
875e5dd7070Spatrick /// VTableThunks - The thunks by vtable index in the vtable currently being
876e5dd7070Spatrick /// built.
877e5dd7070Spatrick VTableThunksMapTy VTableThunks;
878e5dd7070Spatrick
879e5dd7070Spatrick typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
880e5dd7070Spatrick typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
881e5dd7070Spatrick
882e5dd7070Spatrick /// Thunks - A map that contains all the thunks needed for all methods in the
883e5dd7070Spatrick /// most derived class for which the vtable is currently being built.
884e5dd7070Spatrick ThunksMapTy Thunks;
885e5dd7070Spatrick
886e5dd7070Spatrick /// AddThunk - Add a thunk for the given method.
887e5dd7070Spatrick void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
888e5dd7070Spatrick
889e5dd7070Spatrick /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
890e5dd7070Spatrick /// part of the vtable we're currently building.
891e5dd7070Spatrick void ComputeThisAdjustments();
892e5dd7070Spatrick
893e5dd7070Spatrick typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
894e5dd7070Spatrick
895e5dd7070Spatrick /// PrimaryVirtualBases - All known virtual bases who are a primary base of
896e5dd7070Spatrick /// some other base.
897e5dd7070Spatrick VisitedVirtualBasesSetTy PrimaryVirtualBases;
898e5dd7070Spatrick
899e5dd7070Spatrick /// ComputeReturnAdjustment - Compute the return adjustment given a return
900e5dd7070Spatrick /// adjustment base offset.
901e5dd7070Spatrick ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
902e5dd7070Spatrick
903e5dd7070Spatrick /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
904e5dd7070Spatrick /// the 'this' pointer from the base subobject to the derived subobject.
905e5dd7070Spatrick BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
906e5dd7070Spatrick BaseSubobject Derived) const;
907e5dd7070Spatrick
908e5dd7070Spatrick /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
909e5dd7070Spatrick /// given virtual member function, its offset in the layout class and its
910e5dd7070Spatrick /// final overrider.
911e5dd7070Spatrick ThisAdjustment
912e5dd7070Spatrick ComputeThisAdjustment(const CXXMethodDecl *MD,
913e5dd7070Spatrick CharUnits BaseOffsetInLayoutClass,
914e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider);
915e5dd7070Spatrick
916e5dd7070Spatrick /// AddMethod - Add a single virtual member function to the vtable
917e5dd7070Spatrick /// components vector.
918e5dd7070Spatrick void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
919e5dd7070Spatrick
920e5dd7070Spatrick /// IsOverriderUsed - Returns whether the overrider will ever be used in this
921e5dd7070Spatrick /// part of the vtable.
922e5dd7070Spatrick ///
923e5dd7070Spatrick /// Itanium C++ ABI 2.5.2:
924e5dd7070Spatrick ///
925e5dd7070Spatrick /// struct A { virtual void f(); };
926e5dd7070Spatrick /// struct B : virtual public A { int i; };
927e5dd7070Spatrick /// struct C : virtual public A { int j; };
928e5dd7070Spatrick /// struct D : public B, public C {};
929e5dd7070Spatrick ///
930e5dd7070Spatrick /// When B and C are declared, A is a primary base in each case, so although
931e5dd7070Spatrick /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
932e5dd7070Spatrick /// adjustment is required and no thunk is generated. However, inside D
933e5dd7070Spatrick /// objects, A is no longer a primary base of C, so if we allowed calls to
934e5dd7070Spatrick /// C::f() to use the copy of A's vtable in the C subobject, we would need
935e5dd7070Spatrick /// to adjust this from C* to B::A*, which would require a third-party
936e5dd7070Spatrick /// thunk. Since we require that a call to C::f() first convert to A*,
937e5dd7070Spatrick /// C-in-D's copy of A's vtable is never referenced, so this is not
938e5dd7070Spatrick /// necessary.
939e5dd7070Spatrick bool IsOverriderUsed(const CXXMethodDecl *Overrider,
940e5dd7070Spatrick CharUnits BaseOffsetInLayoutClass,
941e5dd7070Spatrick const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
942e5dd7070Spatrick CharUnits FirstBaseOffsetInLayoutClass) const;
943e5dd7070Spatrick
944e5dd7070Spatrick
945e5dd7070Spatrick /// AddMethods - Add the methods of this base subobject and all its
946e5dd7070Spatrick /// primary bases to the vtable components vector.
947e5dd7070Spatrick void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
948e5dd7070Spatrick const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
949e5dd7070Spatrick CharUnits FirstBaseOffsetInLayoutClass,
950e5dd7070Spatrick PrimaryBasesSetVectorTy &PrimaryBases);
951e5dd7070Spatrick
952e5dd7070Spatrick // LayoutVTable - Layout the vtable for the given base class, including its
953e5dd7070Spatrick // secondary vtables and any vtables for virtual bases.
954e5dd7070Spatrick void LayoutVTable();
955e5dd7070Spatrick
956e5dd7070Spatrick /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
957e5dd7070Spatrick /// given base subobject, as well as all its secondary vtables.
958e5dd7070Spatrick ///
959e5dd7070Spatrick /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
960e5dd7070Spatrick /// or a direct or indirect base of a virtual base.
961e5dd7070Spatrick ///
962e5dd7070Spatrick /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
963e5dd7070Spatrick /// in the layout class.
964e5dd7070Spatrick void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
965e5dd7070Spatrick bool BaseIsMorallyVirtual,
966e5dd7070Spatrick bool BaseIsVirtualInLayoutClass,
967e5dd7070Spatrick CharUnits OffsetInLayoutClass);
968e5dd7070Spatrick
969e5dd7070Spatrick /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
970e5dd7070Spatrick /// subobject.
971e5dd7070Spatrick ///
972e5dd7070Spatrick /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
973e5dd7070Spatrick /// or a direct or indirect base of a virtual base.
974e5dd7070Spatrick void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
975e5dd7070Spatrick CharUnits OffsetInLayoutClass);
976e5dd7070Spatrick
977e5dd7070Spatrick /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
978e5dd7070Spatrick /// class hierarchy.
979e5dd7070Spatrick void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
980e5dd7070Spatrick CharUnits OffsetInLayoutClass,
981e5dd7070Spatrick VisitedVirtualBasesSetTy &VBases);
982e5dd7070Spatrick
983e5dd7070Spatrick /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
984e5dd7070Spatrick /// given base (excluding any primary bases).
985e5dd7070Spatrick void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
986e5dd7070Spatrick VisitedVirtualBasesSetTy &VBases);
987e5dd7070Spatrick
988e5dd7070Spatrick /// isBuildingConstructionVTable - Return whether this vtable builder is
989e5dd7070Spatrick /// building a construction vtable.
isBuildingConstructorVTable() const990e5dd7070Spatrick bool isBuildingConstructorVTable() const {
991e5dd7070Spatrick return MostDerivedClass != LayoutClass;
992e5dd7070Spatrick }
993e5dd7070Spatrick
994e5dd7070Spatrick public:
995e5dd7070Spatrick /// Component indices of the first component of each of the vtables in the
996e5dd7070Spatrick /// vtable group.
997e5dd7070Spatrick SmallVector<size_t, 4> VTableIndices;
998e5dd7070Spatrick
ItaniumVTableBuilder(ItaniumVTableContext & VTables,const CXXRecordDecl * MostDerivedClass,CharUnits MostDerivedClassOffset,bool MostDerivedClassIsVirtual,const CXXRecordDecl * LayoutClass)999e5dd7070Spatrick ItaniumVTableBuilder(ItaniumVTableContext &VTables,
1000e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass,
1001e5dd7070Spatrick CharUnits MostDerivedClassOffset,
1002e5dd7070Spatrick bool MostDerivedClassIsVirtual,
1003e5dd7070Spatrick const CXXRecordDecl *LayoutClass)
1004e5dd7070Spatrick : VTables(VTables), MostDerivedClass(MostDerivedClass),
1005e5dd7070Spatrick MostDerivedClassOffset(MostDerivedClassOffset),
1006e5dd7070Spatrick MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1007e5dd7070Spatrick LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1008e5dd7070Spatrick Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1009e5dd7070Spatrick assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
1010e5dd7070Spatrick
1011e5dd7070Spatrick LayoutVTable();
1012e5dd7070Spatrick
1013e5dd7070Spatrick if (Context.getLangOpts().DumpVTableLayouts)
1014e5dd7070Spatrick dumpLayout(llvm::outs());
1015e5dd7070Spatrick }
1016e5dd7070Spatrick
getNumThunks() const1017e5dd7070Spatrick uint64_t getNumThunks() const {
1018e5dd7070Spatrick return Thunks.size();
1019e5dd7070Spatrick }
1020e5dd7070Spatrick
thunks_begin() const1021e5dd7070Spatrick ThunksMapTy::const_iterator thunks_begin() const {
1022e5dd7070Spatrick return Thunks.begin();
1023e5dd7070Spatrick }
1024e5dd7070Spatrick
thunks_end() const1025e5dd7070Spatrick ThunksMapTy::const_iterator thunks_end() const {
1026e5dd7070Spatrick return Thunks.end();
1027e5dd7070Spatrick }
1028e5dd7070Spatrick
getVBaseOffsetOffsets() const1029e5dd7070Spatrick const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1030e5dd7070Spatrick return VBaseOffsetOffsets;
1031e5dd7070Spatrick }
1032e5dd7070Spatrick
getAddressPoints() const1033e5dd7070Spatrick const AddressPointsMapTy &getAddressPoints() const {
1034e5dd7070Spatrick return AddressPoints;
1035e5dd7070Spatrick }
1036e5dd7070Spatrick
vtable_indices_begin() const1037e5dd7070Spatrick MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1038e5dd7070Spatrick return MethodVTableIndices.begin();
1039e5dd7070Spatrick }
1040e5dd7070Spatrick
vtable_indices_end() const1041e5dd7070Spatrick MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1042e5dd7070Spatrick return MethodVTableIndices.end();
1043e5dd7070Spatrick }
1044e5dd7070Spatrick
vtable_components() const1045e5dd7070Spatrick ArrayRef<VTableComponent> vtable_components() const { return Components; }
1046e5dd7070Spatrick
address_points_begin() const1047e5dd7070Spatrick AddressPointsMapTy::const_iterator address_points_begin() const {
1048e5dd7070Spatrick return AddressPoints.begin();
1049e5dd7070Spatrick }
1050e5dd7070Spatrick
address_points_end() const1051e5dd7070Spatrick AddressPointsMapTy::const_iterator address_points_end() const {
1052e5dd7070Spatrick return AddressPoints.end();
1053e5dd7070Spatrick }
1054e5dd7070Spatrick
vtable_thunks_begin() const1055e5dd7070Spatrick VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1056e5dd7070Spatrick return VTableThunks.begin();
1057e5dd7070Spatrick }
1058e5dd7070Spatrick
vtable_thunks_end() const1059e5dd7070Spatrick VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1060e5dd7070Spatrick return VTableThunks.end();
1061e5dd7070Spatrick }
1062e5dd7070Spatrick
1063e5dd7070Spatrick /// dumpLayout - Dump the vtable layout.
1064e5dd7070Spatrick void dumpLayout(raw_ostream&);
1065e5dd7070Spatrick };
1066e5dd7070Spatrick
AddThunk(const CXXMethodDecl * MD,const ThunkInfo & Thunk)1067e5dd7070Spatrick void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1068e5dd7070Spatrick const ThunkInfo &Thunk) {
1069e5dd7070Spatrick assert(!isBuildingConstructorVTable() &&
1070e5dd7070Spatrick "Can't add thunks for construction vtable");
1071e5dd7070Spatrick
1072e5dd7070Spatrick SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1073e5dd7070Spatrick
1074e5dd7070Spatrick // Check if we have this thunk already.
1075*12c85518Srobert if (llvm::is_contained(ThunksVector, Thunk))
1076e5dd7070Spatrick return;
1077e5dd7070Spatrick
1078e5dd7070Spatrick ThunksVector.push_back(Thunk);
1079e5dd7070Spatrick }
1080e5dd7070Spatrick
1081e5dd7070Spatrick typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1082e5dd7070Spatrick
1083e5dd7070Spatrick /// Visit all the methods overridden by the given method recursively,
1084e5dd7070Spatrick /// in a depth-first pre-order. The Visitor's visitor method returns a bool
1085e5dd7070Spatrick /// indicating whether to continue the recursion for the given overridden
1086e5dd7070Spatrick /// method (i.e. returning false stops the iteration).
1087e5dd7070Spatrick template <class VisitorTy>
1088e5dd7070Spatrick static void
visitAllOverriddenMethods(const CXXMethodDecl * MD,VisitorTy & Visitor)1089e5dd7070Spatrick visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
1090ec727ea7Spatrick assert(VTableContextBase::hasVtableSlot(MD) && "Method is not virtual!");
1091e5dd7070Spatrick
1092e5dd7070Spatrick for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
1093e5dd7070Spatrick if (!Visitor(OverriddenMD))
1094e5dd7070Spatrick continue;
1095e5dd7070Spatrick visitAllOverriddenMethods(OverriddenMD, Visitor);
1096e5dd7070Spatrick }
1097e5dd7070Spatrick }
1098e5dd7070Spatrick
1099e5dd7070Spatrick /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1100e5dd7070Spatrick /// the overridden methods that the function decl overrides.
1101e5dd7070Spatrick static void
ComputeAllOverriddenMethods(const CXXMethodDecl * MD,OverriddenMethodsSetTy & OverriddenMethods)1102e5dd7070Spatrick ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1103e5dd7070Spatrick OverriddenMethodsSetTy& OverriddenMethods) {
1104e5dd7070Spatrick auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
1105e5dd7070Spatrick // Don't recurse on this method if we've already collected it.
1106e5dd7070Spatrick return OverriddenMethods.insert(MD).second;
1107e5dd7070Spatrick };
1108e5dd7070Spatrick visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
1109e5dd7070Spatrick }
1110e5dd7070Spatrick
ComputeThisAdjustments()1111e5dd7070Spatrick void ItaniumVTableBuilder::ComputeThisAdjustments() {
1112e5dd7070Spatrick // Now go through the method info map and see if any of the methods need
1113e5dd7070Spatrick // 'this' pointer adjustments.
1114e5dd7070Spatrick for (const auto &MI : MethodInfoMap) {
1115e5dd7070Spatrick const CXXMethodDecl *MD = MI.first;
1116e5dd7070Spatrick const MethodInfo &MethodInfo = MI.second;
1117e5dd7070Spatrick
1118e5dd7070Spatrick // Ignore adjustments for unused function pointers.
1119e5dd7070Spatrick uint64_t VTableIndex = MethodInfo.VTableIndex;
1120e5dd7070Spatrick if (Components[VTableIndex].getKind() ==
1121e5dd7070Spatrick VTableComponent::CK_UnusedFunctionPointer)
1122e5dd7070Spatrick continue;
1123e5dd7070Spatrick
1124e5dd7070Spatrick // Get the final overrider for this method.
1125e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider =
1126e5dd7070Spatrick Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1127e5dd7070Spatrick
1128e5dd7070Spatrick // Check if we need an adjustment at all.
1129e5dd7070Spatrick if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1130e5dd7070Spatrick // When a return thunk is needed by a derived class that overrides a
1131e5dd7070Spatrick // virtual base, gcc uses a virtual 'this' adjustment as well.
1132e5dd7070Spatrick // While the thunk itself might be needed by vtables in subclasses or
1133e5dd7070Spatrick // in construction vtables, there doesn't seem to be a reason for using
1134e5dd7070Spatrick // the thunk in this vtable. Still, we do so to match gcc.
1135e5dd7070Spatrick if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1136e5dd7070Spatrick continue;
1137e5dd7070Spatrick }
1138e5dd7070Spatrick
1139e5dd7070Spatrick ThisAdjustment ThisAdjustment =
1140e5dd7070Spatrick ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1141e5dd7070Spatrick
1142e5dd7070Spatrick if (ThisAdjustment.isEmpty())
1143e5dd7070Spatrick continue;
1144e5dd7070Spatrick
1145e5dd7070Spatrick // Add it.
1146e5dd7070Spatrick VTableThunks[VTableIndex].This = ThisAdjustment;
1147e5dd7070Spatrick
1148e5dd7070Spatrick if (isa<CXXDestructorDecl>(MD)) {
1149e5dd7070Spatrick // Add an adjustment for the deleting destructor as well.
1150e5dd7070Spatrick VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1151e5dd7070Spatrick }
1152e5dd7070Spatrick }
1153e5dd7070Spatrick
1154e5dd7070Spatrick /// Clear the method info map.
1155e5dd7070Spatrick MethodInfoMap.clear();
1156e5dd7070Spatrick
1157e5dd7070Spatrick if (isBuildingConstructorVTable()) {
1158e5dd7070Spatrick // We don't need to store thunk information for construction vtables.
1159e5dd7070Spatrick return;
1160e5dd7070Spatrick }
1161e5dd7070Spatrick
1162e5dd7070Spatrick for (const auto &TI : VTableThunks) {
1163e5dd7070Spatrick const VTableComponent &Component = Components[TI.first];
1164e5dd7070Spatrick const ThunkInfo &Thunk = TI.second;
1165e5dd7070Spatrick const CXXMethodDecl *MD;
1166e5dd7070Spatrick
1167e5dd7070Spatrick switch (Component.getKind()) {
1168e5dd7070Spatrick default:
1169e5dd7070Spatrick llvm_unreachable("Unexpected vtable component kind!");
1170e5dd7070Spatrick case VTableComponent::CK_FunctionPointer:
1171e5dd7070Spatrick MD = Component.getFunctionDecl();
1172e5dd7070Spatrick break;
1173e5dd7070Spatrick case VTableComponent::CK_CompleteDtorPointer:
1174e5dd7070Spatrick MD = Component.getDestructorDecl();
1175e5dd7070Spatrick break;
1176e5dd7070Spatrick case VTableComponent::CK_DeletingDtorPointer:
1177e5dd7070Spatrick // We've already added the thunk when we saw the complete dtor pointer.
1178e5dd7070Spatrick continue;
1179e5dd7070Spatrick }
1180e5dd7070Spatrick
1181e5dd7070Spatrick if (MD->getParent() == MostDerivedClass)
1182e5dd7070Spatrick AddThunk(MD, Thunk);
1183e5dd7070Spatrick }
1184e5dd7070Spatrick }
1185e5dd7070Spatrick
1186e5dd7070Spatrick ReturnAdjustment
ComputeReturnAdjustment(BaseOffset Offset)1187e5dd7070Spatrick ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1188e5dd7070Spatrick ReturnAdjustment Adjustment;
1189e5dd7070Spatrick
1190e5dd7070Spatrick if (!Offset.isEmpty()) {
1191e5dd7070Spatrick if (Offset.VirtualBase) {
1192e5dd7070Spatrick // Get the virtual base offset offset.
1193e5dd7070Spatrick if (Offset.DerivedClass == MostDerivedClass) {
1194e5dd7070Spatrick // We can get the offset offset directly from our map.
1195e5dd7070Spatrick Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1196e5dd7070Spatrick VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1197e5dd7070Spatrick } else {
1198e5dd7070Spatrick Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1199e5dd7070Spatrick VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1200e5dd7070Spatrick Offset.VirtualBase).getQuantity();
1201e5dd7070Spatrick }
1202e5dd7070Spatrick }
1203e5dd7070Spatrick
1204e5dd7070Spatrick Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1205e5dd7070Spatrick }
1206e5dd7070Spatrick
1207e5dd7070Spatrick return Adjustment;
1208e5dd7070Spatrick }
1209e5dd7070Spatrick
ComputeThisAdjustmentBaseOffset(BaseSubobject Base,BaseSubobject Derived) const1210e5dd7070Spatrick BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1211e5dd7070Spatrick BaseSubobject Base, BaseSubobject Derived) const {
1212e5dd7070Spatrick const CXXRecordDecl *BaseRD = Base.getBase();
1213e5dd7070Spatrick const CXXRecordDecl *DerivedRD = Derived.getBase();
1214e5dd7070Spatrick
1215e5dd7070Spatrick CXXBasePaths Paths(/*FindAmbiguities=*/true,
1216e5dd7070Spatrick /*RecordPaths=*/true, /*DetectVirtual=*/true);
1217e5dd7070Spatrick
1218e5dd7070Spatrick if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1219e5dd7070Spatrick llvm_unreachable("Class must be derived from the passed in base class!");
1220e5dd7070Spatrick
1221e5dd7070Spatrick // We have to go through all the paths, and see which one leads us to the
1222e5dd7070Spatrick // right base subobject.
1223e5dd7070Spatrick for (const CXXBasePath &Path : Paths) {
1224e5dd7070Spatrick BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
1225e5dd7070Spatrick
1226e5dd7070Spatrick CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1227e5dd7070Spatrick
1228e5dd7070Spatrick if (Offset.VirtualBase) {
1229e5dd7070Spatrick // If we have a virtual base class, the non-virtual offset is relative
1230e5dd7070Spatrick // to the virtual base class offset.
1231e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1232e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1233e5dd7070Spatrick
1234e5dd7070Spatrick /// Get the virtual base offset, relative to the most derived class
1235e5dd7070Spatrick /// layout.
1236e5dd7070Spatrick OffsetToBaseSubobject +=
1237e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1238e5dd7070Spatrick } else {
1239e5dd7070Spatrick // Otherwise, the non-virtual offset is relative to the derived class
1240e5dd7070Spatrick // offset.
1241e5dd7070Spatrick OffsetToBaseSubobject += Derived.getBaseOffset();
1242e5dd7070Spatrick }
1243e5dd7070Spatrick
1244e5dd7070Spatrick // Check if this path gives us the right base subobject.
1245e5dd7070Spatrick if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1246e5dd7070Spatrick // Since we're going from the base class _to_ the derived class, we'll
1247e5dd7070Spatrick // invert the non-virtual offset here.
1248e5dd7070Spatrick Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1249e5dd7070Spatrick return Offset;
1250e5dd7070Spatrick }
1251e5dd7070Spatrick }
1252e5dd7070Spatrick
1253e5dd7070Spatrick return BaseOffset();
1254e5dd7070Spatrick }
1255e5dd7070Spatrick
ComputeThisAdjustment(const CXXMethodDecl * MD,CharUnits BaseOffsetInLayoutClass,FinalOverriders::OverriderInfo Overrider)1256e5dd7070Spatrick ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1257e5dd7070Spatrick const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1258e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider) {
1259e5dd7070Spatrick // Ignore adjustments for pure virtual member functions.
1260e5dd7070Spatrick if (Overrider.Method->isPure())
1261e5dd7070Spatrick return ThisAdjustment();
1262e5dd7070Spatrick
1263e5dd7070Spatrick BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1264e5dd7070Spatrick BaseOffsetInLayoutClass);
1265e5dd7070Spatrick
1266e5dd7070Spatrick BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1267e5dd7070Spatrick Overrider.Offset);
1268e5dd7070Spatrick
1269e5dd7070Spatrick // Compute the adjustment offset.
1270e5dd7070Spatrick BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1271e5dd7070Spatrick OverriderBaseSubobject);
1272e5dd7070Spatrick if (Offset.isEmpty())
1273e5dd7070Spatrick return ThisAdjustment();
1274e5dd7070Spatrick
1275e5dd7070Spatrick ThisAdjustment Adjustment;
1276e5dd7070Spatrick
1277e5dd7070Spatrick if (Offset.VirtualBase) {
1278e5dd7070Spatrick // Get the vcall offset map for this virtual base.
1279e5dd7070Spatrick VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1280e5dd7070Spatrick
1281e5dd7070Spatrick if (VCallOffsets.empty()) {
1282e5dd7070Spatrick // We don't have vcall offsets for this virtual base, go ahead and
1283e5dd7070Spatrick // build them.
1284ec727ea7Spatrick VCallAndVBaseOffsetBuilder Builder(
1285ec727ea7Spatrick VTables, MostDerivedClass, MostDerivedClass,
1286e5dd7070Spatrick /*Overriders=*/nullptr,
1287ec727ea7Spatrick BaseSubobject(Offset.VirtualBase, CharUnits::Zero()),
1288e5dd7070Spatrick /*BaseIsVirtual=*/true,
1289e5dd7070Spatrick /*OffsetInLayoutClass=*/
1290e5dd7070Spatrick CharUnits::Zero());
1291e5dd7070Spatrick
1292e5dd7070Spatrick VCallOffsets = Builder.getVCallOffsets();
1293e5dd7070Spatrick }
1294e5dd7070Spatrick
1295e5dd7070Spatrick Adjustment.Virtual.Itanium.VCallOffsetOffset =
1296e5dd7070Spatrick VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1297e5dd7070Spatrick }
1298e5dd7070Spatrick
1299e5dd7070Spatrick // Set the non-virtual part of the adjustment.
1300e5dd7070Spatrick Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1301e5dd7070Spatrick
1302e5dd7070Spatrick return Adjustment;
1303e5dd7070Spatrick }
1304e5dd7070Spatrick
AddMethod(const CXXMethodDecl * MD,ReturnAdjustment ReturnAdjustment)1305e5dd7070Spatrick void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1306e5dd7070Spatrick ReturnAdjustment ReturnAdjustment) {
1307e5dd7070Spatrick if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1308e5dd7070Spatrick assert(ReturnAdjustment.isEmpty() &&
1309e5dd7070Spatrick "Destructor can't have return adjustment!");
1310e5dd7070Spatrick
1311e5dd7070Spatrick // Add both the complete destructor and the deleting destructor.
1312e5dd7070Spatrick Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1313e5dd7070Spatrick Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1314e5dd7070Spatrick } else {
1315e5dd7070Spatrick // Add the return adjustment if necessary.
1316e5dd7070Spatrick if (!ReturnAdjustment.isEmpty())
1317e5dd7070Spatrick VTableThunks[Components.size()].Return = ReturnAdjustment;
1318e5dd7070Spatrick
1319e5dd7070Spatrick // Add the function.
1320e5dd7070Spatrick Components.push_back(VTableComponent::MakeFunction(MD));
1321e5dd7070Spatrick }
1322e5dd7070Spatrick }
1323e5dd7070Spatrick
1324e5dd7070Spatrick /// OverridesIndirectMethodInBase - Return whether the given member function
1325e5dd7070Spatrick /// overrides any methods in the set of given bases.
1326e5dd7070Spatrick /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1327e5dd7070Spatrick /// For example, if we have:
1328e5dd7070Spatrick ///
1329e5dd7070Spatrick /// struct A { virtual void f(); }
1330e5dd7070Spatrick /// struct B : A { virtual void f(); }
1331e5dd7070Spatrick /// struct C : B { virtual void f(); }
1332e5dd7070Spatrick ///
1333e5dd7070Spatrick /// OverridesIndirectMethodInBase will return true if given C::f as the method
1334e5dd7070Spatrick /// and { A } as the set of bases.
OverridesIndirectMethodInBases(const CXXMethodDecl * MD,ItaniumVTableBuilder::PrimaryBasesSetVectorTy & Bases)1335e5dd7070Spatrick static bool OverridesIndirectMethodInBases(
1336e5dd7070Spatrick const CXXMethodDecl *MD,
1337e5dd7070Spatrick ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1338e5dd7070Spatrick if (Bases.count(MD->getParent()))
1339e5dd7070Spatrick return true;
1340e5dd7070Spatrick
1341e5dd7070Spatrick for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
1342e5dd7070Spatrick // Check "indirect overriders".
1343e5dd7070Spatrick if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1344e5dd7070Spatrick return true;
1345e5dd7070Spatrick }
1346e5dd7070Spatrick
1347e5dd7070Spatrick return false;
1348e5dd7070Spatrick }
1349e5dd7070Spatrick
IsOverriderUsed(const CXXMethodDecl * Overrider,CharUnits BaseOffsetInLayoutClass,const CXXRecordDecl * FirstBaseInPrimaryBaseChain,CharUnits FirstBaseOffsetInLayoutClass) const1350e5dd7070Spatrick bool ItaniumVTableBuilder::IsOverriderUsed(
1351e5dd7070Spatrick const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1352e5dd7070Spatrick const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1353e5dd7070Spatrick CharUnits FirstBaseOffsetInLayoutClass) const {
1354e5dd7070Spatrick // If the base and the first base in the primary base chain have the same
1355e5dd7070Spatrick // offsets, then this overrider will be used.
1356e5dd7070Spatrick if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1357e5dd7070Spatrick return true;
1358e5dd7070Spatrick
1359e5dd7070Spatrick // We know now that Base (or a direct or indirect base of it) is a primary
1360e5dd7070Spatrick // base in part of the class hierarchy, but not a primary base in the most
1361e5dd7070Spatrick // derived class.
1362e5dd7070Spatrick
1363e5dd7070Spatrick // If the overrider is the first base in the primary base chain, we know
1364e5dd7070Spatrick // that the overrider will be used.
1365e5dd7070Spatrick if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1366e5dd7070Spatrick return true;
1367e5dd7070Spatrick
1368e5dd7070Spatrick ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1369e5dd7070Spatrick
1370e5dd7070Spatrick const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1371e5dd7070Spatrick PrimaryBases.insert(RD);
1372e5dd7070Spatrick
1373e5dd7070Spatrick // Now traverse the base chain, starting with the first base, until we find
1374e5dd7070Spatrick // the base that is no longer a primary base.
1375e5dd7070Spatrick while (true) {
1376e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1377e5dd7070Spatrick const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1378e5dd7070Spatrick
1379e5dd7070Spatrick if (!PrimaryBase)
1380e5dd7070Spatrick break;
1381e5dd7070Spatrick
1382e5dd7070Spatrick if (Layout.isPrimaryBaseVirtual()) {
1383e5dd7070Spatrick assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1384e5dd7070Spatrick "Primary base should always be at offset 0!");
1385e5dd7070Spatrick
1386e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1387e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1388e5dd7070Spatrick
1389e5dd7070Spatrick // Now check if this is the primary base that is not a primary base in the
1390e5dd7070Spatrick // most derived class.
1391e5dd7070Spatrick if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1392e5dd7070Spatrick FirstBaseOffsetInLayoutClass) {
1393e5dd7070Spatrick // We found it, stop walking the chain.
1394e5dd7070Spatrick break;
1395e5dd7070Spatrick }
1396e5dd7070Spatrick } else {
1397e5dd7070Spatrick assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1398e5dd7070Spatrick "Primary base should always be at offset 0!");
1399e5dd7070Spatrick }
1400e5dd7070Spatrick
1401e5dd7070Spatrick if (!PrimaryBases.insert(PrimaryBase))
1402e5dd7070Spatrick llvm_unreachable("Found a duplicate primary base!");
1403e5dd7070Spatrick
1404e5dd7070Spatrick RD = PrimaryBase;
1405e5dd7070Spatrick }
1406e5dd7070Spatrick
1407e5dd7070Spatrick // If the final overrider is an override of one of the primary bases,
1408e5dd7070Spatrick // then we know that it will be used.
1409e5dd7070Spatrick return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1410e5dd7070Spatrick }
1411e5dd7070Spatrick
1412e5dd7070Spatrick typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1413e5dd7070Spatrick
1414e5dd7070Spatrick /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1415e5dd7070Spatrick /// from the nearest base. Returns null if no method was found.
1416e5dd7070Spatrick /// The Bases are expected to be sorted in a base-to-derived order.
1417e5dd7070Spatrick static const CXXMethodDecl *
FindNearestOverriddenMethod(const CXXMethodDecl * MD,BasesSetVectorTy & Bases)1418e5dd7070Spatrick FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1419e5dd7070Spatrick BasesSetVectorTy &Bases) {
1420e5dd7070Spatrick OverriddenMethodsSetTy OverriddenMethods;
1421e5dd7070Spatrick ComputeAllOverriddenMethods(MD, OverriddenMethods);
1422e5dd7070Spatrick
1423*12c85518Srobert for (const CXXRecordDecl *PrimaryBase : llvm::reverse(Bases)) {
1424e5dd7070Spatrick // Now check the overridden methods.
1425e5dd7070Spatrick for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
1426e5dd7070Spatrick // We found our overridden method.
1427e5dd7070Spatrick if (OverriddenMD->getParent() == PrimaryBase)
1428e5dd7070Spatrick return OverriddenMD;
1429e5dd7070Spatrick }
1430e5dd7070Spatrick }
1431e5dd7070Spatrick
1432e5dd7070Spatrick return nullptr;
1433e5dd7070Spatrick }
1434e5dd7070Spatrick
AddMethods(BaseSubobject Base,CharUnits BaseOffsetInLayoutClass,const CXXRecordDecl * FirstBaseInPrimaryBaseChain,CharUnits FirstBaseOffsetInLayoutClass,PrimaryBasesSetVectorTy & PrimaryBases)1435e5dd7070Spatrick void ItaniumVTableBuilder::AddMethods(
1436e5dd7070Spatrick BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1437e5dd7070Spatrick const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1438e5dd7070Spatrick CharUnits FirstBaseOffsetInLayoutClass,
1439e5dd7070Spatrick PrimaryBasesSetVectorTy &PrimaryBases) {
1440e5dd7070Spatrick // Itanium C++ ABI 2.5.2:
1441e5dd7070Spatrick // The order of the virtual function pointers in a virtual table is the
1442e5dd7070Spatrick // order of declaration of the corresponding member functions in the class.
1443e5dd7070Spatrick //
1444e5dd7070Spatrick // There is an entry for any virtual function declared in a class,
1445e5dd7070Spatrick // whether it is a new function or overrides a base class function,
1446e5dd7070Spatrick // unless it overrides a function from the primary base, and conversion
1447e5dd7070Spatrick // between their return types does not require an adjustment.
1448e5dd7070Spatrick
1449e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
1450e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1451e5dd7070Spatrick
1452e5dd7070Spatrick if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1453e5dd7070Spatrick CharUnits PrimaryBaseOffset;
1454e5dd7070Spatrick CharUnits PrimaryBaseOffsetInLayoutClass;
1455e5dd7070Spatrick if (Layout.isPrimaryBaseVirtual()) {
1456e5dd7070Spatrick assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1457e5dd7070Spatrick "Primary vbase should have a zero offset!");
1458e5dd7070Spatrick
1459e5dd7070Spatrick const ASTRecordLayout &MostDerivedClassLayout =
1460e5dd7070Spatrick Context.getASTRecordLayout(MostDerivedClass);
1461e5dd7070Spatrick
1462e5dd7070Spatrick PrimaryBaseOffset =
1463e5dd7070Spatrick MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1464e5dd7070Spatrick
1465e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1466e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1467e5dd7070Spatrick
1468e5dd7070Spatrick PrimaryBaseOffsetInLayoutClass =
1469e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1470e5dd7070Spatrick } else {
1471e5dd7070Spatrick assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1472e5dd7070Spatrick "Primary base should have a zero offset!");
1473e5dd7070Spatrick
1474e5dd7070Spatrick PrimaryBaseOffset = Base.getBaseOffset();
1475e5dd7070Spatrick PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1476e5dd7070Spatrick }
1477e5dd7070Spatrick
1478e5dd7070Spatrick AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1479e5dd7070Spatrick PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1480e5dd7070Spatrick FirstBaseOffsetInLayoutClass, PrimaryBases);
1481e5dd7070Spatrick
1482e5dd7070Spatrick if (!PrimaryBases.insert(PrimaryBase))
1483e5dd7070Spatrick llvm_unreachable("Found a duplicate primary base!");
1484e5dd7070Spatrick }
1485e5dd7070Spatrick
1486e5dd7070Spatrick typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1487e5dd7070Spatrick NewVirtualFunctionsTy NewVirtualFunctions;
1488e5dd7070Spatrick
1489ec727ea7Spatrick llvm::SmallVector<const CXXMethodDecl*, 4> NewImplicitVirtualFunctions;
1490ec727ea7Spatrick
1491e5dd7070Spatrick // Now go through all virtual member functions and add them.
1492e5dd7070Spatrick for (const auto *MD : RD->methods()) {
1493ec727ea7Spatrick if (!ItaniumVTableContext::hasVtableSlot(MD))
1494e5dd7070Spatrick continue;
1495e5dd7070Spatrick MD = MD->getCanonicalDecl();
1496e5dd7070Spatrick
1497e5dd7070Spatrick // Get the final overrider.
1498e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider =
1499e5dd7070Spatrick Overriders.getOverrider(MD, Base.getBaseOffset());
1500e5dd7070Spatrick
1501e5dd7070Spatrick // Check if this virtual member function overrides a method in a primary
1502e5dd7070Spatrick // base. If this is the case, and the return type doesn't require adjustment
1503e5dd7070Spatrick // then we can just use the member function from the primary base.
1504e5dd7070Spatrick if (const CXXMethodDecl *OverriddenMD =
1505e5dd7070Spatrick FindNearestOverriddenMethod(MD, PrimaryBases)) {
1506e5dd7070Spatrick if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1507e5dd7070Spatrick OverriddenMD).isEmpty()) {
1508e5dd7070Spatrick // Replace the method info of the overridden method with our own
1509e5dd7070Spatrick // method.
1510e5dd7070Spatrick assert(MethodInfoMap.count(OverriddenMD) &&
1511e5dd7070Spatrick "Did not find the overridden method!");
1512e5dd7070Spatrick MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1513e5dd7070Spatrick
1514e5dd7070Spatrick MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1515e5dd7070Spatrick OverriddenMethodInfo.VTableIndex);
1516e5dd7070Spatrick
1517e5dd7070Spatrick assert(!MethodInfoMap.count(MD) &&
1518e5dd7070Spatrick "Should not have method info for this method yet!");
1519e5dd7070Spatrick
1520e5dd7070Spatrick MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1521e5dd7070Spatrick MethodInfoMap.erase(OverriddenMD);
1522e5dd7070Spatrick
1523e5dd7070Spatrick // If the overridden method exists in a virtual base class or a direct
1524e5dd7070Spatrick // or indirect base class of a virtual base class, we need to emit a
1525e5dd7070Spatrick // thunk if we ever have a class hierarchy where the base class is not
1526e5dd7070Spatrick // a primary base in the complete object.
1527e5dd7070Spatrick if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1528e5dd7070Spatrick // Compute the this adjustment.
1529e5dd7070Spatrick ThisAdjustment ThisAdjustment =
1530e5dd7070Spatrick ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1531e5dd7070Spatrick Overrider);
1532e5dd7070Spatrick
1533e5dd7070Spatrick if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
1534e5dd7070Spatrick Overrider.Method->getParent() == MostDerivedClass) {
1535e5dd7070Spatrick
1536e5dd7070Spatrick // There's no return adjustment from OverriddenMD and MD,
1537e5dd7070Spatrick // but that doesn't mean there isn't one between MD and
1538e5dd7070Spatrick // the final overrider.
1539e5dd7070Spatrick BaseOffset ReturnAdjustmentOffset =
1540e5dd7070Spatrick ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1541e5dd7070Spatrick ReturnAdjustment ReturnAdjustment =
1542e5dd7070Spatrick ComputeReturnAdjustment(ReturnAdjustmentOffset);
1543e5dd7070Spatrick
1544e5dd7070Spatrick // This is a virtual thunk for the most derived class, add it.
1545e5dd7070Spatrick AddThunk(Overrider.Method,
1546e5dd7070Spatrick ThunkInfo(ThisAdjustment, ReturnAdjustment));
1547e5dd7070Spatrick }
1548e5dd7070Spatrick }
1549e5dd7070Spatrick
1550e5dd7070Spatrick continue;
1551e5dd7070Spatrick }
1552e5dd7070Spatrick }
1553e5dd7070Spatrick
1554ec727ea7Spatrick if (MD->isImplicit())
1555ec727ea7Spatrick NewImplicitVirtualFunctions.push_back(MD);
1556ec727ea7Spatrick else
1557e5dd7070Spatrick NewVirtualFunctions.push_back(MD);
1558e5dd7070Spatrick }
1559e5dd7070Spatrick
1560ec727ea7Spatrick std::stable_sort(
1561ec727ea7Spatrick NewImplicitVirtualFunctions.begin(), NewImplicitVirtualFunctions.end(),
1562ec727ea7Spatrick [](const CXXMethodDecl *A, const CXXMethodDecl *B) {
1563ec727ea7Spatrick if (A->isCopyAssignmentOperator() != B->isCopyAssignmentOperator())
1564ec727ea7Spatrick return A->isCopyAssignmentOperator();
1565ec727ea7Spatrick if (A->isMoveAssignmentOperator() != B->isMoveAssignmentOperator())
1566ec727ea7Spatrick return A->isMoveAssignmentOperator();
1567ec727ea7Spatrick if (isa<CXXDestructorDecl>(A) != isa<CXXDestructorDecl>(B))
1568ec727ea7Spatrick return isa<CXXDestructorDecl>(A);
1569ec727ea7Spatrick assert(A->getOverloadedOperator() == OO_EqualEqual &&
1570ec727ea7Spatrick B->getOverloadedOperator() == OO_EqualEqual &&
1571ec727ea7Spatrick "unexpected or duplicate implicit virtual function");
1572ec727ea7Spatrick // We rely on Sema to have declared the operator== members in the
1573ec727ea7Spatrick // same order as the corresponding operator<=> members.
1574ec727ea7Spatrick return false;
1575ec727ea7Spatrick });
1576ec727ea7Spatrick NewVirtualFunctions.append(NewImplicitVirtualFunctions.begin(),
1577ec727ea7Spatrick NewImplicitVirtualFunctions.end());
1578e5dd7070Spatrick
1579e5dd7070Spatrick for (const CXXMethodDecl *MD : NewVirtualFunctions) {
1580e5dd7070Spatrick // Get the final overrider.
1581e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider =
1582e5dd7070Spatrick Overriders.getOverrider(MD, Base.getBaseOffset());
1583e5dd7070Spatrick
1584e5dd7070Spatrick // Insert the method info for this method.
1585e5dd7070Spatrick MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1586e5dd7070Spatrick Components.size());
1587e5dd7070Spatrick
1588e5dd7070Spatrick assert(!MethodInfoMap.count(MD) &&
1589e5dd7070Spatrick "Should not have method info for this method yet!");
1590e5dd7070Spatrick MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1591e5dd7070Spatrick
1592e5dd7070Spatrick // Check if this overrider is going to be used.
1593e5dd7070Spatrick const CXXMethodDecl *OverriderMD = Overrider.Method;
1594e5dd7070Spatrick if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1595e5dd7070Spatrick FirstBaseInPrimaryBaseChain,
1596e5dd7070Spatrick FirstBaseOffsetInLayoutClass)) {
1597e5dd7070Spatrick Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1598e5dd7070Spatrick continue;
1599e5dd7070Spatrick }
1600e5dd7070Spatrick
1601e5dd7070Spatrick // Check if this overrider needs a return adjustment.
1602e5dd7070Spatrick // We don't want to do this for pure virtual member functions.
1603e5dd7070Spatrick BaseOffset ReturnAdjustmentOffset;
1604e5dd7070Spatrick if (!OverriderMD->isPure()) {
1605e5dd7070Spatrick ReturnAdjustmentOffset =
1606e5dd7070Spatrick ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1607e5dd7070Spatrick }
1608e5dd7070Spatrick
1609e5dd7070Spatrick ReturnAdjustment ReturnAdjustment =
1610e5dd7070Spatrick ComputeReturnAdjustment(ReturnAdjustmentOffset);
1611e5dd7070Spatrick
1612e5dd7070Spatrick AddMethod(Overrider.Method, ReturnAdjustment);
1613e5dd7070Spatrick }
1614e5dd7070Spatrick }
1615e5dd7070Spatrick
LayoutVTable()1616e5dd7070Spatrick void ItaniumVTableBuilder::LayoutVTable() {
1617e5dd7070Spatrick LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1618e5dd7070Spatrick CharUnits::Zero()),
1619e5dd7070Spatrick /*BaseIsMorallyVirtual=*/false,
1620e5dd7070Spatrick MostDerivedClassIsVirtual,
1621e5dd7070Spatrick MostDerivedClassOffset);
1622e5dd7070Spatrick
1623e5dd7070Spatrick VisitedVirtualBasesSetTy VBases;
1624e5dd7070Spatrick
1625e5dd7070Spatrick // Determine the primary virtual bases.
1626e5dd7070Spatrick DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1627e5dd7070Spatrick VBases);
1628e5dd7070Spatrick VBases.clear();
1629e5dd7070Spatrick
1630e5dd7070Spatrick LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1631e5dd7070Spatrick
1632e5dd7070Spatrick // -fapple-kext adds an extra entry at end of vtbl.
1633e5dd7070Spatrick bool IsAppleKext = Context.getLangOpts().AppleKext;
1634e5dd7070Spatrick if (IsAppleKext)
1635e5dd7070Spatrick Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1636e5dd7070Spatrick }
1637e5dd7070Spatrick
LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,bool BaseIsMorallyVirtual,bool BaseIsVirtualInLayoutClass,CharUnits OffsetInLayoutClass)1638e5dd7070Spatrick void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1639e5dd7070Spatrick BaseSubobject Base, bool BaseIsMorallyVirtual,
1640e5dd7070Spatrick bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
1641e5dd7070Spatrick assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1642e5dd7070Spatrick
1643e5dd7070Spatrick unsigned VTableIndex = Components.size();
1644e5dd7070Spatrick VTableIndices.push_back(VTableIndex);
1645e5dd7070Spatrick
1646e5dd7070Spatrick // Add vcall and vbase offsets for this vtable.
1647ec727ea7Spatrick VCallAndVBaseOffsetBuilder Builder(
1648ec727ea7Spatrick VTables, MostDerivedClass, LayoutClass, &Overriders, Base,
1649ec727ea7Spatrick BaseIsVirtualInLayoutClass, OffsetInLayoutClass);
1650e5dd7070Spatrick Components.append(Builder.components_begin(), Builder.components_end());
1651e5dd7070Spatrick
1652e5dd7070Spatrick // Check if we need to add these vcall offsets.
1653e5dd7070Spatrick if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1654e5dd7070Spatrick VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1655e5dd7070Spatrick
1656e5dd7070Spatrick if (VCallOffsets.empty())
1657e5dd7070Spatrick VCallOffsets = Builder.getVCallOffsets();
1658e5dd7070Spatrick }
1659e5dd7070Spatrick
1660e5dd7070Spatrick // If we're laying out the most derived class we want to keep track of the
1661e5dd7070Spatrick // virtual base class offset offsets.
1662e5dd7070Spatrick if (Base.getBase() == MostDerivedClass)
1663e5dd7070Spatrick VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1664e5dd7070Spatrick
1665e5dd7070Spatrick // Add the offset to top.
1666e5dd7070Spatrick CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1667e5dd7070Spatrick Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1668e5dd7070Spatrick
1669e5dd7070Spatrick // Next, add the RTTI.
1670e5dd7070Spatrick Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1671e5dd7070Spatrick
1672e5dd7070Spatrick uint64_t AddressPoint = Components.size();
1673e5dd7070Spatrick
1674e5dd7070Spatrick // Now go through all virtual member functions and add them.
1675e5dd7070Spatrick PrimaryBasesSetVectorTy PrimaryBases;
1676e5dd7070Spatrick AddMethods(Base, OffsetInLayoutClass,
1677e5dd7070Spatrick Base.getBase(), OffsetInLayoutClass,
1678e5dd7070Spatrick PrimaryBases);
1679e5dd7070Spatrick
1680e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
1681e5dd7070Spatrick if (RD == MostDerivedClass) {
1682e5dd7070Spatrick assert(MethodVTableIndices.empty());
1683e5dd7070Spatrick for (const auto &I : MethodInfoMap) {
1684e5dd7070Spatrick const CXXMethodDecl *MD = I.first;
1685e5dd7070Spatrick const MethodInfo &MI = I.second;
1686e5dd7070Spatrick if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1687e5dd7070Spatrick MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1688e5dd7070Spatrick = MI.VTableIndex - AddressPoint;
1689e5dd7070Spatrick MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1690e5dd7070Spatrick = MI.VTableIndex + 1 - AddressPoint;
1691e5dd7070Spatrick } else {
1692e5dd7070Spatrick MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1693e5dd7070Spatrick }
1694e5dd7070Spatrick }
1695e5dd7070Spatrick }
1696e5dd7070Spatrick
1697e5dd7070Spatrick // Compute 'this' pointer adjustments.
1698e5dd7070Spatrick ComputeThisAdjustments();
1699e5dd7070Spatrick
1700e5dd7070Spatrick // Add all address points.
1701e5dd7070Spatrick while (true) {
1702e5dd7070Spatrick AddressPoints.insert(
1703e5dd7070Spatrick std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
1704e5dd7070Spatrick VTableLayout::AddressPointLocation{
1705e5dd7070Spatrick unsigned(VTableIndices.size() - 1),
1706e5dd7070Spatrick unsigned(AddressPoint - VTableIndex)}));
1707e5dd7070Spatrick
1708e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1709e5dd7070Spatrick const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1710e5dd7070Spatrick
1711e5dd7070Spatrick if (!PrimaryBase)
1712e5dd7070Spatrick break;
1713e5dd7070Spatrick
1714e5dd7070Spatrick if (Layout.isPrimaryBaseVirtual()) {
1715e5dd7070Spatrick // Check if this virtual primary base is a primary base in the layout
1716e5dd7070Spatrick // class. If it's not, we don't want to add it.
1717e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1718e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1719e5dd7070Spatrick
1720e5dd7070Spatrick if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1721e5dd7070Spatrick OffsetInLayoutClass) {
1722e5dd7070Spatrick // We don't want to add this class (or any of its primary bases).
1723e5dd7070Spatrick break;
1724e5dd7070Spatrick }
1725e5dd7070Spatrick }
1726e5dd7070Spatrick
1727e5dd7070Spatrick RD = PrimaryBase;
1728e5dd7070Spatrick }
1729e5dd7070Spatrick
1730e5dd7070Spatrick // Layout secondary vtables.
1731e5dd7070Spatrick LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1732e5dd7070Spatrick }
1733e5dd7070Spatrick
1734e5dd7070Spatrick void
LayoutSecondaryVTables(BaseSubobject Base,bool BaseIsMorallyVirtual,CharUnits OffsetInLayoutClass)1735e5dd7070Spatrick ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1736e5dd7070Spatrick bool BaseIsMorallyVirtual,
1737e5dd7070Spatrick CharUnits OffsetInLayoutClass) {
1738e5dd7070Spatrick // Itanium C++ ABI 2.5.2:
1739e5dd7070Spatrick // Following the primary virtual table of a derived class are secondary
1740e5dd7070Spatrick // virtual tables for each of its proper base classes, except any primary
1741e5dd7070Spatrick // base(s) with which it shares its primary virtual table.
1742e5dd7070Spatrick
1743e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
1744e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1745e5dd7070Spatrick const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1746e5dd7070Spatrick
1747e5dd7070Spatrick for (const auto &B : RD->bases()) {
1748e5dd7070Spatrick // Ignore virtual bases, we'll emit them later.
1749e5dd7070Spatrick if (B.isVirtual())
1750e5dd7070Spatrick continue;
1751e5dd7070Spatrick
1752e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1753e5dd7070Spatrick
1754e5dd7070Spatrick // Ignore bases that don't have a vtable.
1755e5dd7070Spatrick if (!BaseDecl->isDynamicClass())
1756e5dd7070Spatrick continue;
1757e5dd7070Spatrick
1758e5dd7070Spatrick if (isBuildingConstructorVTable()) {
1759e5dd7070Spatrick // Itanium C++ ABI 2.6.4:
1760e5dd7070Spatrick // Some of the base class subobjects may not need construction virtual
1761e5dd7070Spatrick // tables, which will therefore not be present in the construction
1762e5dd7070Spatrick // virtual table group, even though the subobject virtual tables are
1763e5dd7070Spatrick // present in the main virtual table group for the complete object.
1764e5dd7070Spatrick if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1765e5dd7070Spatrick continue;
1766e5dd7070Spatrick }
1767e5dd7070Spatrick
1768e5dd7070Spatrick // Get the base offset of this base.
1769e5dd7070Spatrick CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1770e5dd7070Spatrick CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1771e5dd7070Spatrick
1772e5dd7070Spatrick CharUnits BaseOffsetInLayoutClass =
1773e5dd7070Spatrick OffsetInLayoutClass + RelativeBaseOffset;
1774e5dd7070Spatrick
1775e5dd7070Spatrick // Don't emit a secondary vtable for a primary base. We might however want
1776e5dd7070Spatrick // to emit secondary vtables for other bases of this base.
1777e5dd7070Spatrick if (BaseDecl == PrimaryBase) {
1778e5dd7070Spatrick LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1779e5dd7070Spatrick BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1780e5dd7070Spatrick continue;
1781e5dd7070Spatrick }
1782e5dd7070Spatrick
1783e5dd7070Spatrick // Layout the primary vtable (and any secondary vtables) for this base.
1784e5dd7070Spatrick LayoutPrimaryAndSecondaryVTables(
1785e5dd7070Spatrick BaseSubobject(BaseDecl, BaseOffset),
1786e5dd7070Spatrick BaseIsMorallyVirtual,
1787e5dd7070Spatrick /*BaseIsVirtualInLayoutClass=*/false,
1788e5dd7070Spatrick BaseOffsetInLayoutClass);
1789e5dd7070Spatrick }
1790e5dd7070Spatrick }
1791e5dd7070Spatrick
DeterminePrimaryVirtualBases(const CXXRecordDecl * RD,CharUnits OffsetInLayoutClass,VisitedVirtualBasesSetTy & VBases)1792e5dd7070Spatrick void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1793e5dd7070Spatrick const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1794e5dd7070Spatrick VisitedVirtualBasesSetTy &VBases) {
1795e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1796e5dd7070Spatrick
1797e5dd7070Spatrick // Check if this base has a primary base.
1798e5dd7070Spatrick if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1799e5dd7070Spatrick
1800e5dd7070Spatrick // Check if it's virtual.
1801e5dd7070Spatrick if (Layout.isPrimaryBaseVirtual()) {
1802e5dd7070Spatrick bool IsPrimaryVirtualBase = true;
1803e5dd7070Spatrick
1804e5dd7070Spatrick if (isBuildingConstructorVTable()) {
1805e5dd7070Spatrick // Check if the base is actually a primary base in the class we use for
1806e5dd7070Spatrick // layout.
1807e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1808e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1809e5dd7070Spatrick
1810e5dd7070Spatrick CharUnits PrimaryBaseOffsetInLayoutClass =
1811e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1812e5dd7070Spatrick
1813e5dd7070Spatrick // We know that the base is not a primary base in the layout class if
1814e5dd7070Spatrick // the base offsets are different.
1815e5dd7070Spatrick if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1816e5dd7070Spatrick IsPrimaryVirtualBase = false;
1817e5dd7070Spatrick }
1818e5dd7070Spatrick
1819e5dd7070Spatrick if (IsPrimaryVirtualBase)
1820e5dd7070Spatrick PrimaryVirtualBases.insert(PrimaryBase);
1821e5dd7070Spatrick }
1822e5dd7070Spatrick }
1823e5dd7070Spatrick
1824e5dd7070Spatrick // Traverse bases, looking for more primary virtual bases.
1825e5dd7070Spatrick for (const auto &B : RD->bases()) {
1826e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1827e5dd7070Spatrick
1828e5dd7070Spatrick CharUnits BaseOffsetInLayoutClass;
1829e5dd7070Spatrick
1830e5dd7070Spatrick if (B.isVirtual()) {
1831e5dd7070Spatrick if (!VBases.insert(BaseDecl).second)
1832e5dd7070Spatrick continue;
1833e5dd7070Spatrick
1834e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1835e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1836e5dd7070Spatrick
1837e5dd7070Spatrick BaseOffsetInLayoutClass =
1838e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1839e5dd7070Spatrick } else {
1840e5dd7070Spatrick BaseOffsetInLayoutClass =
1841e5dd7070Spatrick OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1842e5dd7070Spatrick }
1843e5dd7070Spatrick
1844e5dd7070Spatrick DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1845e5dd7070Spatrick }
1846e5dd7070Spatrick }
1847e5dd7070Spatrick
LayoutVTablesForVirtualBases(const CXXRecordDecl * RD,VisitedVirtualBasesSetTy & VBases)1848e5dd7070Spatrick void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1849e5dd7070Spatrick const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
1850e5dd7070Spatrick // Itanium C++ ABI 2.5.2:
1851e5dd7070Spatrick // Then come the virtual base virtual tables, also in inheritance graph
1852e5dd7070Spatrick // order, and again excluding primary bases (which share virtual tables with
1853e5dd7070Spatrick // the classes for which they are primary).
1854e5dd7070Spatrick for (const auto &B : RD->bases()) {
1855e5dd7070Spatrick const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1856e5dd7070Spatrick
1857e5dd7070Spatrick // Check if this base needs a vtable. (If it's virtual, not a primary base
1858e5dd7070Spatrick // of some other class, and we haven't visited it before).
1859e5dd7070Spatrick if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1860e5dd7070Spatrick !PrimaryVirtualBases.count(BaseDecl) &&
1861e5dd7070Spatrick VBases.insert(BaseDecl).second) {
1862e5dd7070Spatrick const ASTRecordLayout &MostDerivedClassLayout =
1863e5dd7070Spatrick Context.getASTRecordLayout(MostDerivedClass);
1864e5dd7070Spatrick CharUnits BaseOffset =
1865e5dd7070Spatrick MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1866e5dd7070Spatrick
1867e5dd7070Spatrick const ASTRecordLayout &LayoutClassLayout =
1868e5dd7070Spatrick Context.getASTRecordLayout(LayoutClass);
1869e5dd7070Spatrick CharUnits BaseOffsetInLayoutClass =
1870e5dd7070Spatrick LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1871e5dd7070Spatrick
1872e5dd7070Spatrick LayoutPrimaryAndSecondaryVTables(
1873e5dd7070Spatrick BaseSubobject(BaseDecl, BaseOffset),
1874e5dd7070Spatrick /*BaseIsMorallyVirtual=*/true,
1875e5dd7070Spatrick /*BaseIsVirtualInLayoutClass=*/true,
1876e5dd7070Spatrick BaseOffsetInLayoutClass);
1877e5dd7070Spatrick }
1878e5dd7070Spatrick
1879e5dd7070Spatrick // We only need to check the base for virtual base vtables if it actually
1880e5dd7070Spatrick // has virtual bases.
1881e5dd7070Spatrick if (BaseDecl->getNumVBases())
1882e5dd7070Spatrick LayoutVTablesForVirtualBases(BaseDecl, VBases);
1883e5dd7070Spatrick }
1884e5dd7070Spatrick }
1885e5dd7070Spatrick
1886e5dd7070Spatrick /// dumpLayout - Dump the vtable layout.
dumpLayout(raw_ostream & Out)1887e5dd7070Spatrick void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
1888e5dd7070Spatrick // FIXME: write more tests that actually use the dumpLayout output to prevent
1889e5dd7070Spatrick // ItaniumVTableBuilder regressions.
1890e5dd7070Spatrick
1891e5dd7070Spatrick if (isBuildingConstructorVTable()) {
1892e5dd7070Spatrick Out << "Construction vtable for ('";
1893e5dd7070Spatrick MostDerivedClass->printQualifiedName(Out);
1894e5dd7070Spatrick Out << "', ";
1895e5dd7070Spatrick Out << MostDerivedClassOffset.getQuantity() << ") in '";
1896e5dd7070Spatrick LayoutClass->printQualifiedName(Out);
1897e5dd7070Spatrick } else {
1898e5dd7070Spatrick Out << "Vtable for '";
1899e5dd7070Spatrick MostDerivedClass->printQualifiedName(Out);
1900e5dd7070Spatrick }
1901e5dd7070Spatrick Out << "' (" << Components.size() << " entries).\n";
1902e5dd7070Spatrick
1903e5dd7070Spatrick // Iterate through the address points and insert them into a new map where
1904e5dd7070Spatrick // they are keyed by the index and not the base object.
1905e5dd7070Spatrick // Since an address point can be shared by multiple subobjects, we use an
1906e5dd7070Spatrick // STL multimap.
1907e5dd7070Spatrick std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1908e5dd7070Spatrick for (const auto &AP : AddressPoints) {
1909e5dd7070Spatrick const BaseSubobject &Base = AP.first;
1910e5dd7070Spatrick uint64_t Index =
1911e5dd7070Spatrick VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
1912e5dd7070Spatrick
1913e5dd7070Spatrick AddressPointsByIndex.insert(std::make_pair(Index, Base));
1914e5dd7070Spatrick }
1915e5dd7070Spatrick
1916e5dd7070Spatrick for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1917e5dd7070Spatrick uint64_t Index = I;
1918e5dd7070Spatrick
1919e5dd7070Spatrick Out << llvm::format("%4d | ", I);
1920e5dd7070Spatrick
1921e5dd7070Spatrick const VTableComponent &Component = Components[I];
1922e5dd7070Spatrick
1923e5dd7070Spatrick // Dump the component.
1924e5dd7070Spatrick switch (Component.getKind()) {
1925e5dd7070Spatrick
1926e5dd7070Spatrick case VTableComponent::CK_VCallOffset:
1927e5dd7070Spatrick Out << "vcall_offset ("
1928e5dd7070Spatrick << Component.getVCallOffset().getQuantity()
1929e5dd7070Spatrick << ")";
1930e5dd7070Spatrick break;
1931e5dd7070Spatrick
1932e5dd7070Spatrick case VTableComponent::CK_VBaseOffset:
1933e5dd7070Spatrick Out << "vbase_offset ("
1934e5dd7070Spatrick << Component.getVBaseOffset().getQuantity()
1935e5dd7070Spatrick << ")";
1936e5dd7070Spatrick break;
1937e5dd7070Spatrick
1938e5dd7070Spatrick case VTableComponent::CK_OffsetToTop:
1939e5dd7070Spatrick Out << "offset_to_top ("
1940e5dd7070Spatrick << Component.getOffsetToTop().getQuantity()
1941e5dd7070Spatrick << ")";
1942e5dd7070Spatrick break;
1943e5dd7070Spatrick
1944e5dd7070Spatrick case VTableComponent::CK_RTTI:
1945e5dd7070Spatrick Component.getRTTIDecl()->printQualifiedName(Out);
1946e5dd7070Spatrick Out << " RTTI";
1947e5dd7070Spatrick break;
1948e5dd7070Spatrick
1949e5dd7070Spatrick case VTableComponent::CK_FunctionPointer: {
1950e5dd7070Spatrick const CXXMethodDecl *MD = Component.getFunctionDecl();
1951e5dd7070Spatrick
1952e5dd7070Spatrick std::string Str =
1953e5dd7070Spatrick PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1954e5dd7070Spatrick MD);
1955e5dd7070Spatrick Out << Str;
1956e5dd7070Spatrick if (MD->isPure())
1957e5dd7070Spatrick Out << " [pure]";
1958e5dd7070Spatrick
1959e5dd7070Spatrick if (MD->isDeleted())
1960e5dd7070Spatrick Out << " [deleted]";
1961e5dd7070Spatrick
1962e5dd7070Spatrick ThunkInfo Thunk = VTableThunks.lookup(I);
1963e5dd7070Spatrick if (!Thunk.isEmpty()) {
1964e5dd7070Spatrick // If this function pointer has a return adjustment, dump it.
1965e5dd7070Spatrick if (!Thunk.Return.isEmpty()) {
1966e5dd7070Spatrick Out << "\n [return adjustment: ";
1967e5dd7070Spatrick Out << Thunk.Return.NonVirtual << " non-virtual";
1968e5dd7070Spatrick
1969e5dd7070Spatrick if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1970e5dd7070Spatrick Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
1971e5dd7070Spatrick Out << " vbase offset offset";
1972e5dd7070Spatrick }
1973e5dd7070Spatrick
1974e5dd7070Spatrick Out << ']';
1975e5dd7070Spatrick }
1976e5dd7070Spatrick
1977e5dd7070Spatrick // If this function pointer has a 'this' pointer adjustment, dump it.
1978e5dd7070Spatrick if (!Thunk.This.isEmpty()) {
1979e5dd7070Spatrick Out << "\n [this adjustment: ";
1980e5dd7070Spatrick Out << Thunk.This.NonVirtual << " non-virtual";
1981e5dd7070Spatrick
1982e5dd7070Spatrick if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1983e5dd7070Spatrick Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
1984e5dd7070Spatrick Out << " vcall offset offset";
1985e5dd7070Spatrick }
1986e5dd7070Spatrick
1987e5dd7070Spatrick Out << ']';
1988e5dd7070Spatrick }
1989e5dd7070Spatrick }
1990e5dd7070Spatrick
1991e5dd7070Spatrick break;
1992e5dd7070Spatrick }
1993e5dd7070Spatrick
1994e5dd7070Spatrick case VTableComponent::CK_CompleteDtorPointer:
1995e5dd7070Spatrick case VTableComponent::CK_DeletingDtorPointer: {
1996e5dd7070Spatrick bool IsComplete =
1997e5dd7070Spatrick Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1998e5dd7070Spatrick
1999e5dd7070Spatrick const CXXDestructorDecl *DD = Component.getDestructorDecl();
2000e5dd7070Spatrick
2001e5dd7070Spatrick DD->printQualifiedName(Out);
2002e5dd7070Spatrick if (IsComplete)
2003e5dd7070Spatrick Out << "() [complete]";
2004e5dd7070Spatrick else
2005e5dd7070Spatrick Out << "() [deleting]";
2006e5dd7070Spatrick
2007e5dd7070Spatrick if (DD->isPure())
2008e5dd7070Spatrick Out << " [pure]";
2009e5dd7070Spatrick
2010e5dd7070Spatrick ThunkInfo Thunk = VTableThunks.lookup(I);
2011e5dd7070Spatrick if (!Thunk.isEmpty()) {
2012e5dd7070Spatrick // If this destructor has a 'this' pointer adjustment, dump it.
2013e5dd7070Spatrick if (!Thunk.This.isEmpty()) {
2014e5dd7070Spatrick Out << "\n [this adjustment: ";
2015e5dd7070Spatrick Out << Thunk.This.NonVirtual << " non-virtual";
2016e5dd7070Spatrick
2017e5dd7070Spatrick if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2018e5dd7070Spatrick Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2019e5dd7070Spatrick Out << " vcall offset offset";
2020e5dd7070Spatrick }
2021e5dd7070Spatrick
2022e5dd7070Spatrick Out << ']';
2023e5dd7070Spatrick }
2024e5dd7070Spatrick }
2025e5dd7070Spatrick
2026e5dd7070Spatrick break;
2027e5dd7070Spatrick }
2028e5dd7070Spatrick
2029e5dd7070Spatrick case VTableComponent::CK_UnusedFunctionPointer: {
2030e5dd7070Spatrick const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2031e5dd7070Spatrick
2032e5dd7070Spatrick std::string Str =
2033e5dd7070Spatrick PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2034e5dd7070Spatrick MD);
2035e5dd7070Spatrick Out << "[unused] " << Str;
2036e5dd7070Spatrick if (MD->isPure())
2037e5dd7070Spatrick Out << " [pure]";
2038e5dd7070Spatrick }
2039e5dd7070Spatrick
2040e5dd7070Spatrick }
2041e5dd7070Spatrick
2042e5dd7070Spatrick Out << '\n';
2043e5dd7070Spatrick
2044e5dd7070Spatrick // Dump the next address point.
2045e5dd7070Spatrick uint64_t NextIndex = Index + 1;
2046e5dd7070Spatrick if (AddressPointsByIndex.count(NextIndex)) {
2047e5dd7070Spatrick if (AddressPointsByIndex.count(NextIndex) == 1) {
2048e5dd7070Spatrick const BaseSubobject &Base =
2049e5dd7070Spatrick AddressPointsByIndex.find(NextIndex)->second;
2050e5dd7070Spatrick
2051e5dd7070Spatrick Out << " -- (";
2052e5dd7070Spatrick Base.getBase()->printQualifiedName(Out);
2053e5dd7070Spatrick Out << ", " << Base.getBaseOffset().getQuantity();
2054e5dd7070Spatrick Out << ") vtable address --\n";
2055e5dd7070Spatrick } else {
2056e5dd7070Spatrick CharUnits BaseOffset =
2057e5dd7070Spatrick AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2058e5dd7070Spatrick
2059e5dd7070Spatrick // We store the class names in a set to get a stable order.
2060e5dd7070Spatrick std::set<std::string> ClassNames;
2061e5dd7070Spatrick for (const auto &I :
2062e5dd7070Spatrick llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
2063e5dd7070Spatrick assert(I.second.getBaseOffset() == BaseOffset &&
2064e5dd7070Spatrick "Invalid base offset!");
2065e5dd7070Spatrick const CXXRecordDecl *RD = I.second.getBase();
2066e5dd7070Spatrick ClassNames.insert(RD->getQualifiedNameAsString());
2067e5dd7070Spatrick }
2068e5dd7070Spatrick
2069e5dd7070Spatrick for (const std::string &Name : ClassNames) {
2070e5dd7070Spatrick Out << " -- (" << Name;
2071e5dd7070Spatrick Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2072e5dd7070Spatrick }
2073e5dd7070Spatrick }
2074e5dd7070Spatrick }
2075e5dd7070Spatrick }
2076e5dd7070Spatrick
2077e5dd7070Spatrick Out << '\n';
2078e5dd7070Spatrick
2079e5dd7070Spatrick if (isBuildingConstructorVTable())
2080e5dd7070Spatrick return;
2081e5dd7070Spatrick
2082e5dd7070Spatrick if (MostDerivedClass->getNumVBases()) {
2083e5dd7070Spatrick // We store the virtual base class names and their offsets in a map to get
2084e5dd7070Spatrick // a stable order.
2085e5dd7070Spatrick
2086e5dd7070Spatrick std::map<std::string, CharUnits> ClassNamesAndOffsets;
2087e5dd7070Spatrick for (const auto &I : VBaseOffsetOffsets) {
2088e5dd7070Spatrick std::string ClassName = I.first->getQualifiedNameAsString();
2089e5dd7070Spatrick CharUnits OffsetOffset = I.second;
2090e5dd7070Spatrick ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2091e5dd7070Spatrick }
2092e5dd7070Spatrick
2093e5dd7070Spatrick Out << "Virtual base offset offsets for '";
2094e5dd7070Spatrick MostDerivedClass->printQualifiedName(Out);
2095e5dd7070Spatrick Out << "' (";
2096e5dd7070Spatrick Out << ClassNamesAndOffsets.size();
2097e5dd7070Spatrick Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2098e5dd7070Spatrick
2099e5dd7070Spatrick for (const auto &I : ClassNamesAndOffsets)
2100e5dd7070Spatrick Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
2101e5dd7070Spatrick
2102e5dd7070Spatrick Out << "\n";
2103e5dd7070Spatrick }
2104e5dd7070Spatrick
2105e5dd7070Spatrick if (!Thunks.empty()) {
2106e5dd7070Spatrick // We store the method names in a map to get a stable order.
2107e5dd7070Spatrick std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2108e5dd7070Spatrick
2109e5dd7070Spatrick for (const auto &I : Thunks) {
2110e5dd7070Spatrick const CXXMethodDecl *MD = I.first;
2111e5dd7070Spatrick std::string MethodName =
2112e5dd7070Spatrick PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2113e5dd7070Spatrick MD);
2114e5dd7070Spatrick
2115e5dd7070Spatrick MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2116e5dd7070Spatrick }
2117e5dd7070Spatrick
2118e5dd7070Spatrick for (const auto &I : MethodNamesAndDecls) {
2119e5dd7070Spatrick const std::string &MethodName = I.first;
2120e5dd7070Spatrick const CXXMethodDecl *MD = I.second;
2121e5dd7070Spatrick
2122e5dd7070Spatrick ThunkInfoVectorTy ThunksVector = Thunks[MD];
2123e5dd7070Spatrick llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2124e5dd7070Spatrick assert(LHS.Method == nullptr && RHS.Method == nullptr);
2125e5dd7070Spatrick return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
2126e5dd7070Spatrick });
2127e5dd7070Spatrick
2128e5dd7070Spatrick Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2129e5dd7070Spatrick Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2130e5dd7070Spatrick
2131e5dd7070Spatrick for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2132e5dd7070Spatrick const ThunkInfo &Thunk = ThunksVector[I];
2133e5dd7070Spatrick
2134e5dd7070Spatrick Out << llvm::format("%4d | ", I);
2135e5dd7070Spatrick
2136e5dd7070Spatrick // If this function pointer has a return pointer adjustment, dump it.
2137e5dd7070Spatrick if (!Thunk.Return.isEmpty()) {
2138e5dd7070Spatrick Out << "return adjustment: " << Thunk.Return.NonVirtual;
2139e5dd7070Spatrick Out << " non-virtual";
2140e5dd7070Spatrick if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2141e5dd7070Spatrick Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
2142e5dd7070Spatrick Out << " vbase offset offset";
2143e5dd7070Spatrick }
2144e5dd7070Spatrick
2145e5dd7070Spatrick if (!Thunk.This.isEmpty())
2146e5dd7070Spatrick Out << "\n ";
2147e5dd7070Spatrick }
2148e5dd7070Spatrick
2149e5dd7070Spatrick // If this function pointer has a 'this' pointer adjustment, dump it.
2150e5dd7070Spatrick if (!Thunk.This.isEmpty()) {
2151e5dd7070Spatrick Out << "this adjustment: ";
2152e5dd7070Spatrick Out << Thunk.This.NonVirtual << " non-virtual";
2153e5dd7070Spatrick
2154e5dd7070Spatrick if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2155e5dd7070Spatrick Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2156e5dd7070Spatrick Out << " vcall offset offset";
2157e5dd7070Spatrick }
2158e5dd7070Spatrick }
2159e5dd7070Spatrick
2160e5dd7070Spatrick Out << '\n';
2161e5dd7070Spatrick }
2162e5dd7070Spatrick
2163e5dd7070Spatrick Out << '\n';
2164e5dd7070Spatrick }
2165e5dd7070Spatrick }
2166e5dd7070Spatrick
2167e5dd7070Spatrick // Compute the vtable indices for all the member functions.
2168e5dd7070Spatrick // Store them in a map keyed by the index so we'll get a sorted table.
2169e5dd7070Spatrick std::map<uint64_t, std::string> IndicesMap;
2170e5dd7070Spatrick
2171e5dd7070Spatrick for (const auto *MD : MostDerivedClass->methods()) {
2172e5dd7070Spatrick // We only want virtual member functions.
2173ec727ea7Spatrick if (!ItaniumVTableContext::hasVtableSlot(MD))
2174e5dd7070Spatrick continue;
2175e5dd7070Spatrick MD = MD->getCanonicalDecl();
2176e5dd7070Spatrick
2177e5dd7070Spatrick std::string MethodName =
2178e5dd7070Spatrick PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2179e5dd7070Spatrick MD);
2180e5dd7070Spatrick
2181e5dd7070Spatrick if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2182e5dd7070Spatrick GlobalDecl GD(DD, Dtor_Complete);
2183e5dd7070Spatrick assert(MethodVTableIndices.count(GD));
2184e5dd7070Spatrick uint64_t VTableIndex = MethodVTableIndices[GD];
2185e5dd7070Spatrick IndicesMap[VTableIndex] = MethodName + " [complete]";
2186e5dd7070Spatrick IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
2187e5dd7070Spatrick } else {
2188e5dd7070Spatrick assert(MethodVTableIndices.count(MD));
2189e5dd7070Spatrick IndicesMap[MethodVTableIndices[MD]] = MethodName;
2190e5dd7070Spatrick }
2191e5dd7070Spatrick }
2192e5dd7070Spatrick
2193e5dd7070Spatrick // Print the vtable indices for all the member functions.
2194e5dd7070Spatrick if (!IndicesMap.empty()) {
2195e5dd7070Spatrick Out << "VTable indices for '";
2196e5dd7070Spatrick MostDerivedClass->printQualifiedName(Out);
2197e5dd7070Spatrick Out << "' (" << IndicesMap.size() << " entries).\n";
2198e5dd7070Spatrick
2199e5dd7070Spatrick for (const auto &I : IndicesMap) {
2200e5dd7070Spatrick uint64_t VTableIndex = I.first;
2201e5dd7070Spatrick const std::string &MethodName = I.second;
2202e5dd7070Spatrick
2203e5dd7070Spatrick Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
2204e5dd7070Spatrick << '\n';
2205e5dd7070Spatrick }
2206e5dd7070Spatrick }
2207e5dd7070Spatrick
2208e5dd7070Spatrick Out << '\n';
2209e5dd7070Spatrick }
2210e5dd7070Spatrick }
2211e5dd7070Spatrick
2212ec727ea7Spatrick static VTableLayout::AddressPointsIndexMapTy
MakeAddressPointIndices(const VTableLayout::AddressPointsMapTy & addressPoints,unsigned numVTables)2213ec727ea7Spatrick MakeAddressPointIndices(const VTableLayout::AddressPointsMapTy &addressPoints,
2214ec727ea7Spatrick unsigned numVTables) {
2215ec727ea7Spatrick VTableLayout::AddressPointsIndexMapTy indexMap(numVTables);
2216ec727ea7Spatrick
2217ec727ea7Spatrick for (auto it = addressPoints.begin(); it != addressPoints.end(); ++it) {
2218ec727ea7Spatrick const auto &addressPointLoc = it->second;
2219ec727ea7Spatrick unsigned vtableIndex = addressPointLoc.VTableIndex;
2220ec727ea7Spatrick unsigned addressPoint = addressPointLoc.AddressPointIndex;
2221ec727ea7Spatrick if (indexMap[vtableIndex]) {
2222ec727ea7Spatrick // Multiple BaseSubobjects can map to the same AddressPointLocation, but
2223ec727ea7Spatrick // every vtable index should have a unique address point.
2224ec727ea7Spatrick assert(indexMap[vtableIndex] == addressPoint &&
2225ec727ea7Spatrick "Every vtable index should have a unique address point. Found a "
2226ec727ea7Spatrick "vtable that has two different address points.");
2227ec727ea7Spatrick } else {
2228ec727ea7Spatrick indexMap[vtableIndex] = addressPoint;
2229ec727ea7Spatrick }
2230ec727ea7Spatrick }
2231ec727ea7Spatrick
2232ec727ea7Spatrick // Note that by this point, not all the address may be initialized if the
2233ec727ea7Spatrick // AddressPoints map is empty. This is ok if the map isn't needed. See
2234ec727ea7Spatrick // MicrosoftVTableContext::computeVTableRelatedInformation() which uses an
2235ec727ea7Spatrick // emprt map.
2236ec727ea7Spatrick return indexMap;
2237ec727ea7Spatrick }
2238ec727ea7Spatrick
VTableLayout(ArrayRef<size_t> VTableIndices,ArrayRef<VTableComponent> VTableComponents,ArrayRef<VTableThunkTy> VTableThunks,const AddressPointsMapTy & AddressPoints)2239e5dd7070Spatrick VTableLayout::VTableLayout(ArrayRef<size_t> VTableIndices,
2240e5dd7070Spatrick ArrayRef<VTableComponent> VTableComponents,
2241e5dd7070Spatrick ArrayRef<VTableThunkTy> VTableThunks,
2242e5dd7070Spatrick const AddressPointsMapTy &AddressPoints)
2243e5dd7070Spatrick : VTableComponents(VTableComponents), VTableThunks(VTableThunks),
2244ec727ea7Spatrick AddressPoints(AddressPoints), AddressPointIndices(MakeAddressPointIndices(
2245ec727ea7Spatrick AddressPoints, VTableIndices.size())) {
2246e5dd7070Spatrick if (VTableIndices.size() <= 1)
2247e5dd7070Spatrick assert(VTableIndices.size() == 1 && VTableIndices[0] == 0);
2248e5dd7070Spatrick else
2249e5dd7070Spatrick this->VTableIndices = OwningArrayRef<size_t>(VTableIndices);
2250e5dd7070Spatrick
2251e5dd7070Spatrick llvm::sort(this->VTableThunks, [](const VTableLayout::VTableThunkTy &LHS,
2252e5dd7070Spatrick const VTableLayout::VTableThunkTy &RHS) {
2253e5dd7070Spatrick assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2254e5dd7070Spatrick "Different thunks should have unique indices!");
2255e5dd7070Spatrick return LHS.first < RHS.first;
2256e5dd7070Spatrick });
2257e5dd7070Spatrick }
2258e5dd7070Spatrick
~VTableLayout()2259e5dd7070Spatrick VTableLayout::~VTableLayout() { }
2260e5dd7070Spatrick
hasVtableSlot(const CXXMethodDecl * MD)2261ec727ea7Spatrick bool VTableContextBase::hasVtableSlot(const CXXMethodDecl *MD) {
2262ec727ea7Spatrick return MD->isVirtual() && !MD->isConsteval();
2263ec727ea7Spatrick }
2264ec727ea7Spatrick
ItaniumVTableContext(ASTContext & Context,VTableComponentLayout ComponentLayout)2265ec727ea7Spatrick ItaniumVTableContext::ItaniumVTableContext(
2266ec727ea7Spatrick ASTContext &Context, VTableComponentLayout ComponentLayout)
2267ec727ea7Spatrick : VTableContextBase(/*MS=*/false), ComponentLayout(ComponentLayout) {}
2268e5dd7070Spatrick
~ItaniumVTableContext()2269e5dd7070Spatrick ItaniumVTableContext::~ItaniumVTableContext() {}
2270e5dd7070Spatrick
getMethodVTableIndex(GlobalDecl GD)2271e5dd7070Spatrick uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
2272e5dd7070Spatrick GD = GD.getCanonicalDecl();
2273e5dd7070Spatrick MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2274e5dd7070Spatrick if (I != MethodVTableIndices.end())
2275e5dd7070Spatrick return I->second;
2276e5dd7070Spatrick
2277e5dd7070Spatrick const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2278e5dd7070Spatrick
2279e5dd7070Spatrick computeVTableRelatedInformation(RD);
2280e5dd7070Spatrick
2281e5dd7070Spatrick I = MethodVTableIndices.find(GD);
2282e5dd7070Spatrick assert(I != MethodVTableIndices.end() && "Did not find index!");
2283e5dd7070Spatrick return I->second;
2284e5dd7070Spatrick }
2285e5dd7070Spatrick
2286e5dd7070Spatrick CharUnits
getVirtualBaseOffsetOffset(const CXXRecordDecl * RD,const CXXRecordDecl * VBase)2287e5dd7070Spatrick ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2288e5dd7070Spatrick const CXXRecordDecl *VBase) {
2289e5dd7070Spatrick ClassPairTy ClassPair(RD, VBase);
2290e5dd7070Spatrick
2291e5dd7070Spatrick VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2292e5dd7070Spatrick VirtualBaseClassOffsetOffsets.find(ClassPair);
2293e5dd7070Spatrick if (I != VirtualBaseClassOffsetOffsets.end())
2294e5dd7070Spatrick return I->second;
2295e5dd7070Spatrick
2296ec727ea7Spatrick VCallAndVBaseOffsetBuilder Builder(*this, RD, RD, /*Overriders=*/nullptr,
2297e5dd7070Spatrick BaseSubobject(RD, CharUnits::Zero()),
2298e5dd7070Spatrick /*BaseIsVirtual=*/false,
2299e5dd7070Spatrick /*OffsetInLayoutClass=*/CharUnits::Zero());
2300e5dd7070Spatrick
2301e5dd7070Spatrick for (const auto &I : Builder.getVBaseOffsetOffsets()) {
2302e5dd7070Spatrick // Insert all types.
2303e5dd7070Spatrick ClassPairTy ClassPair(RD, I.first);
2304e5dd7070Spatrick
2305e5dd7070Spatrick VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
2306e5dd7070Spatrick }
2307e5dd7070Spatrick
2308e5dd7070Spatrick I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2309e5dd7070Spatrick assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2310e5dd7070Spatrick
2311e5dd7070Spatrick return I->second;
2312e5dd7070Spatrick }
2313e5dd7070Spatrick
2314e5dd7070Spatrick static std::unique_ptr<VTableLayout>
CreateVTableLayout(const ItaniumVTableBuilder & Builder)2315e5dd7070Spatrick CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
2316e5dd7070Spatrick SmallVector<VTableLayout::VTableThunkTy, 1>
2317e5dd7070Spatrick VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2318e5dd7070Spatrick
2319e5dd7070Spatrick return std::make_unique<VTableLayout>(
2320e5dd7070Spatrick Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
2321e5dd7070Spatrick Builder.getAddressPoints());
2322e5dd7070Spatrick }
2323e5dd7070Spatrick
2324e5dd7070Spatrick void
computeVTableRelatedInformation(const CXXRecordDecl * RD)2325e5dd7070Spatrick ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
2326e5dd7070Spatrick std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
2327e5dd7070Spatrick
2328e5dd7070Spatrick // Check if we've computed this information before.
2329e5dd7070Spatrick if (Entry)
2330e5dd7070Spatrick return;
2331e5dd7070Spatrick
2332e5dd7070Spatrick ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2333*12c85518Srobert /*MostDerivedClassIsVirtual=*/false, RD);
2334e5dd7070Spatrick Entry = CreateVTableLayout(Builder);
2335e5dd7070Spatrick
2336e5dd7070Spatrick MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2337e5dd7070Spatrick Builder.vtable_indices_end());
2338e5dd7070Spatrick
2339e5dd7070Spatrick // Add the known thunks.
2340e5dd7070Spatrick Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2341e5dd7070Spatrick
2342e5dd7070Spatrick // If we don't have the vbase information for this class, insert it.
2343e5dd7070Spatrick // getVirtualBaseOffsetOffset will compute it separately without computing
2344e5dd7070Spatrick // the rest of the vtable related information.
2345e5dd7070Spatrick if (!RD->getNumVBases())
2346e5dd7070Spatrick return;
2347e5dd7070Spatrick
2348e5dd7070Spatrick const CXXRecordDecl *VBase =
2349e5dd7070Spatrick RD->vbases_begin()->getType()->getAsCXXRecordDecl();
2350e5dd7070Spatrick
2351e5dd7070Spatrick if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2352e5dd7070Spatrick return;
2353e5dd7070Spatrick
2354e5dd7070Spatrick for (const auto &I : Builder.getVBaseOffsetOffsets()) {
2355e5dd7070Spatrick // Insert all types.
2356e5dd7070Spatrick ClassPairTy ClassPair(RD, I.first);
2357e5dd7070Spatrick
2358e5dd7070Spatrick VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
2359e5dd7070Spatrick }
2360e5dd7070Spatrick }
2361e5dd7070Spatrick
2362e5dd7070Spatrick std::unique_ptr<VTableLayout>
createConstructionVTableLayout(const CXXRecordDecl * MostDerivedClass,CharUnits MostDerivedClassOffset,bool MostDerivedClassIsVirtual,const CXXRecordDecl * LayoutClass)2363e5dd7070Spatrick ItaniumVTableContext::createConstructionVTableLayout(
2364e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2365e5dd7070Spatrick bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2366e5dd7070Spatrick ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2367e5dd7070Spatrick MostDerivedClassIsVirtual, LayoutClass);
2368e5dd7070Spatrick return CreateVTableLayout(Builder);
2369e5dd7070Spatrick }
2370e5dd7070Spatrick
2371e5dd7070Spatrick namespace {
2372e5dd7070Spatrick
2373e5dd7070Spatrick // Vtables in the Microsoft ABI are different from the Itanium ABI.
2374e5dd7070Spatrick //
2375e5dd7070Spatrick // The main differences are:
2376e5dd7070Spatrick // 1. Separate vftable and vbtable.
2377e5dd7070Spatrick //
2378e5dd7070Spatrick // 2. Each subobject with a vfptr gets its own vftable rather than an address
2379e5dd7070Spatrick // point in a single vtable shared between all the subobjects.
2380e5dd7070Spatrick // Each vftable is represented by a separate section and virtual calls
2381e5dd7070Spatrick // must be done using the vftable which has a slot for the function to be
2382e5dd7070Spatrick // called.
2383e5dd7070Spatrick //
2384e5dd7070Spatrick // 3. Virtual method definitions expect their 'this' parameter to point to the
2385e5dd7070Spatrick // first vfptr whose table provides a compatible overridden method. In many
2386e5dd7070Spatrick // cases, this permits the original vf-table entry to directly call
2387e5dd7070Spatrick // the method instead of passing through a thunk.
2388e5dd7070Spatrick // See example before VFTableBuilder::ComputeThisOffset below.
2389e5dd7070Spatrick //
2390e5dd7070Spatrick // A compatible overridden method is one which does not have a non-trivial
2391e5dd7070Spatrick // covariant-return adjustment.
2392e5dd7070Spatrick //
2393e5dd7070Spatrick // The first vfptr is the one with the lowest offset in the complete-object
2394e5dd7070Spatrick // layout of the defining class, and the method definition will subtract
2395e5dd7070Spatrick // that constant offset from the parameter value to get the real 'this'
2396e5dd7070Spatrick // value. Therefore, if the offset isn't really constant (e.g. if a virtual
2397e5dd7070Spatrick // function defined in a virtual base is overridden in a more derived
2398e5dd7070Spatrick // virtual base and these bases have a reverse order in the complete
2399e5dd7070Spatrick // object), the vf-table may require a this-adjustment thunk.
2400e5dd7070Spatrick //
2401e5dd7070Spatrick // 4. vftables do not contain new entries for overrides that merely require
2402e5dd7070Spatrick // this-adjustment. Together with #3, this keeps vf-tables smaller and
2403e5dd7070Spatrick // eliminates the need for this-adjustment thunks in many cases, at the cost
2404e5dd7070Spatrick // of often requiring redundant work to adjust the "this" pointer.
2405e5dd7070Spatrick //
2406e5dd7070Spatrick // 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2407e5dd7070Spatrick // Vtordisps are emitted into the class layout if a class has
2408e5dd7070Spatrick // a) a user-defined ctor/dtor
2409e5dd7070Spatrick // and
2410e5dd7070Spatrick // b) a method overriding a method in a virtual base.
2411e5dd7070Spatrick //
2412e5dd7070Spatrick // To get a better understanding of this code,
2413e5dd7070Spatrick // you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
2414e5dd7070Spatrick
2415e5dd7070Spatrick class VFTableBuilder {
2416e5dd7070Spatrick public:
2417e5dd7070Spatrick typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2418e5dd7070Spatrick MethodVFTableLocationsTy;
2419e5dd7070Spatrick
2420e5dd7070Spatrick typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2421e5dd7070Spatrick method_locations_range;
2422e5dd7070Spatrick
2423e5dd7070Spatrick private:
2424e5dd7070Spatrick /// VTables - Global vtable information.
2425e5dd7070Spatrick MicrosoftVTableContext &VTables;
2426e5dd7070Spatrick
2427e5dd7070Spatrick /// Context - The ASTContext which we will use for layout information.
2428e5dd7070Spatrick ASTContext &Context;
2429e5dd7070Spatrick
2430e5dd7070Spatrick /// MostDerivedClass - The most derived class for which we're building this
2431e5dd7070Spatrick /// vtable.
2432e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass;
2433e5dd7070Spatrick
2434e5dd7070Spatrick const ASTRecordLayout &MostDerivedClassLayout;
2435e5dd7070Spatrick
2436e5dd7070Spatrick const VPtrInfo &WhichVFPtr;
2437e5dd7070Spatrick
2438e5dd7070Spatrick /// FinalOverriders - The final overriders of the most derived class.
2439e5dd7070Spatrick const FinalOverriders Overriders;
2440e5dd7070Spatrick
2441e5dd7070Spatrick /// Components - The components of the vftable being built.
2442e5dd7070Spatrick SmallVector<VTableComponent, 64> Components;
2443e5dd7070Spatrick
2444e5dd7070Spatrick MethodVFTableLocationsTy MethodVFTableLocations;
2445e5dd7070Spatrick
2446e5dd7070Spatrick /// Does this class have an RTTI component?
2447e5dd7070Spatrick bool HasRTTIComponent = false;
2448e5dd7070Spatrick
2449e5dd7070Spatrick /// MethodInfo - Contains information about a method in a vtable.
2450e5dd7070Spatrick /// (Used for computing 'this' pointer adjustment thunks.
2451e5dd7070Spatrick struct MethodInfo {
2452e5dd7070Spatrick /// VBTableIndex - The nonzero index in the vbtable that
2453e5dd7070Spatrick /// this method's base has, or zero.
2454e5dd7070Spatrick const uint64_t VBTableIndex;
2455e5dd7070Spatrick
2456e5dd7070Spatrick /// VFTableIndex - The index in the vftable that this method has.
2457e5dd7070Spatrick const uint64_t VFTableIndex;
2458e5dd7070Spatrick
2459e5dd7070Spatrick /// Shadowed - Indicates if this vftable slot is shadowed by
2460e5dd7070Spatrick /// a slot for a covariant-return override. If so, it shouldn't be printed
2461e5dd7070Spatrick /// or used for vcalls in the most derived class.
2462e5dd7070Spatrick bool Shadowed;
2463e5dd7070Spatrick
2464e5dd7070Spatrick /// UsesExtraSlot - Indicates if this vftable slot was created because
2465e5dd7070Spatrick /// any of the overridden slots required a return adjusting thunk.
2466e5dd7070Spatrick bool UsesExtraSlot;
2467e5dd7070Spatrick
MethodInfo__anon8b019dcd0611::VFTableBuilder::MethodInfo2468e5dd7070Spatrick MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2469e5dd7070Spatrick bool UsesExtraSlot = false)
2470e5dd7070Spatrick : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2471e5dd7070Spatrick Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2472e5dd7070Spatrick
MethodInfo__anon8b019dcd0611::VFTableBuilder::MethodInfo2473e5dd7070Spatrick MethodInfo()
2474e5dd7070Spatrick : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2475e5dd7070Spatrick UsesExtraSlot(false) {}
2476e5dd7070Spatrick };
2477e5dd7070Spatrick
2478e5dd7070Spatrick typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2479e5dd7070Spatrick
2480e5dd7070Spatrick /// MethodInfoMap - The information for all methods in the vftable we're
2481e5dd7070Spatrick /// currently building.
2482e5dd7070Spatrick MethodInfoMapTy MethodInfoMap;
2483e5dd7070Spatrick
2484e5dd7070Spatrick typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2485e5dd7070Spatrick
2486e5dd7070Spatrick /// VTableThunks - The thunks by vftable index in the vftable currently being
2487e5dd7070Spatrick /// built.
2488e5dd7070Spatrick VTableThunksMapTy VTableThunks;
2489e5dd7070Spatrick
2490e5dd7070Spatrick typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2491e5dd7070Spatrick typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2492e5dd7070Spatrick
2493e5dd7070Spatrick /// Thunks - A map that contains all the thunks needed for all methods in the
2494e5dd7070Spatrick /// most derived class for which the vftable is currently being built.
2495e5dd7070Spatrick ThunksMapTy Thunks;
2496e5dd7070Spatrick
2497e5dd7070Spatrick /// AddThunk - Add a thunk for the given method.
AddThunk(const CXXMethodDecl * MD,const ThunkInfo & Thunk)2498e5dd7070Spatrick void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2499e5dd7070Spatrick SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2500e5dd7070Spatrick
2501e5dd7070Spatrick // Check if we have this thunk already.
2502*12c85518Srobert if (llvm::is_contained(ThunksVector, Thunk))
2503e5dd7070Spatrick return;
2504e5dd7070Spatrick
2505e5dd7070Spatrick ThunksVector.push_back(Thunk);
2506e5dd7070Spatrick }
2507e5dd7070Spatrick
2508e5dd7070Spatrick /// ComputeThisOffset - Returns the 'this' argument offset for the given
2509e5dd7070Spatrick /// method, relative to the beginning of the MostDerivedClass.
2510e5dd7070Spatrick CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
2511e5dd7070Spatrick
2512e5dd7070Spatrick void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2513e5dd7070Spatrick CharUnits ThisOffset, ThisAdjustment &TA);
2514e5dd7070Spatrick
2515e5dd7070Spatrick /// AddMethod - Add a single virtual member function to the vftable
2516e5dd7070Spatrick /// components vector.
AddMethod(const CXXMethodDecl * MD,ThunkInfo TI)2517e5dd7070Spatrick void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
2518e5dd7070Spatrick if (!TI.isEmpty()) {
2519e5dd7070Spatrick VTableThunks[Components.size()] = TI;
2520e5dd7070Spatrick AddThunk(MD, TI);
2521e5dd7070Spatrick }
2522e5dd7070Spatrick if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2523e5dd7070Spatrick assert(TI.Return.isEmpty() &&
2524e5dd7070Spatrick "Destructor can't have return adjustment!");
2525e5dd7070Spatrick Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2526e5dd7070Spatrick } else {
2527e5dd7070Spatrick Components.push_back(VTableComponent::MakeFunction(MD));
2528e5dd7070Spatrick }
2529e5dd7070Spatrick }
2530e5dd7070Spatrick
2531e5dd7070Spatrick /// AddMethods - Add the methods of this base subobject and the relevant
2532e5dd7070Spatrick /// subbases to the vftable we're currently laying out.
2533e5dd7070Spatrick void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2534e5dd7070Spatrick const CXXRecordDecl *LastVBase,
2535e5dd7070Spatrick BasesSetVectorTy &VisitedBases);
2536e5dd7070Spatrick
LayoutVFTable()2537e5dd7070Spatrick void LayoutVFTable() {
2538e5dd7070Spatrick // RTTI data goes before all other entries.
2539e5dd7070Spatrick if (HasRTTIComponent)
2540e5dd7070Spatrick Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
2541e5dd7070Spatrick
2542e5dd7070Spatrick BasesSetVectorTy VisitedBases;
2543e5dd7070Spatrick AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
2544e5dd7070Spatrick VisitedBases);
2545ec727ea7Spatrick // Note that it is possible for the vftable to contain only an RTTI
2546ec727ea7Spatrick // pointer, if all virtual functions are constewval.
2547ec727ea7Spatrick assert(!Components.empty() && "vftable can't be empty");
2548e5dd7070Spatrick
2549e5dd7070Spatrick assert(MethodVFTableLocations.empty());
2550e5dd7070Spatrick for (const auto &I : MethodInfoMap) {
2551e5dd7070Spatrick const CXXMethodDecl *MD = I.first;
2552e5dd7070Spatrick const MethodInfo &MI = I.second;
2553e5dd7070Spatrick assert(MD == MD->getCanonicalDecl());
2554e5dd7070Spatrick
2555e5dd7070Spatrick // Skip the methods that the MostDerivedClass didn't override
2556e5dd7070Spatrick // and the entries shadowed by return adjusting thunks.
2557e5dd7070Spatrick if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2558e5dd7070Spatrick continue;
2559e5dd7070Spatrick MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2560e5dd7070Spatrick WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
2561e5dd7070Spatrick if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2562e5dd7070Spatrick MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2563e5dd7070Spatrick } else {
2564e5dd7070Spatrick MethodVFTableLocations[MD] = Loc;
2565e5dd7070Spatrick }
2566e5dd7070Spatrick }
2567e5dd7070Spatrick }
2568e5dd7070Spatrick
2569e5dd7070Spatrick public:
VFTableBuilder(MicrosoftVTableContext & VTables,const CXXRecordDecl * MostDerivedClass,const VPtrInfo & Which)2570e5dd7070Spatrick VFTableBuilder(MicrosoftVTableContext &VTables,
2571e5dd7070Spatrick const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
2572e5dd7070Spatrick : VTables(VTables),
2573e5dd7070Spatrick Context(MostDerivedClass->getASTContext()),
2574e5dd7070Spatrick MostDerivedClass(MostDerivedClass),
2575e5dd7070Spatrick MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2576e5dd7070Spatrick WhichVFPtr(Which),
2577e5dd7070Spatrick Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2578e5dd7070Spatrick // Provide the RTTI component if RTTIData is enabled. If the vftable would
2579e5dd7070Spatrick // be available externally, we should not provide the RTTI componenent. It
2580e5dd7070Spatrick // is currently impossible to get available externally vftables with either
2581e5dd7070Spatrick // dllimport or extern template instantiations, but eventually we may add a
2582e5dd7070Spatrick // flag to support additional devirtualization that needs this.
2583e5dd7070Spatrick if (Context.getLangOpts().RTTIData)
2584e5dd7070Spatrick HasRTTIComponent = true;
2585e5dd7070Spatrick
2586e5dd7070Spatrick LayoutVFTable();
2587e5dd7070Spatrick
2588e5dd7070Spatrick if (Context.getLangOpts().DumpVTableLayouts)
2589e5dd7070Spatrick dumpLayout(llvm::outs());
2590e5dd7070Spatrick }
2591e5dd7070Spatrick
getNumThunks() const2592e5dd7070Spatrick uint64_t getNumThunks() const { return Thunks.size(); }
2593e5dd7070Spatrick
thunks_begin() const2594e5dd7070Spatrick ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2595e5dd7070Spatrick
thunks_end() const2596e5dd7070Spatrick ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2597e5dd7070Spatrick
vtable_locations() const2598e5dd7070Spatrick method_locations_range vtable_locations() const {
2599e5dd7070Spatrick return method_locations_range(MethodVFTableLocations.begin(),
2600e5dd7070Spatrick MethodVFTableLocations.end());
2601e5dd7070Spatrick }
2602e5dd7070Spatrick
vtable_components() const2603e5dd7070Spatrick ArrayRef<VTableComponent> vtable_components() const { return Components; }
2604e5dd7070Spatrick
vtable_thunks_begin() const2605e5dd7070Spatrick VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2606e5dd7070Spatrick return VTableThunks.begin();
2607e5dd7070Spatrick }
2608e5dd7070Spatrick
vtable_thunks_end() const2609e5dd7070Spatrick VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2610e5dd7070Spatrick return VTableThunks.end();
2611e5dd7070Spatrick }
2612e5dd7070Spatrick
2613e5dd7070Spatrick void dumpLayout(raw_ostream &);
2614e5dd7070Spatrick };
2615e5dd7070Spatrick
2616e5dd7070Spatrick } // end namespace
2617e5dd7070Spatrick
2618e5dd7070Spatrick // Let's study one class hierarchy as an example:
2619e5dd7070Spatrick // struct A {
2620e5dd7070Spatrick // virtual void f();
2621e5dd7070Spatrick // int x;
2622e5dd7070Spatrick // };
2623e5dd7070Spatrick //
2624e5dd7070Spatrick // struct B : virtual A {
2625e5dd7070Spatrick // virtual void f();
2626e5dd7070Spatrick // };
2627e5dd7070Spatrick //
2628e5dd7070Spatrick // Record layouts:
2629e5dd7070Spatrick // struct A:
2630e5dd7070Spatrick // 0 | (A vftable pointer)
2631e5dd7070Spatrick // 4 | int x
2632e5dd7070Spatrick //
2633e5dd7070Spatrick // struct B:
2634e5dd7070Spatrick // 0 | (B vbtable pointer)
2635e5dd7070Spatrick // 4 | struct A (virtual base)
2636e5dd7070Spatrick // 4 | (A vftable pointer)
2637e5dd7070Spatrick // 8 | int x
2638e5dd7070Spatrick //
2639e5dd7070Spatrick // Let's assume we have a pointer to the A part of an object of dynamic type B:
2640e5dd7070Spatrick // B b;
2641e5dd7070Spatrick // A *a = (A*)&b;
2642e5dd7070Spatrick // a->f();
2643e5dd7070Spatrick //
2644e5dd7070Spatrick // In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2645e5dd7070Spatrick // "this" parameter to point at the A subobject, which is B+4.
2646e5dd7070Spatrick // In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
2647e5dd7070Spatrick // performed as a *static* adjustment.
2648e5dd7070Spatrick //
2649e5dd7070Spatrick // Interesting thing happens when we alter the relative placement of A and B
2650e5dd7070Spatrick // subobjects in a class:
2651e5dd7070Spatrick // struct C : virtual B { };
2652e5dd7070Spatrick //
2653e5dd7070Spatrick // C c;
2654e5dd7070Spatrick // A *a = (A*)&c;
2655e5dd7070Spatrick // a->f();
2656e5dd7070Spatrick //
2657e5dd7070Spatrick // Respective record layout is:
2658e5dd7070Spatrick // 0 | (C vbtable pointer)
2659e5dd7070Spatrick // 4 | struct A (virtual base)
2660e5dd7070Spatrick // 4 | (A vftable pointer)
2661e5dd7070Spatrick // 8 | int x
2662e5dd7070Spatrick // 12 | struct B (virtual base)
2663e5dd7070Spatrick // 12 | (B vbtable pointer)
2664e5dd7070Spatrick //
2665e5dd7070Spatrick // The final overrider of f() in class C is still B::f(), so B+4 should be
2666e5dd7070Spatrick // passed as "this" to that code. However, "a" points at B-8, so the respective
2667e5dd7070Spatrick // vftable entry should hold a thunk that adds 12 to the "this" argument before
2668e5dd7070Spatrick // performing a tail call to B::f().
2669e5dd7070Spatrick //
2670e5dd7070Spatrick // With this example in mind, we can now calculate the 'this' argument offset
2671e5dd7070Spatrick // for the given method, relative to the beginning of the MostDerivedClass.
2672e5dd7070Spatrick CharUnits
ComputeThisOffset(FinalOverriders::OverriderInfo Overrider)2673e5dd7070Spatrick VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
2674e5dd7070Spatrick BasesSetVectorTy Bases;
2675e5dd7070Spatrick
2676e5dd7070Spatrick {
2677e5dd7070Spatrick // Find the set of least derived bases that define the given method.
2678e5dd7070Spatrick OverriddenMethodsSetTy VisitedOverriddenMethods;
2679e5dd7070Spatrick auto InitialOverriddenDefinitionCollector = [&](
2680e5dd7070Spatrick const CXXMethodDecl *OverriddenMD) {
2681e5dd7070Spatrick if (OverriddenMD->size_overridden_methods() == 0)
2682e5dd7070Spatrick Bases.insert(OverriddenMD->getParent());
2683e5dd7070Spatrick // Don't recurse on this method if we've already collected it.
2684e5dd7070Spatrick return VisitedOverriddenMethods.insert(OverriddenMD).second;
2685e5dd7070Spatrick };
2686e5dd7070Spatrick visitAllOverriddenMethods(Overrider.Method,
2687e5dd7070Spatrick InitialOverriddenDefinitionCollector);
2688e5dd7070Spatrick }
2689e5dd7070Spatrick
2690e5dd7070Spatrick // If there are no overrides then 'this' is located
2691e5dd7070Spatrick // in the base that defines the method.
2692e5dd7070Spatrick if (Bases.size() == 0)
2693e5dd7070Spatrick return Overrider.Offset;
2694e5dd7070Spatrick
2695e5dd7070Spatrick CXXBasePaths Paths;
2696e5dd7070Spatrick Overrider.Method->getParent()->lookupInBases(
2697e5dd7070Spatrick [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
2698e5dd7070Spatrick return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
2699e5dd7070Spatrick },
2700e5dd7070Spatrick Paths);
2701e5dd7070Spatrick
2702e5dd7070Spatrick // This will hold the smallest this offset among overridees of MD.
2703e5dd7070Spatrick // This implies that an offset of a non-virtual base will dominate an offset
2704e5dd7070Spatrick // of a virtual base to potentially reduce the number of thunks required
2705e5dd7070Spatrick // in the derived classes that inherit this method.
2706e5dd7070Spatrick CharUnits Ret;
2707e5dd7070Spatrick bool First = true;
2708e5dd7070Spatrick
2709e5dd7070Spatrick const ASTRecordLayout &OverriderRDLayout =
2710e5dd7070Spatrick Context.getASTRecordLayout(Overrider.Method->getParent());
2711e5dd7070Spatrick for (const CXXBasePath &Path : Paths) {
2712e5dd7070Spatrick CharUnits ThisOffset = Overrider.Offset;
2713e5dd7070Spatrick CharUnits LastVBaseOffset;
2714e5dd7070Spatrick
2715e5dd7070Spatrick // For each path from the overrider to the parents of the overridden
2716e5dd7070Spatrick // methods, traverse the path, calculating the this offset in the most
2717e5dd7070Spatrick // derived class.
2718e5dd7070Spatrick for (const CXXBasePathElement &Element : Path) {
2719e5dd7070Spatrick QualType CurTy = Element.Base->getType();
2720e5dd7070Spatrick const CXXRecordDecl *PrevRD = Element.Class,
2721e5dd7070Spatrick *CurRD = CurTy->getAsCXXRecordDecl();
2722e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2723e5dd7070Spatrick
2724e5dd7070Spatrick if (Element.Base->isVirtual()) {
2725e5dd7070Spatrick // The interesting things begin when you have virtual inheritance.
2726e5dd7070Spatrick // The final overrider will use a static adjustment equal to the offset
2727e5dd7070Spatrick // of the vbase in the final overrider class.
2728e5dd7070Spatrick // For example, if the final overrider is in a vbase B of the most
2729e5dd7070Spatrick // derived class and it overrides a method of the B's own vbase A,
2730e5dd7070Spatrick // it uses A* as "this". In its prologue, it can cast A* to B* with
2731e5dd7070Spatrick // a static offset. This offset is used regardless of the actual
2732e5dd7070Spatrick // offset of A from B in the most derived class, requiring an
2733e5dd7070Spatrick // this-adjusting thunk in the vftable if A and B are laid out
2734e5dd7070Spatrick // differently in the most derived class.
2735e5dd7070Spatrick LastVBaseOffset = ThisOffset =
2736e5dd7070Spatrick Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
2737e5dd7070Spatrick } else {
2738e5dd7070Spatrick ThisOffset += Layout.getBaseClassOffset(CurRD);
2739e5dd7070Spatrick }
2740e5dd7070Spatrick }
2741e5dd7070Spatrick
2742e5dd7070Spatrick if (isa<CXXDestructorDecl>(Overrider.Method)) {
2743e5dd7070Spatrick if (LastVBaseOffset.isZero()) {
2744e5dd7070Spatrick // If a "Base" class has at least one non-virtual base with a virtual
2745e5dd7070Spatrick // destructor, the "Base" virtual destructor will take the address
2746e5dd7070Spatrick // of the "Base" subobject as the "this" argument.
2747e5dd7070Spatrick ThisOffset = Overrider.Offset;
2748e5dd7070Spatrick } else {
2749e5dd7070Spatrick // A virtual destructor of a virtual base takes the address of the
2750e5dd7070Spatrick // virtual base subobject as the "this" argument.
2751e5dd7070Spatrick ThisOffset = LastVBaseOffset;
2752e5dd7070Spatrick }
2753e5dd7070Spatrick }
2754e5dd7070Spatrick
2755e5dd7070Spatrick if (Ret > ThisOffset || First) {
2756e5dd7070Spatrick First = false;
2757e5dd7070Spatrick Ret = ThisOffset;
2758e5dd7070Spatrick }
2759e5dd7070Spatrick }
2760e5dd7070Spatrick
2761e5dd7070Spatrick assert(!First && "Method not found in the given subobject?");
2762e5dd7070Spatrick return Ret;
2763e5dd7070Spatrick }
2764e5dd7070Spatrick
2765e5dd7070Spatrick // Things are getting even more complex when the "this" adjustment has to
2766e5dd7070Spatrick // use a dynamic offset instead of a static one, or even two dynamic offsets.
2767e5dd7070Spatrick // This is sometimes required when a virtual call happens in the middle of
2768e5dd7070Spatrick // a non-most-derived class construction or destruction.
2769e5dd7070Spatrick //
2770e5dd7070Spatrick // Let's take a look at the following example:
2771e5dd7070Spatrick // struct A {
2772e5dd7070Spatrick // virtual void f();
2773e5dd7070Spatrick // };
2774e5dd7070Spatrick //
2775e5dd7070Spatrick // void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
2776e5dd7070Spatrick //
2777e5dd7070Spatrick // struct B : virtual A {
2778e5dd7070Spatrick // virtual void f();
2779e5dd7070Spatrick // B() {
2780e5dd7070Spatrick // foo(this);
2781e5dd7070Spatrick // }
2782e5dd7070Spatrick // };
2783e5dd7070Spatrick //
2784e5dd7070Spatrick // struct C : virtual B {
2785e5dd7070Spatrick // virtual void f();
2786e5dd7070Spatrick // };
2787e5dd7070Spatrick //
2788e5dd7070Spatrick // Record layouts for these classes are:
2789e5dd7070Spatrick // struct A
2790e5dd7070Spatrick // 0 | (A vftable pointer)
2791e5dd7070Spatrick //
2792e5dd7070Spatrick // struct B
2793e5dd7070Spatrick // 0 | (B vbtable pointer)
2794e5dd7070Spatrick // 4 | (vtordisp for vbase A)
2795e5dd7070Spatrick // 8 | struct A (virtual base)
2796e5dd7070Spatrick // 8 | (A vftable pointer)
2797e5dd7070Spatrick //
2798e5dd7070Spatrick // struct C
2799e5dd7070Spatrick // 0 | (C vbtable pointer)
2800e5dd7070Spatrick // 4 | (vtordisp for vbase A)
2801e5dd7070Spatrick // 8 | struct A (virtual base) // A precedes B!
2802e5dd7070Spatrick // 8 | (A vftable pointer)
2803e5dd7070Spatrick // 12 | struct B (virtual base)
2804e5dd7070Spatrick // 12 | (B vbtable pointer)
2805e5dd7070Spatrick //
2806e5dd7070Spatrick // When one creates an object of type C, the C constructor:
2807e5dd7070Spatrick // - initializes all the vbptrs, then
2808e5dd7070Spatrick // - calls the A subobject constructor
2809e5dd7070Spatrick // (initializes A's vfptr with an address of A vftable), then
2810e5dd7070Spatrick // - calls the B subobject constructor
2811e5dd7070Spatrick // (initializes A's vfptr with an address of B vftable and vtordisp for A),
2812e5dd7070Spatrick // that in turn calls foo(), then
2813e5dd7070Spatrick // - initializes A's vfptr with an address of C vftable and zeroes out the
2814e5dd7070Spatrick // vtordisp
2815e5dd7070Spatrick // FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2816e5dd7070Spatrick // without vtordisp thunks?
2817e5dd7070Spatrick // FIXME: how are vtordisp handled in the presence of nooverride/final?
2818e5dd7070Spatrick //
2819e5dd7070Spatrick // When foo() is called, an object with a layout of class C has a vftable
2820e5dd7070Spatrick // referencing B::f() that assumes a B layout, so the "this" adjustments are
2821e5dd7070Spatrick // incorrect, unless an extra adjustment is done. This adjustment is called
2822e5dd7070Spatrick // "vtordisp adjustment". Vtordisp basically holds the difference between the
2823e5dd7070Spatrick // actual location of a vbase in the layout class and the location assumed by
2824e5dd7070Spatrick // the vftable of the class being constructed/destructed. Vtordisp is only
2825e5dd7070Spatrick // needed if "this" escapes a
2826e5dd7070Spatrick // structor (or we can't prove otherwise).
2827e5dd7070Spatrick // [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2828e5dd7070Spatrick // estimation of a dynamic adjustment]
2829e5dd7070Spatrick //
2830e5dd7070Spatrick // foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2831e5dd7070Spatrick // so it just passes that pointer as "this" in a virtual call.
2832e5dd7070Spatrick // If there was no vtordisp, that would just dispatch to B::f().
2833e5dd7070Spatrick // However, B::f() assumes B+8 is passed as "this",
2834e5dd7070Spatrick // yet the pointer foo() passes along is B-4 (i.e. C+8).
2835e5dd7070Spatrick // An extra adjustment is needed, so we emit a thunk into the B vftable.
2836e5dd7070Spatrick // This vtordisp thunk subtracts the value of vtordisp
2837e5dd7070Spatrick // from the "this" argument (-12) before making a tailcall to B::f().
2838e5dd7070Spatrick //
2839e5dd7070Spatrick // Let's consider an even more complex example:
2840e5dd7070Spatrick // struct D : virtual B, virtual C {
2841e5dd7070Spatrick // D() {
2842e5dd7070Spatrick // foo(this);
2843e5dd7070Spatrick // }
2844e5dd7070Spatrick // };
2845e5dd7070Spatrick //
2846e5dd7070Spatrick // struct D
2847e5dd7070Spatrick // 0 | (D vbtable pointer)
2848e5dd7070Spatrick // 4 | (vtordisp for vbase A)
2849e5dd7070Spatrick // 8 | struct A (virtual base) // A precedes both B and C!
2850e5dd7070Spatrick // 8 | (A vftable pointer)
2851e5dd7070Spatrick // 12 | struct B (virtual base) // B precedes C!
2852e5dd7070Spatrick // 12 | (B vbtable pointer)
2853e5dd7070Spatrick // 16 | struct C (virtual base)
2854e5dd7070Spatrick // 16 | (C vbtable pointer)
2855e5dd7070Spatrick //
2856e5dd7070Spatrick // When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2857e5dd7070Spatrick // to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
2858e5dd7070Spatrick // passes along A, which is C-8. The A vtordisp holds
2859e5dd7070Spatrick // "D.vbptr[index_of_A] - offset_of_A_in_D"
2860e5dd7070Spatrick // and we statically know offset_of_A_in_D, so can get a pointer to D.
2861e5dd7070Spatrick // When we know it, we can make an extra vbtable lookup to locate the C vbase
2862e5dd7070Spatrick // and one extra static adjustment to calculate the expected value of C+8.
CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,CharUnits ThisOffset,ThisAdjustment & TA)2863e5dd7070Spatrick void VFTableBuilder::CalculateVtordispAdjustment(
2864e5dd7070Spatrick FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2865e5dd7070Spatrick ThisAdjustment &TA) {
2866e5dd7070Spatrick const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2867e5dd7070Spatrick MostDerivedClassLayout.getVBaseOffsetsMap();
2868e5dd7070Spatrick const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
2869e5dd7070Spatrick VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
2870e5dd7070Spatrick assert(VBaseMapEntry != VBaseMap.end());
2871e5dd7070Spatrick
2872e5dd7070Spatrick // If there's no vtordisp or the final overrider is defined in the same vbase
2873e5dd7070Spatrick // as the initial declaration, we don't need any vtordisp adjustment.
2874e5dd7070Spatrick if (!VBaseMapEntry->second.hasVtorDisp() ||
2875e5dd7070Spatrick Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
2876e5dd7070Spatrick return;
2877e5dd7070Spatrick
2878e5dd7070Spatrick // OK, now we know we need to use a vtordisp thunk.
2879e5dd7070Spatrick // The implicit vtordisp field is located right before the vbase.
2880e5dd7070Spatrick CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
2881e5dd7070Spatrick TA.Virtual.Microsoft.VtordispOffset =
2882e5dd7070Spatrick (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
2883e5dd7070Spatrick
2884e5dd7070Spatrick // A simple vtordisp thunk will suffice if the final overrider is defined
2885e5dd7070Spatrick // in either the most derived class or its non-virtual base.
2886e5dd7070Spatrick if (Overrider.Method->getParent() == MostDerivedClass ||
2887e5dd7070Spatrick !Overrider.VirtualBase)
2888e5dd7070Spatrick return;
2889e5dd7070Spatrick
2890e5dd7070Spatrick // Otherwise, we need to do use the dynamic offset of the final overrider
2891e5dd7070Spatrick // in order to get "this" adjustment right.
2892e5dd7070Spatrick TA.Virtual.Microsoft.VBPtrOffset =
2893e5dd7070Spatrick (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
2894e5dd7070Spatrick MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2895e5dd7070Spatrick TA.Virtual.Microsoft.VBOffsetOffset =
2896e5dd7070Spatrick Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2897e5dd7070Spatrick VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
2898e5dd7070Spatrick
2899e5dd7070Spatrick TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2900e5dd7070Spatrick }
2901e5dd7070Spatrick
GroupNewVirtualOverloads(const CXXRecordDecl * RD,SmallVector<const CXXMethodDecl *,10> & VirtualMethods)2902e5dd7070Spatrick static void GroupNewVirtualOverloads(
2903e5dd7070Spatrick const CXXRecordDecl *RD,
2904e5dd7070Spatrick SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2905e5dd7070Spatrick // Put the virtual methods into VirtualMethods in the proper order:
2906e5dd7070Spatrick // 1) Group overloads by declaration name. New groups are added to the
2907e5dd7070Spatrick // vftable in the order of their first declarations in this class
2908e5dd7070Spatrick // (including overrides, non-virtual methods and any other named decl that
2909e5dd7070Spatrick // might be nested within the class).
2910e5dd7070Spatrick // 2) In each group, new overloads appear in the reverse order of declaration.
2911e5dd7070Spatrick typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2912e5dd7070Spatrick SmallVector<MethodGroup, 10> Groups;
2913e5dd7070Spatrick typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2914e5dd7070Spatrick VisitedGroupIndicesTy VisitedGroupIndices;
2915e5dd7070Spatrick for (const auto *D : RD->decls()) {
2916e5dd7070Spatrick const auto *ND = dyn_cast<NamedDecl>(D);
2917e5dd7070Spatrick if (!ND)
2918e5dd7070Spatrick continue;
2919e5dd7070Spatrick VisitedGroupIndicesTy::iterator J;
2920e5dd7070Spatrick bool Inserted;
2921e5dd7070Spatrick std::tie(J, Inserted) = VisitedGroupIndices.insert(
2922e5dd7070Spatrick std::make_pair(ND->getDeclName(), Groups.size()));
2923e5dd7070Spatrick if (Inserted)
2924e5dd7070Spatrick Groups.push_back(MethodGroup());
2925e5dd7070Spatrick if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
2926ec727ea7Spatrick if (MicrosoftVTableContext::hasVtableSlot(MD))
2927e5dd7070Spatrick Groups[J->second].push_back(MD->getCanonicalDecl());
2928e5dd7070Spatrick }
2929e5dd7070Spatrick
2930e5dd7070Spatrick for (const MethodGroup &Group : Groups)
2931e5dd7070Spatrick VirtualMethods.append(Group.rbegin(), Group.rend());
2932e5dd7070Spatrick }
2933e5dd7070Spatrick
isDirectVBase(const CXXRecordDecl * Base,const CXXRecordDecl * RD)2934e5dd7070Spatrick static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2935e5dd7070Spatrick for (const auto &B : RD->bases()) {
2936e5dd7070Spatrick if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2937e5dd7070Spatrick return true;
2938e5dd7070Spatrick }
2939e5dd7070Spatrick return false;
2940e5dd7070Spatrick }
2941e5dd7070Spatrick
AddMethods(BaseSubobject Base,unsigned BaseDepth,const CXXRecordDecl * LastVBase,BasesSetVectorTy & VisitedBases)2942e5dd7070Spatrick void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2943e5dd7070Spatrick const CXXRecordDecl *LastVBase,
2944e5dd7070Spatrick BasesSetVectorTy &VisitedBases) {
2945e5dd7070Spatrick const CXXRecordDecl *RD = Base.getBase();
2946e5dd7070Spatrick if (!RD->isPolymorphic())
2947e5dd7070Spatrick return;
2948e5dd7070Spatrick
2949e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2950e5dd7070Spatrick
2951e5dd7070Spatrick // See if this class expands a vftable of the base we look at, which is either
2952e5dd7070Spatrick // the one defined by the vfptr base path or the primary base of the current
2953e5dd7070Spatrick // class.
2954e5dd7070Spatrick const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
2955e5dd7070Spatrick CharUnits NextBaseOffset;
2956e5dd7070Spatrick if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
2957e5dd7070Spatrick NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
2958e5dd7070Spatrick if (isDirectVBase(NextBase, RD)) {
2959e5dd7070Spatrick NextLastVBase = NextBase;
2960e5dd7070Spatrick NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2961e5dd7070Spatrick } else {
2962e5dd7070Spatrick NextBaseOffset =
2963e5dd7070Spatrick Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2964e5dd7070Spatrick }
2965e5dd7070Spatrick } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2966e5dd7070Spatrick assert(!Layout.isPrimaryBaseVirtual() &&
2967e5dd7070Spatrick "No primary virtual bases in this ABI");
2968e5dd7070Spatrick NextBase = PrimaryBase;
2969e5dd7070Spatrick NextBaseOffset = Base.getBaseOffset();
2970e5dd7070Spatrick }
2971e5dd7070Spatrick
2972e5dd7070Spatrick if (NextBase) {
2973e5dd7070Spatrick AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2974e5dd7070Spatrick NextLastVBase, VisitedBases);
2975e5dd7070Spatrick if (!VisitedBases.insert(NextBase))
2976e5dd7070Spatrick llvm_unreachable("Found a duplicate primary base!");
2977e5dd7070Spatrick }
2978e5dd7070Spatrick
2979e5dd7070Spatrick SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2980e5dd7070Spatrick // Put virtual methods in the proper order.
2981e5dd7070Spatrick GroupNewVirtualOverloads(RD, VirtualMethods);
2982e5dd7070Spatrick
2983e5dd7070Spatrick // Now go through all virtual member functions and add them to the current
2984e5dd7070Spatrick // vftable. This is done by
2985e5dd7070Spatrick // - replacing overridden methods in their existing slots, as long as they
2986e5dd7070Spatrick // don't require return adjustment; calculating This adjustment if needed.
2987e5dd7070Spatrick // - adding new slots for methods of the current base not present in any
2988e5dd7070Spatrick // sub-bases;
2989e5dd7070Spatrick // - adding new slots for methods that require Return adjustment.
2990e5dd7070Spatrick // We keep track of the methods visited in the sub-bases in MethodInfoMap.
2991e5dd7070Spatrick for (const CXXMethodDecl *MD : VirtualMethods) {
2992e5dd7070Spatrick FinalOverriders::OverriderInfo FinalOverrider =
2993e5dd7070Spatrick Overriders.getOverrider(MD, Base.getBaseOffset());
2994e5dd7070Spatrick const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
2995e5dd7070Spatrick const CXXMethodDecl *OverriddenMD =
2996e5dd7070Spatrick FindNearestOverriddenMethod(MD, VisitedBases);
2997e5dd7070Spatrick
2998e5dd7070Spatrick ThisAdjustment ThisAdjustmentOffset;
2999e5dd7070Spatrick bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
3000e5dd7070Spatrick CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
3001e5dd7070Spatrick ThisAdjustmentOffset.NonVirtual =
3002e5dd7070Spatrick (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
3003e5dd7070Spatrick if ((OverriddenMD || FinalOverriderMD != MD) &&
3004e5dd7070Spatrick WhichVFPtr.getVBaseWithVPtr())
3005e5dd7070Spatrick CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
3006e5dd7070Spatrick ThisAdjustmentOffset);
3007e5dd7070Spatrick
3008e5dd7070Spatrick unsigned VBIndex =
3009e5dd7070Spatrick LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
3010e5dd7070Spatrick
3011e5dd7070Spatrick if (OverriddenMD) {
3012e5dd7070Spatrick // If MD overrides anything in this vftable, we need to update the
3013e5dd7070Spatrick // entries.
3014e5dd7070Spatrick MethodInfoMapTy::iterator OverriddenMDIterator =
3015e5dd7070Spatrick MethodInfoMap.find(OverriddenMD);
3016e5dd7070Spatrick
3017e5dd7070Spatrick // If the overridden method went to a different vftable, skip it.
3018e5dd7070Spatrick if (OverriddenMDIterator == MethodInfoMap.end())
3019e5dd7070Spatrick continue;
3020e5dd7070Spatrick
3021e5dd7070Spatrick MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
3022e5dd7070Spatrick
3023e5dd7070Spatrick VBIndex = OverriddenMethodInfo.VBTableIndex;
3024e5dd7070Spatrick
3025e5dd7070Spatrick // Let's check if the overrider requires any return adjustments.
3026e5dd7070Spatrick // We must create a new slot if the MD's return type is not trivially
3027e5dd7070Spatrick // convertible to the OverriddenMD's one.
3028e5dd7070Spatrick // Once a chain of method overrides adds a return adjusting vftable slot,
3029e5dd7070Spatrick // all subsequent overrides will also use an extra method slot.
3030e5dd7070Spatrick ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
3031e5dd7070Spatrick Context, MD, OverriddenMD).isEmpty() ||
3032e5dd7070Spatrick OverriddenMethodInfo.UsesExtraSlot;
3033e5dd7070Spatrick
3034e5dd7070Spatrick if (!ReturnAdjustingThunk) {
3035e5dd7070Spatrick // No return adjustment needed - just replace the overridden method info
3036e5dd7070Spatrick // with the current info.
3037e5dd7070Spatrick MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
3038e5dd7070Spatrick MethodInfoMap.erase(OverriddenMDIterator);
3039e5dd7070Spatrick
3040e5dd7070Spatrick assert(!MethodInfoMap.count(MD) &&
3041e5dd7070Spatrick "Should not have method info for this method yet!");
3042e5dd7070Spatrick MethodInfoMap.insert(std::make_pair(MD, MI));
3043e5dd7070Spatrick continue;
3044e5dd7070Spatrick }
3045e5dd7070Spatrick
3046e5dd7070Spatrick // In case we need a return adjustment, we'll add a new slot for
3047e5dd7070Spatrick // the overrider. Mark the overridden method as shadowed by the new slot.
3048e5dd7070Spatrick OverriddenMethodInfo.Shadowed = true;
3049e5dd7070Spatrick
3050e5dd7070Spatrick // Force a special name mangling for a return-adjusting thunk
3051e5dd7070Spatrick // unless the method is the final overrider without this adjustment.
3052e5dd7070Spatrick ForceReturnAdjustmentMangling =
3053e5dd7070Spatrick !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
3054e5dd7070Spatrick } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
3055e5dd7070Spatrick MD->size_overridden_methods()) {
3056e5dd7070Spatrick // Skip methods that don't belong to the vftable of the current class,
3057e5dd7070Spatrick // e.g. each method that wasn't seen in any of the visited sub-bases
3058e5dd7070Spatrick // but overrides multiple methods of other sub-bases.
3059e5dd7070Spatrick continue;
3060e5dd7070Spatrick }
3061e5dd7070Spatrick
3062e5dd7070Spatrick // If we got here, MD is a method not seen in any of the sub-bases or
3063e5dd7070Spatrick // it requires return adjustment. Insert the method info for this method.
3064e5dd7070Spatrick MethodInfo MI(VBIndex,
3065e5dd7070Spatrick HasRTTIComponent ? Components.size() - 1 : Components.size(),
3066e5dd7070Spatrick ReturnAdjustingThunk);
3067e5dd7070Spatrick
3068e5dd7070Spatrick assert(!MethodInfoMap.count(MD) &&
3069e5dd7070Spatrick "Should not have method info for this method yet!");
3070e5dd7070Spatrick MethodInfoMap.insert(std::make_pair(MD, MI));
3071e5dd7070Spatrick
3072e5dd7070Spatrick // Check if this overrider needs a return adjustment.
3073e5dd7070Spatrick // We don't want to do this for pure virtual member functions.
3074e5dd7070Spatrick BaseOffset ReturnAdjustmentOffset;
3075e5dd7070Spatrick ReturnAdjustment ReturnAdjustment;
3076e5dd7070Spatrick if (!FinalOverriderMD->isPure()) {
3077e5dd7070Spatrick ReturnAdjustmentOffset =
3078e5dd7070Spatrick ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
3079e5dd7070Spatrick }
3080e5dd7070Spatrick if (!ReturnAdjustmentOffset.isEmpty()) {
3081e5dd7070Spatrick ForceReturnAdjustmentMangling = true;
3082e5dd7070Spatrick ReturnAdjustment.NonVirtual =
3083e5dd7070Spatrick ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3084e5dd7070Spatrick if (ReturnAdjustmentOffset.VirtualBase) {
3085e5dd7070Spatrick const ASTRecordLayout &DerivedLayout =
3086e5dd7070Spatrick Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3087e5dd7070Spatrick ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
3088e5dd7070Spatrick DerivedLayout.getVBPtrOffset().getQuantity();
3089e5dd7070Spatrick ReturnAdjustment.Virtual.Microsoft.VBIndex =
3090e5dd7070Spatrick VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3091e5dd7070Spatrick ReturnAdjustmentOffset.VirtualBase);
3092e5dd7070Spatrick }
3093e5dd7070Spatrick }
3094e5dd7070Spatrick
3095e5dd7070Spatrick AddMethod(FinalOverriderMD,
3096e5dd7070Spatrick ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3097e5dd7070Spatrick ForceReturnAdjustmentMangling ? MD : nullptr));
3098e5dd7070Spatrick }
3099e5dd7070Spatrick }
3100e5dd7070Spatrick
PrintBasePath(const VPtrInfo::BasePath & Path,raw_ostream & Out)3101e5dd7070Spatrick static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
3102*12c85518Srobert for (const CXXRecordDecl *Elem : llvm::reverse(Path)) {
3103e5dd7070Spatrick Out << "'";
3104e5dd7070Spatrick Elem->printQualifiedName(Out);
3105e5dd7070Spatrick Out << "' in ";
3106e5dd7070Spatrick }
3107e5dd7070Spatrick }
3108e5dd7070Spatrick
dumpMicrosoftThunkAdjustment(const ThunkInfo & TI,raw_ostream & Out,bool ContinueFirstLine)3109e5dd7070Spatrick static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3110e5dd7070Spatrick bool ContinueFirstLine) {
3111e5dd7070Spatrick const ReturnAdjustment &R = TI.Return;
3112e5dd7070Spatrick bool Multiline = false;
3113e5dd7070Spatrick const char *LinePrefix = "\n ";
3114e5dd7070Spatrick if (!R.isEmpty() || TI.Method) {
3115e5dd7070Spatrick if (!ContinueFirstLine)
3116e5dd7070Spatrick Out << LinePrefix;
3117e5dd7070Spatrick Out << "[return adjustment (to type '"
3118*12c85518Srobert << TI.Method->getReturnType().getCanonicalType() << "'): ";
3119e5dd7070Spatrick if (R.Virtual.Microsoft.VBPtrOffset)
3120e5dd7070Spatrick Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3121e5dd7070Spatrick if (R.Virtual.Microsoft.VBIndex)
3122e5dd7070Spatrick Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3123e5dd7070Spatrick Out << R.NonVirtual << " non-virtual]";
3124e5dd7070Spatrick Multiline = true;
3125e5dd7070Spatrick }
3126e5dd7070Spatrick
3127e5dd7070Spatrick const ThisAdjustment &T = TI.This;
3128e5dd7070Spatrick if (!T.isEmpty()) {
3129e5dd7070Spatrick if (Multiline || !ContinueFirstLine)
3130e5dd7070Spatrick Out << LinePrefix;
3131e5dd7070Spatrick Out << "[this adjustment: ";
3132e5dd7070Spatrick if (!TI.This.Virtual.isEmpty()) {
3133e5dd7070Spatrick assert(T.Virtual.Microsoft.VtordispOffset < 0);
3134e5dd7070Spatrick Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3135e5dd7070Spatrick if (T.Virtual.Microsoft.VBPtrOffset) {
3136e5dd7070Spatrick Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
3137e5dd7070Spatrick << " to the left,";
3138e5dd7070Spatrick assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3139e5dd7070Spatrick Out << LinePrefix << " vboffset at "
3140e5dd7070Spatrick << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3141e5dd7070Spatrick }
3142e5dd7070Spatrick }
3143e5dd7070Spatrick Out << T.NonVirtual << " non-virtual]";
3144e5dd7070Spatrick }
3145e5dd7070Spatrick }
3146e5dd7070Spatrick
dumpLayout(raw_ostream & Out)3147e5dd7070Spatrick void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3148e5dd7070Spatrick Out << "VFTable for ";
3149e5dd7070Spatrick PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
3150e5dd7070Spatrick Out << "'";
3151e5dd7070Spatrick MostDerivedClass->printQualifiedName(Out);
3152e5dd7070Spatrick Out << "' (" << Components.size()
3153e5dd7070Spatrick << (Components.size() == 1 ? " entry" : " entries") << ").\n";
3154e5dd7070Spatrick
3155e5dd7070Spatrick for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3156e5dd7070Spatrick Out << llvm::format("%4d | ", I);
3157e5dd7070Spatrick
3158e5dd7070Spatrick const VTableComponent &Component = Components[I];
3159e5dd7070Spatrick
3160e5dd7070Spatrick // Dump the component.
3161e5dd7070Spatrick switch (Component.getKind()) {
3162e5dd7070Spatrick case VTableComponent::CK_RTTI:
3163e5dd7070Spatrick Component.getRTTIDecl()->printQualifiedName(Out);
3164e5dd7070Spatrick Out << " RTTI";
3165e5dd7070Spatrick break;
3166e5dd7070Spatrick
3167e5dd7070Spatrick case VTableComponent::CK_FunctionPointer: {
3168e5dd7070Spatrick const CXXMethodDecl *MD = Component.getFunctionDecl();
3169e5dd7070Spatrick
3170e5dd7070Spatrick // FIXME: Figure out how to print the real thunk type, since they can
3171e5dd7070Spatrick // differ in the return type.
3172e5dd7070Spatrick std::string Str = PredefinedExpr::ComputeName(
3173e5dd7070Spatrick PredefinedExpr::PrettyFunctionNoVirtual, MD);
3174e5dd7070Spatrick Out << Str;
3175e5dd7070Spatrick if (MD->isPure())
3176e5dd7070Spatrick Out << " [pure]";
3177e5dd7070Spatrick
3178e5dd7070Spatrick if (MD->isDeleted())
3179e5dd7070Spatrick Out << " [deleted]";
3180e5dd7070Spatrick
3181e5dd7070Spatrick ThunkInfo Thunk = VTableThunks.lookup(I);
3182e5dd7070Spatrick if (!Thunk.isEmpty())
3183e5dd7070Spatrick dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3184e5dd7070Spatrick
3185e5dd7070Spatrick break;
3186e5dd7070Spatrick }
3187e5dd7070Spatrick
3188e5dd7070Spatrick case VTableComponent::CK_DeletingDtorPointer: {
3189e5dd7070Spatrick const CXXDestructorDecl *DD = Component.getDestructorDecl();
3190e5dd7070Spatrick
3191e5dd7070Spatrick DD->printQualifiedName(Out);
3192e5dd7070Spatrick Out << "() [scalar deleting]";
3193e5dd7070Spatrick
3194e5dd7070Spatrick if (DD->isPure())
3195e5dd7070Spatrick Out << " [pure]";
3196e5dd7070Spatrick
3197e5dd7070Spatrick ThunkInfo Thunk = VTableThunks.lookup(I);
3198e5dd7070Spatrick if (!Thunk.isEmpty()) {
3199e5dd7070Spatrick assert(Thunk.Return.isEmpty() &&
3200e5dd7070Spatrick "No return adjustment needed for destructors!");
3201e5dd7070Spatrick dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3202e5dd7070Spatrick }
3203e5dd7070Spatrick
3204e5dd7070Spatrick break;
3205e5dd7070Spatrick }
3206e5dd7070Spatrick
3207e5dd7070Spatrick default:
3208e5dd7070Spatrick DiagnosticsEngine &Diags = Context.getDiagnostics();
3209e5dd7070Spatrick unsigned DiagID = Diags.getCustomDiagID(
3210e5dd7070Spatrick DiagnosticsEngine::Error,
3211e5dd7070Spatrick "Unexpected vftable component type %0 for component number %1");
3212e5dd7070Spatrick Diags.Report(MostDerivedClass->getLocation(), DiagID)
3213e5dd7070Spatrick << I << Component.getKind();
3214e5dd7070Spatrick }
3215e5dd7070Spatrick
3216e5dd7070Spatrick Out << '\n';
3217e5dd7070Spatrick }
3218e5dd7070Spatrick
3219e5dd7070Spatrick Out << '\n';
3220e5dd7070Spatrick
3221e5dd7070Spatrick if (!Thunks.empty()) {
3222e5dd7070Spatrick // We store the method names in a map to get a stable order.
3223e5dd7070Spatrick std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3224e5dd7070Spatrick
3225e5dd7070Spatrick for (const auto &I : Thunks) {
3226e5dd7070Spatrick const CXXMethodDecl *MD = I.first;
3227e5dd7070Spatrick std::string MethodName = PredefinedExpr::ComputeName(
3228e5dd7070Spatrick PredefinedExpr::PrettyFunctionNoVirtual, MD);
3229e5dd7070Spatrick
3230e5dd7070Spatrick MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3231e5dd7070Spatrick }
3232e5dd7070Spatrick
3233e5dd7070Spatrick for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
3234e5dd7070Spatrick const std::string &MethodName = MethodNameAndDecl.first;
3235e5dd7070Spatrick const CXXMethodDecl *MD = MethodNameAndDecl.second;
3236e5dd7070Spatrick
3237e5dd7070Spatrick ThunkInfoVectorTy ThunksVector = Thunks[MD];
3238e5dd7070Spatrick llvm::stable_sort(ThunksVector, [](const ThunkInfo &LHS,
3239e5dd7070Spatrick const ThunkInfo &RHS) {
3240e5dd7070Spatrick // Keep different thunks with the same adjustments in the order they
3241e5dd7070Spatrick // were put into the vector.
3242e5dd7070Spatrick return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
3243e5dd7070Spatrick });
3244e5dd7070Spatrick
3245e5dd7070Spatrick Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3246e5dd7070Spatrick Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3247e5dd7070Spatrick
3248e5dd7070Spatrick for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3249e5dd7070Spatrick const ThunkInfo &Thunk = ThunksVector[I];
3250e5dd7070Spatrick
3251e5dd7070Spatrick Out << llvm::format("%4d | ", I);
3252e5dd7070Spatrick dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
3253e5dd7070Spatrick Out << '\n';
3254e5dd7070Spatrick }
3255e5dd7070Spatrick
3256e5dd7070Spatrick Out << '\n';
3257e5dd7070Spatrick }
3258e5dd7070Spatrick }
3259e5dd7070Spatrick
3260e5dd7070Spatrick Out.flush();
3261e5dd7070Spatrick }
3262e5dd7070Spatrick
setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *,4> & A,ArrayRef<const CXXRecordDecl * > B)3263e5dd7070Spatrick static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3264e5dd7070Spatrick ArrayRef<const CXXRecordDecl *> B) {
3265e5dd7070Spatrick for (const CXXRecordDecl *Decl : B) {
3266e5dd7070Spatrick if (A.count(Decl))
3267e5dd7070Spatrick return true;
3268e5dd7070Spatrick }
3269e5dd7070Spatrick return false;
3270e5dd7070Spatrick }
3271e5dd7070Spatrick
3272e5dd7070Spatrick static bool rebucketPaths(VPtrInfoVector &Paths);
3273e5dd7070Spatrick
3274e5dd7070Spatrick /// Produces MSVC-compatible vbtable data. The symbols produced by this
3275e5dd7070Spatrick /// algorithm match those produced by MSVC 2012 and newer, which is different
3276e5dd7070Spatrick /// from MSVC 2010.
3277e5dd7070Spatrick ///
3278e5dd7070Spatrick /// MSVC 2012 appears to minimize the vbtable names using the following
3279e5dd7070Spatrick /// algorithm. First, walk the class hierarchy in the usual order, depth first,
3280e5dd7070Spatrick /// left to right, to find all of the subobjects which contain a vbptr field.
3281e5dd7070Spatrick /// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3282e5dd7070Spatrick /// record with a vbptr creates an initially empty path.
3283e5dd7070Spatrick ///
3284e5dd7070Spatrick /// To combine paths from child nodes, the paths are compared to check for
3285e5dd7070Spatrick /// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3286e5dd7070Spatrick /// components in the same order. Each group of ambiguous paths is extended by
3287e5dd7070Spatrick /// appending the class of the base from which it came. If the current class
3288e5dd7070Spatrick /// node produced an ambiguous path, its path is extended with the current class.
3289e5dd7070Spatrick /// After extending paths, MSVC again checks for ambiguity, and extends any
3290e5dd7070Spatrick /// ambiguous path which wasn't already extended. Because each node yields an
3291e5dd7070Spatrick /// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3292e5dd7070Spatrick /// to produce an unambiguous set of paths.
3293e5dd7070Spatrick ///
3294e5dd7070Spatrick /// TODO: Presumably vftables use the same algorithm.
computeVTablePaths(bool ForVBTables,const CXXRecordDecl * RD,VPtrInfoVector & Paths)3295e5dd7070Spatrick void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3296e5dd7070Spatrick const CXXRecordDecl *RD,
3297e5dd7070Spatrick VPtrInfoVector &Paths) {
3298e5dd7070Spatrick assert(Paths.empty());
3299e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3300e5dd7070Spatrick
3301e5dd7070Spatrick // Base case: this subobject has its own vptr.
3302e5dd7070Spatrick if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3303e5dd7070Spatrick Paths.push_back(std::make_unique<VPtrInfo>(RD));
3304e5dd7070Spatrick
3305e5dd7070Spatrick // Recursive case: get all the vbtables from our bases and remove anything
3306e5dd7070Spatrick // that shares a virtual base.
3307e5dd7070Spatrick llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
3308e5dd7070Spatrick for (const auto &B : RD->bases()) {
3309e5dd7070Spatrick const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3310e5dd7070Spatrick if (B.isVirtual() && VBasesSeen.count(Base))
3311e5dd7070Spatrick continue;
3312e5dd7070Spatrick
3313e5dd7070Spatrick if (!Base->isDynamicClass())
3314e5dd7070Spatrick continue;
3315e5dd7070Spatrick
3316e5dd7070Spatrick const VPtrInfoVector &BasePaths =
3317e5dd7070Spatrick ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3318e5dd7070Spatrick
3319e5dd7070Spatrick for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
3320e5dd7070Spatrick // Don't include the path if it goes through a virtual base that we've
3321e5dd7070Spatrick // already included.
3322e5dd7070Spatrick if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
3323e5dd7070Spatrick continue;
3324e5dd7070Spatrick
3325e5dd7070Spatrick // Copy the path and adjust it as necessary.
3326e5dd7070Spatrick auto P = std::make_unique<VPtrInfo>(*BaseInfo);
3327e5dd7070Spatrick
3328e5dd7070Spatrick // We mangle Base into the path if the path would've been ambiguous and it
3329e5dd7070Spatrick // wasn't already extended with Base.
3330e5dd7070Spatrick if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3331e5dd7070Spatrick P->NextBaseToMangle = Base;
3332e5dd7070Spatrick
3333e5dd7070Spatrick // Keep track of which vtable the derived class is going to extend with
3334e5dd7070Spatrick // new methods or bases. We append to either the vftable of our primary
3335e5dd7070Spatrick // base, or the first non-virtual base that has a vbtable.
3336e5dd7070Spatrick if (P->ObjectWithVPtr == Base &&
3337e5dd7070Spatrick Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3338e5dd7070Spatrick : Layout.getPrimaryBase()))
3339e5dd7070Spatrick P->ObjectWithVPtr = RD;
3340e5dd7070Spatrick
3341e5dd7070Spatrick // Keep track of the full adjustment from the MDC to this vtable. The
3342e5dd7070Spatrick // adjustment is captured by an optional vbase and a non-virtual offset.
3343e5dd7070Spatrick if (B.isVirtual())
3344e5dd7070Spatrick P->ContainingVBases.push_back(Base);
3345e5dd7070Spatrick else if (P->ContainingVBases.empty())
3346e5dd7070Spatrick P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3347e5dd7070Spatrick
3348e5dd7070Spatrick // Update the full offset in the MDC.
3349e5dd7070Spatrick P->FullOffsetInMDC = P->NonVirtualOffset;
3350e5dd7070Spatrick if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3351e5dd7070Spatrick P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3352e5dd7070Spatrick
3353e5dd7070Spatrick Paths.push_back(std::move(P));
3354e5dd7070Spatrick }
3355e5dd7070Spatrick
3356e5dd7070Spatrick if (B.isVirtual())
3357e5dd7070Spatrick VBasesSeen.insert(Base);
3358e5dd7070Spatrick
3359e5dd7070Spatrick // After visiting any direct base, we've transitively visited all of its
3360e5dd7070Spatrick // morally virtual bases.
3361e5dd7070Spatrick for (const auto &VB : Base->vbases())
3362e5dd7070Spatrick VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
3363e5dd7070Spatrick }
3364e5dd7070Spatrick
3365e5dd7070Spatrick // Sort the paths into buckets, and if any of them are ambiguous, extend all
3366e5dd7070Spatrick // paths in ambiguous buckets.
3367e5dd7070Spatrick bool Changed = true;
3368e5dd7070Spatrick while (Changed)
3369e5dd7070Spatrick Changed = rebucketPaths(Paths);
3370e5dd7070Spatrick }
3371e5dd7070Spatrick
extendPath(VPtrInfo & P)3372e5dd7070Spatrick static bool extendPath(VPtrInfo &P) {
3373e5dd7070Spatrick if (P.NextBaseToMangle) {
3374e5dd7070Spatrick P.MangledPath.push_back(P.NextBaseToMangle);
3375e5dd7070Spatrick P.NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
3376e5dd7070Spatrick return true;
3377e5dd7070Spatrick }
3378e5dd7070Spatrick return false;
3379e5dd7070Spatrick }
3380e5dd7070Spatrick
rebucketPaths(VPtrInfoVector & Paths)3381e5dd7070Spatrick static bool rebucketPaths(VPtrInfoVector &Paths) {
3382e5dd7070Spatrick // What we're essentially doing here is bucketing together ambiguous paths.
3383e5dd7070Spatrick // Any bucket with more than one path in it gets extended by NextBase, which
3384e5dd7070Spatrick // is usually the direct base of the inherited the vbptr. This code uses a
3385e5dd7070Spatrick // sorted vector to implement a multiset to form the buckets. Note that the
3386e5dd7070Spatrick // ordering is based on pointers, but it doesn't change our output order. The
3387e5dd7070Spatrick // current algorithm is designed to match MSVC 2012's names.
3388*12c85518Srobert llvm::SmallVector<std::reference_wrapper<VPtrInfo>, 2> PathsSorted(
3389*12c85518Srobert llvm::make_pointee_range(Paths));
3390e5dd7070Spatrick llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
3391e5dd7070Spatrick return LHS.MangledPath < RHS.MangledPath;
3392e5dd7070Spatrick });
3393e5dd7070Spatrick bool Changed = false;
3394e5dd7070Spatrick for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3395e5dd7070Spatrick // Scan forward to find the end of the bucket.
3396e5dd7070Spatrick size_t BucketStart = I;
3397e5dd7070Spatrick do {
3398e5dd7070Spatrick ++I;
3399e5dd7070Spatrick } while (I != E &&
3400e5dd7070Spatrick PathsSorted[BucketStart].get().MangledPath ==
3401e5dd7070Spatrick PathsSorted[I].get().MangledPath);
3402e5dd7070Spatrick
3403e5dd7070Spatrick // If this bucket has multiple paths, extend them all.
3404e5dd7070Spatrick if (I - BucketStart > 1) {
3405e5dd7070Spatrick for (size_t II = BucketStart; II != I; ++II)
3406e5dd7070Spatrick Changed |= extendPath(PathsSorted[II]);
3407e5dd7070Spatrick assert(Changed && "no paths were extended to fix ambiguity");
3408e5dd7070Spatrick }
3409e5dd7070Spatrick }
3410e5dd7070Spatrick return Changed;
3411e5dd7070Spatrick }
3412e5dd7070Spatrick
~MicrosoftVTableContext()3413e5dd7070Spatrick MicrosoftVTableContext::~MicrosoftVTableContext() {}
3414e5dd7070Spatrick
3415e5dd7070Spatrick namespace {
3416e5dd7070Spatrick typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3417e5dd7070Spatrick llvm::DenseSet<BaseSubobject>> FullPathTy;
3418e5dd7070Spatrick }
3419e5dd7070Spatrick
3420e5dd7070Spatrick // This recursive function finds all paths from a subobject centered at
3421e5dd7070Spatrick // (RD, Offset) to the subobject located at IntroducingObject.
findPathsToSubobject(ASTContext & Context,const ASTRecordLayout & MostDerivedLayout,const CXXRecordDecl * RD,CharUnits Offset,BaseSubobject IntroducingObject,FullPathTy & FullPath,std::list<FullPathTy> & Paths)3422e5dd7070Spatrick static void findPathsToSubobject(ASTContext &Context,
3423e5dd7070Spatrick const ASTRecordLayout &MostDerivedLayout,
3424e5dd7070Spatrick const CXXRecordDecl *RD, CharUnits Offset,
3425e5dd7070Spatrick BaseSubobject IntroducingObject,
3426e5dd7070Spatrick FullPathTy &FullPath,
3427e5dd7070Spatrick std::list<FullPathTy> &Paths) {
3428e5dd7070Spatrick if (BaseSubobject(RD, Offset) == IntroducingObject) {
3429e5dd7070Spatrick Paths.push_back(FullPath);
3430e5dd7070Spatrick return;
3431e5dd7070Spatrick }
3432e5dd7070Spatrick
3433e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3434e5dd7070Spatrick
3435e5dd7070Spatrick for (const CXXBaseSpecifier &BS : RD->bases()) {
3436e5dd7070Spatrick const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
3437e5dd7070Spatrick CharUnits NewOffset = BS.isVirtual()
3438e5dd7070Spatrick ? MostDerivedLayout.getVBaseClassOffset(Base)
3439e5dd7070Spatrick : Offset + Layout.getBaseClassOffset(Base);
3440e5dd7070Spatrick FullPath.insert(BaseSubobject(Base, NewOffset));
3441e5dd7070Spatrick findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
3442e5dd7070Spatrick IntroducingObject, FullPath, Paths);
3443e5dd7070Spatrick FullPath.pop_back();
3444e5dd7070Spatrick }
3445e5dd7070Spatrick }
3446e5dd7070Spatrick
3447e5dd7070Spatrick // Return the paths which are not subsets of other paths.
removeRedundantPaths(std::list<FullPathTy> & FullPaths)3448e5dd7070Spatrick static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3449e5dd7070Spatrick FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3450e5dd7070Spatrick for (const FullPathTy &OtherPath : FullPaths) {
3451e5dd7070Spatrick if (&SpecificPath == &OtherPath)
3452e5dd7070Spatrick continue;
3453e5dd7070Spatrick if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
3454*12c85518Srobert return OtherPath.contains(BSO);
3455e5dd7070Spatrick })) {
3456e5dd7070Spatrick return true;
3457e5dd7070Spatrick }
3458e5dd7070Spatrick }
3459e5dd7070Spatrick return false;
3460e5dd7070Spatrick });
3461e5dd7070Spatrick }
3462e5dd7070Spatrick
getOffsetOfFullPath(ASTContext & Context,const CXXRecordDecl * RD,const FullPathTy & FullPath)3463e5dd7070Spatrick static CharUnits getOffsetOfFullPath(ASTContext &Context,
3464e5dd7070Spatrick const CXXRecordDecl *RD,
3465e5dd7070Spatrick const FullPathTy &FullPath) {
3466e5dd7070Spatrick const ASTRecordLayout &MostDerivedLayout =
3467e5dd7070Spatrick Context.getASTRecordLayout(RD);
3468e5dd7070Spatrick CharUnits Offset = CharUnits::fromQuantity(-1);
3469e5dd7070Spatrick for (const BaseSubobject &BSO : FullPath) {
3470e5dd7070Spatrick const CXXRecordDecl *Base = BSO.getBase();
3471e5dd7070Spatrick // The first entry in the path is always the most derived record, skip it.
3472e5dd7070Spatrick if (Base == RD) {
3473e5dd7070Spatrick assert(Offset.getQuantity() == -1);
3474e5dd7070Spatrick Offset = CharUnits::Zero();
3475e5dd7070Spatrick continue;
3476e5dd7070Spatrick }
3477e5dd7070Spatrick assert(Offset.getQuantity() != -1);
3478e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3479e5dd7070Spatrick // While we know which base has to be traversed, we don't know if that base
3480e5dd7070Spatrick // was a virtual base.
3481e5dd7070Spatrick const CXXBaseSpecifier *BaseBS = std::find_if(
3482e5dd7070Spatrick RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3483e5dd7070Spatrick return BS.getType()->getAsCXXRecordDecl() == Base;
3484e5dd7070Spatrick });
3485e5dd7070Spatrick Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3486e5dd7070Spatrick : Offset + Layout.getBaseClassOffset(Base);
3487e5dd7070Spatrick RD = Base;
3488e5dd7070Spatrick }
3489e5dd7070Spatrick return Offset;
3490e5dd7070Spatrick }
3491e5dd7070Spatrick
3492e5dd7070Spatrick // We want to select the path which introduces the most covariant overrides. If
3493e5dd7070Spatrick // two paths introduce overrides which the other path doesn't contain, issue a
3494e5dd7070Spatrick // diagnostic.
selectBestPath(ASTContext & Context,const CXXRecordDecl * RD,const VPtrInfo & Info,std::list<FullPathTy> & FullPaths)3495e5dd7070Spatrick static const FullPathTy *selectBestPath(ASTContext &Context,
3496e5dd7070Spatrick const CXXRecordDecl *RD,
3497e5dd7070Spatrick const VPtrInfo &Info,
3498e5dd7070Spatrick std::list<FullPathTy> &FullPaths) {
3499e5dd7070Spatrick // Handle some easy cases first.
3500e5dd7070Spatrick if (FullPaths.empty())
3501e5dd7070Spatrick return nullptr;
3502e5dd7070Spatrick if (FullPaths.size() == 1)
3503e5dd7070Spatrick return &FullPaths.front();
3504e5dd7070Spatrick
3505e5dd7070Spatrick const FullPathTy *BestPath = nullptr;
3506e5dd7070Spatrick typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3507e5dd7070Spatrick OverriderSetTy LastOverrides;
3508e5dd7070Spatrick for (const FullPathTy &SpecificPath : FullPaths) {
3509e5dd7070Spatrick assert(!SpecificPath.empty());
3510e5dd7070Spatrick OverriderSetTy CurrentOverrides;
3511e5dd7070Spatrick const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3512e5dd7070Spatrick // Find the distance from the start of the path to the subobject with the
3513e5dd7070Spatrick // VPtr.
3514e5dd7070Spatrick CharUnits BaseOffset =
3515e5dd7070Spatrick getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3516e5dd7070Spatrick FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
3517e5dd7070Spatrick for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
3518ec727ea7Spatrick if (!MicrosoftVTableContext::hasVtableSlot(MD))
3519e5dd7070Spatrick continue;
3520e5dd7070Spatrick FinalOverriders::OverriderInfo OI =
3521e5dd7070Spatrick Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
3522e5dd7070Spatrick const CXXMethodDecl *OverridingMethod = OI.Method;
3523e5dd7070Spatrick // Only overriders which have a return adjustment introduce problematic
3524e5dd7070Spatrick // thunks.
3525e5dd7070Spatrick if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3526e5dd7070Spatrick .isEmpty())
3527e5dd7070Spatrick continue;
3528e5dd7070Spatrick // It's possible that the overrider isn't in this path. If so, skip it
3529e5dd7070Spatrick // because this path didn't introduce it.
3530e5dd7070Spatrick const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
3531e5dd7070Spatrick if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
3532e5dd7070Spatrick return BSO.getBase() == OverridingParent;
3533e5dd7070Spatrick }))
3534e5dd7070Spatrick continue;
3535e5dd7070Spatrick CurrentOverrides.insert(OverridingMethod);
3536e5dd7070Spatrick }
3537e5dd7070Spatrick OverriderSetTy NewOverrides =
3538e5dd7070Spatrick llvm::set_difference(CurrentOverrides, LastOverrides);
3539e5dd7070Spatrick if (NewOverrides.empty())
3540e5dd7070Spatrick continue;
3541e5dd7070Spatrick OverriderSetTy MissingOverrides =
3542e5dd7070Spatrick llvm::set_difference(LastOverrides, CurrentOverrides);
3543e5dd7070Spatrick if (MissingOverrides.empty()) {
3544e5dd7070Spatrick // This path is a strict improvement over the last path, let's use it.
3545e5dd7070Spatrick BestPath = &SpecificPath;
3546e5dd7070Spatrick std::swap(CurrentOverrides, LastOverrides);
3547e5dd7070Spatrick } else {
3548e5dd7070Spatrick // This path introduces an overrider with a conflicting covariant thunk.
3549e5dd7070Spatrick DiagnosticsEngine &Diags = Context.getDiagnostics();
3550e5dd7070Spatrick const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3551e5dd7070Spatrick const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3552e5dd7070Spatrick Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3553e5dd7070Spatrick << RD;
3554e5dd7070Spatrick Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3555e5dd7070Spatrick << CovariantMD;
3556e5dd7070Spatrick Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3557e5dd7070Spatrick << ConflictMD;
3558e5dd7070Spatrick }
3559e5dd7070Spatrick }
3560e5dd7070Spatrick // Go with the path that introduced the most covariant overrides. If there is
3561e5dd7070Spatrick // no such path, pick the first path.
3562e5dd7070Spatrick return BestPath ? BestPath : &FullPaths.front();
3563e5dd7070Spatrick }
3564e5dd7070Spatrick
computeFullPathsForVFTables(ASTContext & Context,const CXXRecordDecl * RD,VPtrInfoVector & Paths)3565e5dd7070Spatrick static void computeFullPathsForVFTables(ASTContext &Context,
3566e5dd7070Spatrick const CXXRecordDecl *RD,
3567e5dd7070Spatrick VPtrInfoVector &Paths) {
3568e5dd7070Spatrick const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
3569e5dd7070Spatrick FullPathTy FullPath;
3570e5dd7070Spatrick std::list<FullPathTy> FullPaths;
3571e5dd7070Spatrick for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
3572e5dd7070Spatrick findPathsToSubobject(
3573e5dd7070Spatrick Context, MostDerivedLayout, RD, CharUnits::Zero(),
3574e5dd7070Spatrick BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
3575e5dd7070Spatrick FullPaths);
3576e5dd7070Spatrick FullPath.clear();
3577e5dd7070Spatrick removeRedundantPaths(FullPaths);
3578e5dd7070Spatrick Info->PathToIntroducingObject.clear();
3579e5dd7070Spatrick if (const FullPathTy *BestPath =
3580e5dd7070Spatrick selectBestPath(Context, RD, *Info, FullPaths))
3581e5dd7070Spatrick for (const BaseSubobject &BSO : *BestPath)
3582e5dd7070Spatrick Info->PathToIntroducingObject.push_back(BSO.getBase());
3583e5dd7070Spatrick FullPaths.clear();
3584e5dd7070Spatrick }
3585e5dd7070Spatrick }
3586e5dd7070Spatrick
vfptrIsEarlierInMDC(const ASTRecordLayout & Layout,const MethodVFTableLocation & LHS,const MethodVFTableLocation & RHS)3587e5dd7070Spatrick static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
3588e5dd7070Spatrick const MethodVFTableLocation &LHS,
3589e5dd7070Spatrick const MethodVFTableLocation &RHS) {
3590e5dd7070Spatrick CharUnits L = LHS.VFPtrOffset;
3591e5dd7070Spatrick CharUnits R = RHS.VFPtrOffset;
3592e5dd7070Spatrick if (LHS.VBase)
3593e5dd7070Spatrick L += Layout.getVBaseClassOffset(LHS.VBase);
3594e5dd7070Spatrick if (RHS.VBase)
3595e5dd7070Spatrick R += Layout.getVBaseClassOffset(RHS.VBase);
3596e5dd7070Spatrick return L < R;
3597e5dd7070Spatrick }
3598e5dd7070Spatrick
computeVTableRelatedInformation(const CXXRecordDecl * RD)3599e5dd7070Spatrick void MicrosoftVTableContext::computeVTableRelatedInformation(
3600e5dd7070Spatrick const CXXRecordDecl *RD) {
3601e5dd7070Spatrick assert(RD->isDynamicClass());
3602e5dd7070Spatrick
3603e5dd7070Spatrick // Check if we've computed this information before.
3604e5dd7070Spatrick if (VFPtrLocations.count(RD))
3605e5dd7070Spatrick return;
3606e5dd7070Spatrick
3607e5dd7070Spatrick const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3608e5dd7070Spatrick
3609e5dd7070Spatrick {
3610e5dd7070Spatrick auto VFPtrs = std::make_unique<VPtrInfoVector>();
3611e5dd7070Spatrick computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3612e5dd7070Spatrick computeFullPathsForVFTables(Context, RD, *VFPtrs);
3613e5dd7070Spatrick VFPtrLocations[RD] = std::move(VFPtrs);
3614e5dd7070Spatrick }
3615e5dd7070Spatrick
3616e5dd7070Spatrick MethodVFTableLocationsTy NewMethodLocations;
3617e5dd7070Spatrick for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
3618e5dd7070Spatrick VFTableBuilder Builder(*this, RD, *VFPtr);
3619e5dd7070Spatrick
3620e5dd7070Spatrick VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
3621e5dd7070Spatrick assert(VFTableLayouts.count(id) == 0);
3622e5dd7070Spatrick SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3623e5dd7070Spatrick Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
3624e5dd7070Spatrick VFTableLayouts[id] = std::make_unique<VTableLayout>(
3625e5dd7070Spatrick ArrayRef<size_t>{0}, Builder.vtable_components(), VTableThunks,
3626e5dd7070Spatrick EmptyAddressPointsMap);
3627e5dd7070Spatrick Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3628e5dd7070Spatrick
3629e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3630e5dd7070Spatrick for (const auto &Loc : Builder.vtable_locations()) {
3631e5dd7070Spatrick auto Insert = NewMethodLocations.insert(Loc);
3632e5dd7070Spatrick if (!Insert.second) {
3633e5dd7070Spatrick const MethodVFTableLocation &NewLoc = Loc.second;
3634e5dd7070Spatrick MethodVFTableLocation &OldLoc = Insert.first->second;
3635e5dd7070Spatrick if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
3636e5dd7070Spatrick OldLoc = NewLoc;
3637e5dd7070Spatrick }
3638e5dd7070Spatrick }
3639e5dd7070Spatrick }
3640e5dd7070Spatrick
3641e5dd7070Spatrick MethodVFTableLocations.insert(NewMethodLocations.begin(),
3642e5dd7070Spatrick NewMethodLocations.end());
3643e5dd7070Spatrick if (Context.getLangOpts().DumpVTableLayouts)
3644e5dd7070Spatrick dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
3645e5dd7070Spatrick }
3646e5dd7070Spatrick
dumpMethodLocations(const CXXRecordDecl * RD,const MethodVFTableLocationsTy & NewMethods,raw_ostream & Out)3647e5dd7070Spatrick void MicrosoftVTableContext::dumpMethodLocations(
3648e5dd7070Spatrick const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3649e5dd7070Spatrick raw_ostream &Out) {
3650e5dd7070Spatrick // Compute the vtable indices for all the member functions.
3651e5dd7070Spatrick // Store them in a map keyed by the location so we'll get a sorted table.
3652e5dd7070Spatrick std::map<MethodVFTableLocation, std::string> IndicesMap;
3653e5dd7070Spatrick bool HasNonzeroOffset = false;
3654e5dd7070Spatrick
3655e5dd7070Spatrick for (const auto &I : NewMethods) {
3656e5dd7070Spatrick const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
3657ec727ea7Spatrick assert(hasVtableSlot(MD));
3658e5dd7070Spatrick
3659e5dd7070Spatrick std::string MethodName = PredefinedExpr::ComputeName(
3660e5dd7070Spatrick PredefinedExpr::PrettyFunctionNoVirtual, MD);
3661e5dd7070Spatrick
3662e5dd7070Spatrick if (isa<CXXDestructorDecl>(MD)) {
3663e5dd7070Spatrick IndicesMap[I.second] = MethodName + " [scalar deleting]";
3664e5dd7070Spatrick } else {
3665e5dd7070Spatrick IndicesMap[I.second] = MethodName;
3666e5dd7070Spatrick }
3667e5dd7070Spatrick
3668e5dd7070Spatrick if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
3669e5dd7070Spatrick HasNonzeroOffset = true;
3670e5dd7070Spatrick }
3671e5dd7070Spatrick
3672e5dd7070Spatrick // Print the vtable indices for all the member functions.
3673e5dd7070Spatrick if (!IndicesMap.empty()) {
3674e5dd7070Spatrick Out << "VFTable indices for ";
3675e5dd7070Spatrick Out << "'";
3676e5dd7070Spatrick RD->printQualifiedName(Out);
3677e5dd7070Spatrick Out << "' (" << IndicesMap.size()
3678e5dd7070Spatrick << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
3679e5dd7070Spatrick
3680e5dd7070Spatrick CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3681e5dd7070Spatrick uint64_t LastVBIndex = 0;
3682e5dd7070Spatrick for (const auto &I : IndicesMap) {
3683e5dd7070Spatrick CharUnits VFPtrOffset = I.first.VFPtrOffset;
3684e5dd7070Spatrick uint64_t VBIndex = I.first.VBTableIndex;
3685e5dd7070Spatrick if (HasNonzeroOffset &&
3686e5dd7070Spatrick (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3687e5dd7070Spatrick assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3688e5dd7070Spatrick Out << " -- accessible via ";
3689e5dd7070Spatrick if (VBIndex)
3690e5dd7070Spatrick Out << "vbtable index " << VBIndex << ", ";
3691e5dd7070Spatrick Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3692e5dd7070Spatrick LastVFPtrOffset = VFPtrOffset;
3693e5dd7070Spatrick LastVBIndex = VBIndex;
3694e5dd7070Spatrick }
3695e5dd7070Spatrick
3696e5dd7070Spatrick uint64_t VTableIndex = I.first.Index;
3697e5dd7070Spatrick const std::string &MethodName = I.second;
3698e5dd7070Spatrick Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3699e5dd7070Spatrick }
3700e5dd7070Spatrick Out << '\n';
3701e5dd7070Spatrick }
3702e5dd7070Spatrick
3703e5dd7070Spatrick Out.flush();
3704e5dd7070Spatrick }
3705e5dd7070Spatrick
computeVBTableRelatedInformation(const CXXRecordDecl * RD)3706e5dd7070Spatrick const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
3707e5dd7070Spatrick const CXXRecordDecl *RD) {
3708e5dd7070Spatrick VirtualBaseInfo *VBI;
3709e5dd7070Spatrick
3710e5dd7070Spatrick {
3711e5dd7070Spatrick // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3712e5dd7070Spatrick // as it may be modified and rehashed under us.
3713e5dd7070Spatrick std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
3714e5dd7070Spatrick if (Entry)
3715e5dd7070Spatrick return *Entry;
3716e5dd7070Spatrick Entry = std::make_unique<VirtualBaseInfo>();
3717e5dd7070Spatrick VBI = Entry.get();
3718e5dd7070Spatrick }
3719e5dd7070Spatrick
3720e5dd7070Spatrick computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
3721e5dd7070Spatrick
3722e5dd7070Spatrick // First, see if the Derived class shared the vbptr with a non-virtual base.
3723e5dd7070Spatrick const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3724e5dd7070Spatrick if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
3725e5dd7070Spatrick // If the Derived class shares the vbptr with a non-virtual base, the shared
3726e5dd7070Spatrick // virtual bases come first so that the layout is the same.
3727e5dd7070Spatrick const VirtualBaseInfo &BaseInfo =
3728e5dd7070Spatrick computeVBTableRelatedInformation(VBPtrBase);
3729e5dd7070Spatrick VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
3730e5dd7070Spatrick BaseInfo.VBTableIndices.end());
3731e5dd7070Spatrick }
3732e5dd7070Spatrick
3733e5dd7070Spatrick // New vbases are added to the end of the vbtable.
3734e5dd7070Spatrick // Skip the self entry and vbases visited in the non-virtual base, if any.
3735e5dd7070Spatrick unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
3736e5dd7070Spatrick for (const auto &VB : RD->vbases()) {
3737e5dd7070Spatrick const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
3738e5dd7070Spatrick if (!VBI->VBTableIndices.count(CurVBase))
3739e5dd7070Spatrick VBI->VBTableIndices[CurVBase] = VBTableIndex++;
3740e5dd7070Spatrick }
3741e5dd7070Spatrick
3742e5dd7070Spatrick return *VBI;
3743e5dd7070Spatrick }
3744e5dd7070Spatrick
getVBTableIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * VBase)3745e5dd7070Spatrick unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3746e5dd7070Spatrick const CXXRecordDecl *VBase) {
3747e5dd7070Spatrick const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
3748e5dd7070Spatrick assert(VBInfo.VBTableIndices.count(VBase));
3749e5dd7070Spatrick return VBInfo.VBTableIndices.find(VBase)->second;
3750e5dd7070Spatrick }
3751e5dd7070Spatrick
3752e5dd7070Spatrick const VPtrInfoVector &
enumerateVBTables(const CXXRecordDecl * RD)3753e5dd7070Spatrick MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
3754e5dd7070Spatrick return computeVBTableRelatedInformation(RD).VBPtrPaths;
3755e5dd7070Spatrick }
3756e5dd7070Spatrick
3757e5dd7070Spatrick const VPtrInfoVector &
getVFPtrOffsets(const CXXRecordDecl * RD)3758e5dd7070Spatrick MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3759e5dd7070Spatrick computeVTableRelatedInformation(RD);
3760e5dd7070Spatrick
3761e5dd7070Spatrick assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3762e5dd7070Spatrick return *VFPtrLocations[RD];
3763e5dd7070Spatrick }
3764e5dd7070Spatrick
3765e5dd7070Spatrick const VTableLayout &
getVFTableLayout(const CXXRecordDecl * RD,CharUnits VFPtrOffset)3766e5dd7070Spatrick MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3767e5dd7070Spatrick CharUnits VFPtrOffset) {
3768e5dd7070Spatrick computeVTableRelatedInformation(RD);
3769e5dd7070Spatrick
3770e5dd7070Spatrick VFTableIdTy id(RD, VFPtrOffset);
3771e5dd7070Spatrick assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3772e5dd7070Spatrick return *VFTableLayouts[id];
3773e5dd7070Spatrick }
3774e5dd7070Spatrick
3775e5dd7070Spatrick MethodVFTableLocation
getMethodVFTableLocation(GlobalDecl GD)3776e5dd7070Spatrick MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3777ec727ea7Spatrick assert(hasVtableSlot(cast<CXXMethodDecl>(GD.getDecl())) &&
3778e5dd7070Spatrick "Only use this method for virtual methods or dtors");
3779e5dd7070Spatrick if (isa<CXXDestructorDecl>(GD.getDecl()))
3780e5dd7070Spatrick assert(GD.getDtorType() == Dtor_Deleting);
3781e5dd7070Spatrick
3782e5dd7070Spatrick GD = GD.getCanonicalDecl();
3783e5dd7070Spatrick
3784e5dd7070Spatrick MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3785e5dd7070Spatrick if (I != MethodVFTableLocations.end())
3786e5dd7070Spatrick return I->second;
3787e5dd7070Spatrick
3788e5dd7070Spatrick const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3789e5dd7070Spatrick
3790e5dd7070Spatrick computeVTableRelatedInformation(RD);
3791e5dd7070Spatrick
3792e5dd7070Spatrick I = MethodVFTableLocations.find(GD);
3793e5dd7070Spatrick assert(I != MethodVFTableLocations.end() && "Did not find index!");
3794e5dd7070Spatrick return I->second;
3795e5dd7070Spatrick }
3796