blob: c018f1b303e940c3f65a24271d639a84c6ffd773 [file] [log] [blame]
Peter Collingbournecfd23562011-09-26 01:57:12 +00001//===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with generation of the layout of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/VTableBuilder.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000015#include "clang/AST/ASTContext.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
Reid Kleckner5f080942014-01-03 23:42:00 +000019#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000020#include "llvm/Support/Format.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000021#include "llvm/Support/raw_ostream.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000022#include <algorithm>
23#include <cstdio>
24
25using namespace clang;
26
27#define DUMP_OVERRIDERS 0
28
29namespace {
30
31/// BaseOffset - Represents an offset from a derived class to a direct or
32/// indirect base class.
33struct BaseOffset {
34 /// DerivedClass - The derived class.
35 const CXXRecordDecl *DerivedClass;
36
37 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +000038 /// involves virtual base classes, this holds the declaration of the last
39 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbournecfd23562011-09-26 01:57:12 +000040 const CXXRecordDecl *VirtualBase;
41
42 /// NonVirtualOffset - The offset from the derived class to the base class.
43 /// (Or the offset from the virtual base class to the base class, if the
44 /// path from the derived class to the base class involves a virtual base
45 /// class.
46 CharUnits NonVirtualOffset;
47
48 BaseOffset() : DerivedClass(0), VirtualBase(0),
49 NonVirtualOffset(CharUnits::Zero()) { }
50 BaseOffset(const CXXRecordDecl *DerivedClass,
51 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
52 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
53 NonVirtualOffset(NonVirtualOffset) { }
54
55 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
56};
57
58/// FinalOverriders - Contains the final overrider member functions for all
59/// member functions in the base subobjects of a class.
60class FinalOverriders {
61public:
62 /// OverriderInfo - Information about a final overrider.
63 struct OverriderInfo {
64 /// Method - The method decl of the overrider.
65 const CXXMethodDecl *Method;
66
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +000067 /// VirtualBase - The virtual base class subobject of this overridder.
68 /// Note that this records the closest derived virtual base class subobject.
69 const CXXRecordDecl *VirtualBase;
70
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000071 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +000072 CharUnits Offset;
73
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +000074 OverriderInfo() : Method(0), VirtualBase(0), Offset(CharUnits::Zero()) { }
Peter Collingbournecfd23562011-09-26 01:57:12 +000075 };
76
77private:
78 /// MostDerivedClass - The most derived class for which the final overriders
79 /// are stored.
80 const CXXRecordDecl *MostDerivedClass;
81
82 /// MostDerivedClassOffset - If we're building final overriders for a
83 /// construction vtable, this holds the offset from the layout class to the
84 /// most derived class.
85 const CharUnits MostDerivedClassOffset;
86
87 /// LayoutClass - The class we're using for layout information. Will be
88 /// different than the most derived class if the final overriders are for a
89 /// construction vtable.
90 const CXXRecordDecl *LayoutClass;
91
92 ASTContext &Context;
93
94 /// MostDerivedClassLayout - the AST record layout of the most derived class.
95 const ASTRecordLayout &MostDerivedClassLayout;
96
97 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
98 /// in a base subobject.
99 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
100
101 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
102 OverriderInfo> OverridersMapTy;
103
104 /// OverridersMap - The final overriders for all virtual member functions of
105 /// all the base subobjects of the most derived class.
106 OverridersMapTy OverridersMap;
107
108 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
109 /// as a record decl and a subobject number) and its offsets in the most
110 /// derived class as well as the layout class.
111 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
112 CharUnits> SubobjectOffsetMapTy;
113
114 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
115
116 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
117 /// given base.
118 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
119 CharUnits OffsetInLayoutClass,
120 SubobjectOffsetMapTy &SubobjectOffsets,
121 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
122 SubobjectCountMapTy &SubobjectCounts);
123
124 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
125
126 /// dump - dump the final overriders for a base subobject, and all its direct
127 /// and indirect base subobjects.
128 void dump(raw_ostream &Out, BaseSubobject Base,
129 VisitedVirtualBasesSetTy& VisitedVirtualBases);
130
131public:
132 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
133 CharUnits MostDerivedClassOffset,
134 const CXXRecordDecl *LayoutClass);
135
136 /// getOverrider - Get the final overrider for the given method declaration in
137 /// the subobject with the given base offset.
138 OverriderInfo getOverrider(const CXXMethodDecl *MD,
139 CharUnits BaseOffset) const {
140 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
141 "Did not find overrider!");
142
143 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
144 }
145
146 /// dump - dump the final overriders.
147 void dump() {
148 VisitedVirtualBasesSetTy VisitedVirtualBases;
149 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
150 VisitedVirtualBases);
151 }
152
153};
154
Peter Collingbournecfd23562011-09-26 01:57:12 +0000155FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
156 CharUnits MostDerivedClassOffset,
157 const CXXRecordDecl *LayoutClass)
158 : MostDerivedClass(MostDerivedClass),
159 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
160 Context(MostDerivedClass->getASTContext()),
161 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
162
163 // Compute base offsets.
164 SubobjectOffsetMapTy SubobjectOffsets;
165 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
166 SubobjectCountMapTy SubobjectCounts;
167 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
168 /*IsVirtual=*/false,
169 MostDerivedClassOffset,
170 SubobjectOffsets, SubobjectLayoutClassOffsets,
171 SubobjectCounts);
172
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000173 // Get the final overriders.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000174 CXXFinalOverriderMap FinalOverriders;
175 MostDerivedClass->getFinalOverriders(FinalOverriders);
176
177 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
178 E = FinalOverriders.end(); I != E; ++I) {
179 const CXXMethodDecl *MD = I->first;
180 const OverridingMethods& Methods = I->second;
181
182 for (OverridingMethods::const_iterator I = Methods.begin(),
183 E = Methods.end(); I != E; ++I) {
184 unsigned SubobjectNumber = I->first;
185 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
186 SubobjectNumber)) &&
187 "Did not find subobject offset!");
188
189 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
190 SubobjectNumber)];
191
192 assert(I->second.size() == 1 && "Final overrider is not unique!");
193 const UniqueVirtualMethod &Method = I->second.front();
194
195 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
196 assert(SubobjectLayoutClassOffsets.count(
197 std::make_pair(OverriderRD, Method.Subobject))
198 && "Did not find subobject offset!");
199 CharUnits OverriderOffset =
200 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
201 Method.Subobject)];
202
203 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
204 assert(!Overrider.Method && "Overrider should not exist yet!");
205
206 Overrider.Offset = OverriderOffset;
207 Overrider.Method = Method.Method;
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +0000208 Overrider.VirtualBase = Method.InVirtualSubobject;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000209 }
210 }
211
212#if DUMP_OVERRIDERS
213 // And dump them (for now).
214 dump();
215#endif
216}
217
218static BaseOffset ComputeBaseOffset(ASTContext &Context,
219 const CXXRecordDecl *DerivedRD,
220 const CXXBasePath &Path) {
221 CharUnits NonVirtualOffset = CharUnits::Zero();
222
223 unsigned NonVirtualStart = 0;
224 const CXXRecordDecl *VirtualBase = 0;
225
226 // First, look for the virtual base class.
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000227 for (int I = Path.size(), E = 0; I != E; --I) {
228 const CXXBasePathElement &Element = Path[I - 1];
229
Peter Collingbournecfd23562011-09-26 01:57:12 +0000230 if (Element.Base->isVirtual()) {
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000231 NonVirtualStart = I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000232 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000233 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000234 break;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000235 }
236 }
237
238 // Now compute the non-virtual offset.
239 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
240 const CXXBasePathElement &Element = Path[I];
241
242 // Check the base class offset.
243 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
244
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000245 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000246
247 NonVirtualOffset += Layout.getBaseClassOffset(Base);
248 }
249
250 // FIXME: This should probably use CharUnits or something. Maybe we should
251 // even change the base offsets in ASTRecordLayout to be specified in
252 // CharUnits.
253 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
254
255}
256
257static BaseOffset ComputeBaseOffset(ASTContext &Context,
258 const CXXRecordDecl *BaseRD,
259 const CXXRecordDecl *DerivedRD) {
260 CXXBasePaths Paths(/*FindAmbiguities=*/false,
261 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer325d7452013-02-03 18:55:34 +0000262
263 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000264 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +0000265
266 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
267}
268
269static BaseOffset
270ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
271 const CXXMethodDecl *DerivedMD,
272 const CXXMethodDecl *BaseMD) {
273 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
274 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
275
276 // Canonicalize the return types.
Alp Toker314cc812014-01-25 16:55:45 +0000277 CanQualType CanDerivedReturnType =
278 Context.getCanonicalType(DerivedFT->getReturnType());
279 CanQualType CanBaseReturnType =
280 Context.getCanonicalType(BaseFT->getReturnType());
281
Peter Collingbournecfd23562011-09-26 01:57:12 +0000282 assert(CanDerivedReturnType->getTypeClass() ==
283 CanBaseReturnType->getTypeClass() &&
284 "Types must have same type class!");
285
286 if (CanDerivedReturnType == CanBaseReturnType) {
287 // No adjustment needed.
288 return BaseOffset();
289 }
290
291 if (isa<ReferenceType>(CanDerivedReturnType)) {
292 CanDerivedReturnType =
293 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
294 CanBaseReturnType =
295 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
296 } else if (isa<PointerType>(CanDerivedReturnType)) {
297 CanDerivedReturnType =
298 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
299 CanBaseReturnType =
300 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
301 } else {
302 llvm_unreachable("Unexpected return type!");
303 }
304
305 // We need to compare unqualified types here; consider
306 // const T *Base::foo();
307 // T *Derived::foo();
308 if (CanDerivedReturnType.getUnqualifiedType() ==
309 CanBaseReturnType.getUnqualifiedType()) {
310 // No adjustment needed.
311 return BaseOffset();
312 }
313
314 const CXXRecordDecl *DerivedRD =
315 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
316
317 const CXXRecordDecl *BaseRD =
318 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
319
320 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
321}
322
323void
324FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
325 CharUnits OffsetInLayoutClass,
326 SubobjectOffsetMapTy &SubobjectOffsets,
327 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
328 SubobjectCountMapTy &SubobjectCounts) {
329 const CXXRecordDecl *RD = Base.getBase();
330
331 unsigned SubobjectNumber = 0;
332 if (!IsVirtual)
333 SubobjectNumber = ++SubobjectCounts[RD];
334
335 // Set up the subobject to offset mapping.
336 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
337 && "Subobject offset already exists!");
338 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
339 && "Subobject offset already exists!");
340
341 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
342 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
343 OffsetInLayoutClass;
344
345 // Traverse our bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000346 for (const auto &B : RD->bases()) {
347 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000348
349 CharUnits BaseOffset;
350 CharUnits BaseOffsetInLayoutClass;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000351 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000352 // Check if we've visited this virtual base before.
353 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
354 continue;
355
356 const ASTRecordLayout &LayoutClassLayout =
357 Context.getASTRecordLayout(LayoutClass);
358
359 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
360 BaseOffsetInLayoutClass =
361 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
362 } else {
363 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
364 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
365
366 BaseOffset = Base.getBaseOffset() + Offset;
367 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
368 }
369
370 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000371 B.isVirtual(), BaseOffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000372 SubobjectOffsets, SubobjectLayoutClassOffsets,
373 SubobjectCounts);
374 }
375}
376
377void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
378 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
379 const CXXRecordDecl *RD = Base.getBase();
380 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
381
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000382 for (const auto &B : RD->bases()) {
383 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000384
385 // Ignore bases that don't have any virtual member functions.
386 if (!BaseDecl->isPolymorphic())
387 continue;
388
389 CharUnits BaseOffset;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000390 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000391 if (!VisitedVirtualBases.insert(BaseDecl)) {
392 // We've visited this base before.
393 continue;
394 }
395
396 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
397 } else {
398 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
399 }
400
401 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
402 }
403
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000404 Out << "Final overriders for (";
405 RD->printQualifiedName(Out);
406 Out << ", ";
Peter Collingbournecfd23562011-09-26 01:57:12 +0000407 Out << Base.getBaseOffset().getQuantity() << ")\n";
408
409 // Now dump the overriders for this base subobject.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000410 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000411 if (!MD->isVirtual())
412 continue;
413
414 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
415
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000416 Out << " ";
417 MD->printQualifiedName(Out);
418 Out << " - (";
419 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000420 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000421
422 BaseOffset Offset;
423 if (!Overrider.Method->isPure())
424 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
425
426 if (!Offset.isEmpty()) {
427 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000428 if (Offset.VirtualBase) {
429 Offset.VirtualBase->printQualifiedName(Out);
430 Out << " vbase, ";
431 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000432
433 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
434 }
435
436 Out << "\n";
437 }
438}
439
440/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
441struct VCallOffsetMap {
442
443 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
444
445 /// Offsets - Keeps track of methods and their offsets.
446 // FIXME: This should be a real map and not a vector.
447 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
448
449 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
450 /// can share the same vcall offset.
451 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
452 const CXXMethodDecl *RHS);
453
454public:
455 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
456 /// add was successful, or false if there was already a member function with
457 /// the same signature in the map.
458 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
459
460 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
461 /// vtable address point) for the given virtual member function.
462 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
463
464 // empty - Return whether the offset map is empty or not.
465 bool empty() const { return Offsets.empty(); }
466};
467
468static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
469 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000470 const FunctionProtoType *LT =
471 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
472 const FunctionProtoType *RT =
473 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000474
475 // Fast-path matches in the canonical types.
476 if (LT == RT) return true;
477
478 // Force the signatures to match. We can't rely on the overrides
479 // list here because there isn't necessarily an inheritance
480 // relationship between the two methods.
John McCallb6c4a7e2012-03-21 06:57:19 +0000481 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000482 LT->getNumParams() != RT->getNumParams())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000483 return false;
Alp Toker9cacbab2014-01-20 20:26:09 +0000484 for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
485 if (LT->getParamType(I) != RT->getParamType(I))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000486 return false;
487 return true;
488}
489
490bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
491 const CXXMethodDecl *RHS) {
492 assert(LHS->isVirtual() && "LHS must be virtual!");
493 assert(RHS->isVirtual() && "LHS must be virtual!");
494
495 // A destructor can share a vcall offset with another destructor.
496 if (isa<CXXDestructorDecl>(LHS))
497 return isa<CXXDestructorDecl>(RHS);
498
499 // FIXME: We need to check more things here.
500
501 // The methods must have the same name.
502 DeclarationName LHSName = LHS->getDeclName();
503 DeclarationName RHSName = RHS->getDeclName();
504 if (LHSName != RHSName)
505 return false;
506
507 // And the same signatures.
508 return HasSameVirtualSignature(LHS, RHS);
509}
510
511bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
512 CharUnits OffsetOffset) {
513 // Check if we can reuse an offset.
514 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
515 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
516 return false;
517 }
518
519 // Add the offset.
520 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
521 return true;
522}
523
524CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
525 // Look for an offset.
526 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
527 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
528 return Offsets[I].second;
529 }
530
531 llvm_unreachable("Should always find a vcall offset offset!");
532}
533
534/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
535class VCallAndVBaseOffsetBuilder {
536public:
537 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
538 VBaseOffsetOffsetsMapTy;
539
540private:
541 /// MostDerivedClass - The most derived class for which we're building vcall
542 /// and vbase offsets.
543 const CXXRecordDecl *MostDerivedClass;
544
545 /// LayoutClass - The class we're using for layout information. Will be
546 /// different than the most derived class if we're building a construction
547 /// vtable.
548 const CXXRecordDecl *LayoutClass;
549
550 /// Context - The ASTContext which we will use for layout information.
551 ASTContext &Context;
552
553 /// Components - vcall and vbase offset components
554 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
555 VTableComponentVectorTy Components;
556
557 /// VisitedVirtualBases - Visited virtual bases.
558 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
559
560 /// VCallOffsets - Keeps track of vcall offsets.
561 VCallOffsetMap VCallOffsets;
562
563
564 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
565 /// relative to the address point.
566 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
567
568 /// FinalOverriders - The final overriders of the most derived class.
569 /// (Can be null when we're not building a vtable of the most derived class).
570 const FinalOverriders *Overriders;
571
572 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
573 /// given base subobject.
574 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
575 CharUnits RealBaseOffset);
576
577 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
578 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
579
580 /// AddVBaseOffsets - Add vbase offsets for the given class.
581 void AddVBaseOffsets(const CXXRecordDecl *Base,
582 CharUnits OffsetInLayoutClass);
583
584 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
585 /// chars, relative to the vtable address point.
586 CharUnits getCurrentOffsetOffset() const;
587
588public:
589 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
590 const CXXRecordDecl *LayoutClass,
591 const FinalOverriders *Overriders,
592 BaseSubobject Base, bool BaseIsVirtual,
593 CharUnits OffsetInLayoutClass)
594 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
595 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
596
597 // Add vcall and vbase offsets.
598 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
599 }
600
601 /// Methods for iterating over the components.
602 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
603 const_iterator components_begin() const { return Components.rbegin(); }
604 const_iterator components_end() const { return Components.rend(); }
605
606 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
607 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
608 return VBaseOffsetOffsets;
609 }
610};
611
612void
613VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
614 bool BaseIsVirtual,
615 CharUnits RealBaseOffset) {
616 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
617
618 // Itanium C++ ABI 2.5.2:
619 // ..in classes sharing a virtual table with a primary base class, the vcall
620 // and vbase offsets added by the derived class all come before the vcall
621 // and vbase offsets required by the base class, so that the latter may be
622 // laid out as required by the base class without regard to additions from
623 // the derived class(es).
624
625 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
626 // emit them for the primary base first).
627 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
628 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
629
630 CharUnits PrimaryBaseOffset;
631
632 // Get the base offset of the primary base.
633 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000634 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000635 "Primary vbase should have a zero offset!");
636
637 const ASTRecordLayout &MostDerivedClassLayout =
638 Context.getASTRecordLayout(MostDerivedClass);
639
640 PrimaryBaseOffset =
641 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
642 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000643 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000644 "Primary base should have a zero offset!");
645
646 PrimaryBaseOffset = Base.getBaseOffset();
647 }
648
649 AddVCallAndVBaseOffsets(
650 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
651 PrimaryBaseIsVirtual, RealBaseOffset);
652 }
653
654 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
655
656 // We only want to add vcall offsets for virtual bases.
657 if (BaseIsVirtual)
658 AddVCallOffsets(Base, RealBaseOffset);
659}
660
661CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
662 // OffsetIndex is the index of this vcall or vbase offset, relative to the
663 // vtable address point. (We subtract 3 to account for the information just
664 // above the address point, the RTTI info, the offset to top, and the
665 // vcall offset itself).
666 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
667
668 CharUnits PointerWidth =
669 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
670 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
671 return OffsetOffset;
672}
673
674void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
675 CharUnits VBaseOffset) {
676 const CXXRecordDecl *RD = Base.getBase();
677 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
678
679 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
680
681 // Handle the primary base first.
682 // We only want to add vcall offsets if the base is non-virtual; a virtual
683 // primary base will have its vcall and vbase offsets emitted already.
684 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
685 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000686 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000687 "Primary base should have a zero offset!");
688
689 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
690 VBaseOffset);
691 }
692
693 // Add the vcall offsets.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000694 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000695 if (!MD->isVirtual())
696 continue;
697
698 CharUnits OffsetOffset = getCurrentOffsetOffset();
699
700 // Don't add a vcall offset if we already have one for this member function
701 // signature.
702 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
703 continue;
704
705 CharUnits Offset = CharUnits::Zero();
706
707 if (Overriders) {
708 // Get the final overrider.
709 FinalOverriders::OverriderInfo Overrider =
710 Overriders->getOverrider(MD, Base.getBaseOffset());
711
712 /// The vcall offset is the offset from the virtual base to the object
713 /// where the function was overridden.
714 Offset = Overrider.Offset - VBaseOffset;
715 }
716
717 Components.push_back(
718 VTableComponent::MakeVCallOffset(Offset));
719 }
720
721 // And iterate over all non-virtual bases (ignoring the primary base).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000722 for (const auto &B : RD->bases()) {
723 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000724 continue;
725
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000726 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000727 if (BaseDecl == PrimaryBase)
728 continue;
729
730 // Get the base offset of this base.
731 CharUnits BaseOffset = Base.getBaseOffset() +
732 Layout.getBaseClassOffset(BaseDecl);
733
734 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
735 VBaseOffset);
736 }
737}
738
739void
740VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
741 CharUnits OffsetInLayoutClass) {
742 const ASTRecordLayout &LayoutClassLayout =
743 Context.getASTRecordLayout(LayoutClass);
744
745 // Add vbase offsets.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000746 for (const auto &B : RD->bases()) {
747 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000748
749 // Check if this is a virtual base that we haven't visited before.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000750 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000751 CharUnits Offset =
752 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
753
754 // Add the vbase offset offset.
755 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
756 "vbase offset offset already exists!");
757
758 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
759 VBaseOffsetOffsets.insert(
760 std::make_pair(BaseDecl, VBaseOffsetOffset));
761
762 Components.push_back(
763 VTableComponent::MakeVBaseOffset(Offset));
764 }
765
766 // Check the base class looking for more vbase offsets.
767 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
768 }
769}
770
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000771/// ItaniumVTableBuilder - Class for building vtable layout information.
772class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000773public:
774 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
775 /// primary bases.
776 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
777 PrimaryBasesSetVectorTy;
778
779 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
780 VBaseOffsetOffsetsMapTy;
781
782 typedef llvm::DenseMap<BaseSubobject, uint64_t>
783 AddressPointsMapTy;
784
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000785 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
786
Peter Collingbournecfd23562011-09-26 01:57:12 +0000787private:
788 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000789 ItaniumVTableContext &VTables;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000790
791 /// MostDerivedClass - The most derived class for which we're building this
792 /// vtable.
793 const CXXRecordDecl *MostDerivedClass;
794
795 /// MostDerivedClassOffset - If we're building a construction vtable, this
796 /// holds the offset from the layout class to the most derived class.
797 const CharUnits MostDerivedClassOffset;
798
799 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
800 /// base. (This only makes sense when building a construction vtable).
801 bool MostDerivedClassIsVirtual;
802
803 /// LayoutClass - The class we're using for layout information. Will be
804 /// different than the most derived class if we're building a construction
805 /// vtable.
806 const CXXRecordDecl *LayoutClass;
807
808 /// Context - The ASTContext which we will use for layout information.
809 ASTContext &Context;
810
811 /// FinalOverriders - The final overriders of the most derived class.
812 const FinalOverriders Overriders;
813
814 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
815 /// bases in this vtable.
816 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
817
818 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
819 /// the most derived class.
820 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
821
822 /// Components - The components of the vtable being built.
823 SmallVector<VTableComponent, 64> Components;
824
825 /// AddressPoints - Address points for the vtable being built.
826 AddressPointsMapTy AddressPoints;
827
828 /// MethodInfo - Contains information about a method in a vtable.
829 /// (Used for computing 'this' pointer adjustment thunks.
830 struct MethodInfo {
831 /// BaseOffset - The base offset of this method.
832 const CharUnits BaseOffset;
833
834 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
835 /// method.
836 const CharUnits BaseOffsetInLayoutClass;
837
838 /// VTableIndex - The index in the vtable that this method has.
839 /// (For destructors, this is the index of the complete destructor).
840 const uint64_t VTableIndex;
841
842 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
843 uint64_t VTableIndex)
844 : BaseOffset(BaseOffset),
845 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
846 VTableIndex(VTableIndex) { }
847
848 MethodInfo()
849 : BaseOffset(CharUnits::Zero()),
850 BaseOffsetInLayoutClass(CharUnits::Zero()),
851 VTableIndex(0) { }
852 };
853
854 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
855
856 /// MethodInfoMap - The information for all methods in the vtable we're
857 /// currently building.
858 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000859
860 /// MethodVTableIndices - Contains the index (relative to the vtable address
861 /// point) where the function pointer for a virtual function is stored.
862 MethodVTableIndicesTy MethodVTableIndices;
863
Peter Collingbournecfd23562011-09-26 01:57:12 +0000864 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
865
866 /// VTableThunks - The thunks by vtable index in the vtable currently being
867 /// built.
868 VTableThunksMapTy VTableThunks;
869
870 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
871 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
872
873 /// Thunks - A map that contains all the thunks needed for all methods in the
874 /// most derived class for which the vtable is currently being built.
875 ThunksMapTy Thunks;
876
877 /// AddThunk - Add a thunk for the given method.
878 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
879
880 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
881 /// part of the vtable we're currently building.
882 void ComputeThisAdjustments();
883
884 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
885
886 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
887 /// some other base.
888 VisitedVirtualBasesSetTy PrimaryVirtualBases;
889
890 /// ComputeReturnAdjustment - Compute the return adjustment given a return
891 /// adjustment base offset.
892 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
893
894 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
895 /// the 'this' pointer from the base subobject to the derived subobject.
896 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
897 BaseSubobject Derived) const;
898
899 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
900 /// given virtual member function, its offset in the layout class and its
901 /// final overrider.
902 ThisAdjustment
903 ComputeThisAdjustment(const CXXMethodDecl *MD,
904 CharUnits BaseOffsetInLayoutClass,
905 FinalOverriders::OverriderInfo Overrider);
906
907 /// AddMethod - Add a single virtual member function to the vtable
908 /// components vector.
909 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
910
911 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
912 /// part of the vtable.
913 ///
914 /// Itanium C++ ABI 2.5.2:
915 ///
916 /// struct A { virtual void f(); };
917 /// struct B : virtual public A { int i; };
918 /// struct C : virtual public A { int j; };
919 /// struct D : public B, public C {};
920 ///
921 /// When B and C are declared, A is a primary base in each case, so although
922 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
923 /// adjustment is required and no thunk is generated. However, inside D
924 /// objects, A is no longer a primary base of C, so if we allowed calls to
925 /// C::f() to use the copy of A's vtable in the C subobject, we would need
926 /// to adjust this from C* to B::A*, which would require a third-party
927 /// thunk. Since we require that a call to C::f() first convert to A*,
928 /// C-in-D's copy of A's vtable is never referenced, so this is not
929 /// necessary.
930 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
931 CharUnits BaseOffsetInLayoutClass,
932 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
933 CharUnits FirstBaseOffsetInLayoutClass) const;
934
935
936 /// AddMethods - Add the methods of this base subobject and all its
937 /// primary bases to the vtable components vector.
938 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
939 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
940 CharUnits FirstBaseOffsetInLayoutClass,
941 PrimaryBasesSetVectorTy &PrimaryBases);
942
943 // LayoutVTable - Layout the vtable for the given base class, including its
944 // secondary vtables and any vtables for virtual bases.
945 void LayoutVTable();
946
947 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
948 /// given base subobject, as well as all its secondary vtables.
949 ///
950 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
951 /// or a direct or indirect base of a virtual base.
952 ///
953 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
954 /// in the layout class.
955 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
956 bool BaseIsMorallyVirtual,
957 bool BaseIsVirtualInLayoutClass,
958 CharUnits OffsetInLayoutClass);
959
960 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
961 /// subobject.
962 ///
963 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
964 /// or a direct or indirect base of a virtual base.
965 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
966 CharUnits OffsetInLayoutClass);
967
968 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
969 /// class hierarchy.
970 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
971 CharUnits OffsetInLayoutClass,
972 VisitedVirtualBasesSetTy &VBases);
973
974 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
975 /// given base (excluding any primary bases).
976 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
977 VisitedVirtualBasesSetTy &VBases);
978
979 /// isBuildingConstructionVTable - Return whether this vtable builder is
980 /// building a construction vtable.
981 bool isBuildingConstructorVTable() const {
982 return MostDerivedClass != LayoutClass;
983 }
984
985public:
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000986 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
987 const CXXRecordDecl *MostDerivedClass,
988 CharUnits MostDerivedClassOffset,
989 bool MostDerivedClassIsVirtual,
990 const CXXRecordDecl *LayoutClass)
991 : VTables(VTables), MostDerivedClass(MostDerivedClass),
992 MostDerivedClassOffset(MostDerivedClassOffset),
993 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
994 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
995 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000996 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000997
998 LayoutVTable();
999
David Blaikiebbafb8a2012-03-11 07:00:24 +00001000 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00001001 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001002 }
1003
1004 uint64_t getNumThunks() const {
1005 return Thunks.size();
1006 }
1007
1008 ThunksMapTy::const_iterator thunks_begin() const {
1009 return Thunks.begin();
1010 }
1011
1012 ThunksMapTy::const_iterator thunks_end() const {
1013 return Thunks.end();
1014 }
1015
1016 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1017 return VBaseOffsetOffsets;
1018 }
1019
1020 const AddressPointsMapTy &getAddressPoints() const {
1021 return AddressPoints;
1022 }
1023
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001024 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1025 return MethodVTableIndices.begin();
1026 }
1027
1028 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1029 return MethodVTableIndices.end();
1030 }
1031
Peter Collingbournecfd23562011-09-26 01:57:12 +00001032 /// getNumVTableComponents - Return the number of components in the vtable
1033 /// currently built.
1034 uint64_t getNumVTableComponents() const {
1035 return Components.size();
1036 }
1037
1038 const VTableComponent *vtable_component_begin() const {
1039 return Components.begin();
1040 }
1041
1042 const VTableComponent *vtable_component_end() const {
1043 return Components.end();
1044 }
1045
1046 AddressPointsMapTy::const_iterator address_points_begin() const {
1047 return AddressPoints.begin();
1048 }
1049
1050 AddressPointsMapTy::const_iterator address_points_end() const {
1051 return AddressPoints.end();
1052 }
1053
1054 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1055 return VTableThunks.begin();
1056 }
1057
1058 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1059 return VTableThunks.end();
1060 }
1061
1062 /// dumpLayout - Dump the vtable layout.
1063 void dumpLayout(raw_ostream&);
1064};
1065
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001066void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1067 const ThunkInfo &Thunk) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001068 assert(!isBuildingConstructorVTable() &&
1069 "Can't add thunks for construction vtable");
1070
Craig Topper5603df42013-07-05 19:34:19 +00001071 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1072
Peter Collingbournecfd23562011-09-26 01:57:12 +00001073 // Check if we have this thunk already.
1074 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1075 ThunksVector.end())
1076 return;
1077
1078 ThunksVector.push_back(Thunk);
1079}
1080
1081typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1082
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001083/// Visit all the methods overridden by the given method recursively,
1084/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1085/// indicating whether to continue the recursion for the given overridden
1086/// method (i.e. returning false stops the iteration).
1087template <class VisitorTy>
1088static void
1089visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001090 assert(MD->isVirtual() && "Method is not virtual!");
1091
1092 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1093 E = MD->end_overridden_methods(); I != E; ++I) {
1094 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001095 if (!Visitor.visit(OverriddenMD))
1096 continue;
1097 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001098 }
1099}
1100
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001101namespace {
1102 struct OverriddenMethodsCollector {
1103 OverriddenMethodsSetTy *Methods;
1104
1105 bool visit(const CXXMethodDecl *MD) {
1106 // Don't recurse on this method if we've already collected it.
1107 return Methods->insert(MD);
1108 }
1109 };
1110}
1111
1112/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1113/// the overridden methods that the function decl overrides.
1114static void
1115ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1116 OverriddenMethodsSetTy& OverriddenMethods) {
1117 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1118 visitAllOverriddenMethods(MD, Collector);
1119}
1120
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001121void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001122 // Now go through the method info map and see if any of the methods need
1123 // 'this' pointer adjustments.
1124 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1125 E = MethodInfoMap.end(); I != E; ++I) {
1126 const CXXMethodDecl *MD = I->first;
1127 const MethodInfo &MethodInfo = I->second;
1128
1129 // Ignore adjustments for unused function pointers.
1130 uint64_t VTableIndex = MethodInfo.VTableIndex;
1131 if (Components[VTableIndex].getKind() ==
1132 VTableComponent::CK_UnusedFunctionPointer)
1133 continue;
1134
1135 // Get the final overrider for this method.
1136 FinalOverriders::OverriderInfo Overrider =
1137 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1138
1139 // Check if we need an adjustment at all.
1140 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1141 // When a return thunk is needed by a derived class that overrides a
1142 // virtual base, gcc uses a virtual 'this' adjustment as well.
1143 // While the thunk itself might be needed by vtables in subclasses or
1144 // in construction vtables, there doesn't seem to be a reason for using
1145 // the thunk in this vtable. Still, we do so to match gcc.
1146 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1147 continue;
1148 }
1149
1150 ThisAdjustment ThisAdjustment =
1151 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1152
1153 if (ThisAdjustment.isEmpty())
1154 continue;
1155
1156 // Add it.
1157 VTableThunks[VTableIndex].This = ThisAdjustment;
1158
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001159 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001160 // Add an adjustment for the deleting destructor as well.
1161 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1162 }
1163 }
1164
1165 /// Clear the method info map.
1166 MethodInfoMap.clear();
1167
1168 if (isBuildingConstructorVTable()) {
1169 // We don't need to store thunk information for construction vtables.
1170 return;
1171 }
1172
1173 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1174 E = VTableThunks.end(); I != E; ++I) {
1175 const VTableComponent &Component = Components[I->first];
1176 const ThunkInfo &Thunk = I->second;
1177 const CXXMethodDecl *MD;
1178
1179 switch (Component.getKind()) {
1180 default:
1181 llvm_unreachable("Unexpected vtable component kind!");
1182 case VTableComponent::CK_FunctionPointer:
1183 MD = Component.getFunctionDecl();
1184 break;
1185 case VTableComponent::CK_CompleteDtorPointer:
1186 MD = Component.getDestructorDecl();
1187 break;
1188 case VTableComponent::CK_DeletingDtorPointer:
1189 // We've already added the thunk when we saw the complete dtor pointer.
1190 continue;
1191 }
1192
1193 if (MD->getParent() == MostDerivedClass)
1194 AddThunk(MD, Thunk);
1195 }
1196}
1197
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001198ReturnAdjustment
1199ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001200 ReturnAdjustment Adjustment;
1201
1202 if (!Offset.isEmpty()) {
1203 if (Offset.VirtualBase) {
1204 // Get the virtual base offset offset.
1205 if (Offset.DerivedClass == MostDerivedClass) {
1206 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001207 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001208 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1209 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001210 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001211 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1212 Offset.VirtualBase).getQuantity();
1213 }
1214 }
1215
1216 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1217 }
1218
1219 return Adjustment;
1220}
1221
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001222BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1223 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001224 const CXXRecordDecl *BaseRD = Base.getBase();
1225 const CXXRecordDecl *DerivedRD = Derived.getBase();
1226
1227 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1228 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1229
Benjamin Kramer325d7452013-02-03 18:55:34 +00001230 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001231 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001232
1233 // We have to go through all the paths, and see which one leads us to the
1234 // right base subobject.
1235 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1236 I != E; ++I) {
1237 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1238
1239 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1240
1241 if (Offset.VirtualBase) {
1242 // If we have a virtual base class, the non-virtual offset is relative
1243 // to the virtual base class offset.
1244 const ASTRecordLayout &LayoutClassLayout =
1245 Context.getASTRecordLayout(LayoutClass);
1246
1247 /// Get the virtual base offset, relative to the most derived class
1248 /// layout.
1249 OffsetToBaseSubobject +=
1250 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1251 } else {
1252 // Otherwise, the non-virtual offset is relative to the derived class
1253 // offset.
1254 OffsetToBaseSubobject += Derived.getBaseOffset();
1255 }
1256
1257 // Check if this path gives us the right base subobject.
1258 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1259 // Since we're going from the base class _to_ the derived class, we'll
1260 // invert the non-virtual offset here.
1261 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1262 return Offset;
1263 }
1264 }
1265
1266 return BaseOffset();
1267}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001268
1269ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1270 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1271 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001272 // Ignore adjustments for pure virtual member functions.
1273 if (Overrider.Method->isPure())
1274 return ThisAdjustment();
1275
1276 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1277 BaseOffsetInLayoutClass);
1278
1279 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1280 Overrider.Offset);
1281
1282 // Compute the adjustment offset.
1283 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1284 OverriderBaseSubobject);
1285 if (Offset.isEmpty())
1286 return ThisAdjustment();
1287
1288 ThisAdjustment Adjustment;
1289
1290 if (Offset.VirtualBase) {
1291 // Get the vcall offset map for this virtual base.
1292 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1293
1294 if (VCallOffsets.empty()) {
1295 // We don't have vcall offsets for this virtual base, go ahead and
1296 // build them.
1297 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1298 /*FinalOverriders=*/0,
1299 BaseSubobject(Offset.VirtualBase,
1300 CharUnits::Zero()),
1301 /*BaseIsVirtual=*/true,
1302 /*OffsetInLayoutClass=*/
1303 CharUnits::Zero());
1304
1305 VCallOffsets = Builder.getVCallOffsets();
1306 }
1307
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001308 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001309 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1310 }
1311
1312 // Set the non-virtual part of the adjustment.
1313 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1314
1315 return Adjustment;
1316}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001317
1318void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1319 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001320 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1321 assert(ReturnAdjustment.isEmpty() &&
1322 "Destructor can't have return adjustment!");
1323
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001324 // Add both the complete destructor and the deleting destructor.
1325 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1326 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001327 } else {
1328 // Add the return adjustment if necessary.
1329 if (!ReturnAdjustment.isEmpty())
1330 VTableThunks[Components.size()].Return = ReturnAdjustment;
1331
1332 // Add the function.
1333 Components.push_back(VTableComponent::MakeFunction(MD));
1334 }
1335}
1336
1337/// OverridesIndirectMethodInBase - Return whether the given member function
1338/// overrides any methods in the set of given bases.
1339/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1340/// For example, if we have:
1341///
1342/// struct A { virtual void f(); }
1343/// struct B : A { virtual void f(); }
1344/// struct C : B { virtual void f(); }
1345///
1346/// OverridesIndirectMethodInBase will return true if given C::f as the method
1347/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001348static bool OverridesIndirectMethodInBases(
1349 const CXXMethodDecl *MD,
1350 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001351 if (Bases.count(MD->getParent()))
1352 return true;
1353
1354 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1355 E = MD->end_overridden_methods(); I != E; ++I) {
1356 const CXXMethodDecl *OverriddenMD = *I;
1357
1358 // Check "indirect overriders".
1359 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1360 return true;
1361 }
1362
1363 return false;
1364}
1365
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001366bool ItaniumVTableBuilder::IsOverriderUsed(
1367 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1368 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1369 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001370 // If the base and the first base in the primary base chain have the same
1371 // offsets, then this overrider will be used.
1372 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1373 return true;
1374
1375 // We know now that Base (or a direct or indirect base of it) is a primary
1376 // base in part of the class hierarchy, but not a primary base in the most
1377 // derived class.
1378
1379 // If the overrider is the first base in the primary base chain, we know
1380 // that the overrider will be used.
1381 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1382 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001383
1384 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001385
1386 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1387 PrimaryBases.insert(RD);
1388
1389 // Now traverse the base chain, starting with the first base, until we find
1390 // the base that is no longer a primary base.
1391 while (true) {
1392 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1393 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1394
1395 if (!PrimaryBase)
1396 break;
1397
1398 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001399 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001400 "Primary base should always be at offset 0!");
1401
1402 const ASTRecordLayout &LayoutClassLayout =
1403 Context.getASTRecordLayout(LayoutClass);
1404
1405 // Now check if this is the primary base that is not a primary base in the
1406 // most derived class.
1407 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1408 FirstBaseOffsetInLayoutClass) {
1409 // We found it, stop walking the chain.
1410 break;
1411 }
1412 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001413 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001414 "Primary base should always be at offset 0!");
1415 }
1416
1417 if (!PrimaryBases.insert(PrimaryBase))
1418 llvm_unreachable("Found a duplicate primary base!");
1419
1420 RD = PrimaryBase;
1421 }
1422
1423 // If the final overrider is an override of one of the primary bases,
1424 // then we know that it will be used.
1425 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1426}
1427
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001428typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1429
Peter Collingbournecfd23562011-09-26 01:57:12 +00001430/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1431/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001432/// The Bases are expected to be sorted in a base-to-derived order.
1433static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001434FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001435 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001436 OverriddenMethodsSetTy OverriddenMethods;
1437 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1438
1439 for (int I = Bases.size(), E = 0; I != E; --I) {
1440 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1441
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001442 // Now check the overridden methods.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001443 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1444 E = OverriddenMethods.end(); I != E; ++I) {
1445 const CXXMethodDecl *OverriddenMD = *I;
1446
1447 // We found our overridden method.
1448 if (OverriddenMD->getParent() == PrimaryBase)
1449 return OverriddenMD;
1450 }
1451 }
1452
1453 return 0;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001454}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001455
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001456void ItaniumVTableBuilder::AddMethods(
1457 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1458 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1459 CharUnits FirstBaseOffsetInLayoutClass,
1460 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001461 // Itanium C++ ABI 2.5.2:
1462 // The order of the virtual function pointers in a virtual table is the
1463 // order of declaration of the corresponding member functions in the class.
1464 //
1465 // There is an entry for any virtual function declared in a class,
1466 // whether it is a new function or overrides a base class function,
1467 // unless it overrides a function from the primary base, and conversion
1468 // between their return types does not require an adjustment.
1469
Peter Collingbournecfd23562011-09-26 01:57:12 +00001470 const CXXRecordDecl *RD = Base.getBase();
1471 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1472
1473 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1474 CharUnits PrimaryBaseOffset;
1475 CharUnits PrimaryBaseOffsetInLayoutClass;
1476 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001477 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001478 "Primary vbase should have a zero offset!");
1479
1480 const ASTRecordLayout &MostDerivedClassLayout =
1481 Context.getASTRecordLayout(MostDerivedClass);
1482
1483 PrimaryBaseOffset =
1484 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1485
1486 const ASTRecordLayout &LayoutClassLayout =
1487 Context.getASTRecordLayout(LayoutClass);
1488
1489 PrimaryBaseOffsetInLayoutClass =
1490 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1491 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001492 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001493 "Primary base should have a zero offset!");
1494
1495 PrimaryBaseOffset = Base.getBaseOffset();
1496 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1497 }
1498
1499 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1500 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1501 FirstBaseOffsetInLayoutClass, PrimaryBases);
1502
1503 if (!PrimaryBases.insert(PrimaryBase))
1504 llvm_unreachable("Found a duplicate primary base!");
1505 }
1506
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001507 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1508
1509 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1510 NewVirtualFunctionsTy NewVirtualFunctions;
1511
Peter Collingbournecfd23562011-09-26 01:57:12 +00001512 // Now go through all virtual member functions and add them.
Aaron Ballman2b124d12014-03-13 16:36:16 +00001513 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001514 if (!MD->isVirtual())
1515 continue;
1516
1517 // Get the final overrider.
1518 FinalOverriders::OverriderInfo Overrider =
1519 Overriders.getOverrider(MD, Base.getBaseOffset());
1520
1521 // Check if this virtual member function overrides a method in a primary
1522 // base. If this is the case, and the return type doesn't require adjustment
1523 // then we can just use the member function from the primary base.
1524 if (const CXXMethodDecl *OverriddenMD =
1525 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1526 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1527 OverriddenMD).isEmpty()) {
1528 // Replace the method info of the overridden method with our own
1529 // method.
1530 assert(MethodInfoMap.count(OverriddenMD) &&
1531 "Did not find the overridden method!");
1532 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1533
1534 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1535 OverriddenMethodInfo.VTableIndex);
1536
1537 assert(!MethodInfoMap.count(MD) &&
1538 "Should not have method info for this method yet!");
1539
1540 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1541 MethodInfoMap.erase(OverriddenMD);
1542
1543 // If the overridden method exists in a virtual base class or a direct
1544 // or indirect base class of a virtual base class, we need to emit a
1545 // thunk if we ever have a class hierarchy where the base class is not
1546 // a primary base in the complete object.
1547 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1548 // Compute the this adjustment.
1549 ThisAdjustment ThisAdjustment =
1550 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1551 Overrider);
1552
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001553 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001554 Overrider.Method->getParent() == MostDerivedClass) {
1555
1556 // There's no return adjustment from OverriddenMD and MD,
1557 // but that doesn't mean there isn't one between MD and
1558 // the final overrider.
1559 BaseOffset ReturnAdjustmentOffset =
1560 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1561 ReturnAdjustment ReturnAdjustment =
1562 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1563
1564 // This is a virtual thunk for the most derived class, add it.
1565 AddThunk(Overrider.Method,
1566 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1567 }
1568 }
1569
1570 continue;
1571 }
1572 }
1573
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001574 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1575 if (MD->isImplicit()) {
1576 // Itanium C++ ABI 2.5.2:
1577 // If a class has an implicitly-defined virtual destructor,
1578 // its entries come after the declared virtual function pointers.
1579
1580 assert(!ImplicitVirtualDtor &&
1581 "Did already see an implicit virtual dtor!");
1582 ImplicitVirtualDtor = DD;
1583 continue;
1584 }
1585 }
1586
1587 NewVirtualFunctions.push_back(MD);
1588 }
1589
1590 if (ImplicitVirtualDtor)
1591 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1592
1593 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1594 E = NewVirtualFunctions.end(); I != E; ++I) {
1595 const CXXMethodDecl *MD = *I;
1596
1597 // Get the final overrider.
1598 FinalOverriders::OverriderInfo Overrider =
1599 Overriders.getOverrider(MD, Base.getBaseOffset());
1600
Peter Collingbournecfd23562011-09-26 01:57:12 +00001601 // Insert the method info for this method.
1602 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1603 Components.size());
1604
1605 assert(!MethodInfoMap.count(MD) &&
1606 "Should not have method info for this method yet!");
1607 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1608
1609 // Check if this overrider is going to be used.
1610 const CXXMethodDecl *OverriderMD = Overrider.Method;
1611 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1612 FirstBaseInPrimaryBaseChain,
1613 FirstBaseOffsetInLayoutClass)) {
1614 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1615 continue;
1616 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001617
Peter Collingbournecfd23562011-09-26 01:57:12 +00001618 // Check if this overrider needs a return adjustment.
1619 // We don't want to do this for pure virtual member functions.
1620 BaseOffset ReturnAdjustmentOffset;
1621 if (!OverriderMD->isPure()) {
1622 ReturnAdjustmentOffset =
1623 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1624 }
1625
1626 ReturnAdjustment ReturnAdjustment =
1627 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1628
1629 AddMethod(Overrider.Method, ReturnAdjustment);
1630 }
1631}
1632
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001633void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001634 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1635 CharUnits::Zero()),
1636 /*BaseIsMorallyVirtual=*/false,
1637 MostDerivedClassIsVirtual,
1638 MostDerivedClassOffset);
1639
1640 VisitedVirtualBasesSetTy VBases;
1641
1642 // Determine the primary virtual bases.
1643 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1644 VBases);
1645 VBases.clear();
1646
1647 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1648
1649 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001650 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001651 if (IsAppleKext)
1652 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1653}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001654
1655void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1656 BaseSubobject Base, bool BaseIsMorallyVirtual,
1657 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001658 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1659
1660 // Add vcall and vbase offsets for this vtable.
1661 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1662 Base, BaseIsVirtualInLayoutClass,
1663 OffsetInLayoutClass);
1664 Components.append(Builder.components_begin(), Builder.components_end());
1665
1666 // Check if we need to add these vcall offsets.
1667 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1668 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1669
1670 if (VCallOffsets.empty())
1671 VCallOffsets = Builder.getVCallOffsets();
1672 }
1673
1674 // If we're laying out the most derived class we want to keep track of the
1675 // virtual base class offset offsets.
1676 if (Base.getBase() == MostDerivedClass)
1677 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1678
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001679 // Add the offset to top.
1680 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1681 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001682
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001683 // Next, add the RTTI.
1684 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001685
Peter Collingbournecfd23562011-09-26 01:57:12 +00001686 uint64_t AddressPoint = Components.size();
1687
1688 // Now go through all virtual member functions and add them.
1689 PrimaryBasesSetVectorTy PrimaryBases;
1690 AddMethods(Base, OffsetInLayoutClass,
1691 Base.getBase(), OffsetInLayoutClass,
1692 PrimaryBases);
1693
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001694 const CXXRecordDecl *RD = Base.getBase();
1695 if (RD == MostDerivedClass) {
1696 assert(MethodVTableIndices.empty());
1697 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1698 E = MethodInfoMap.end(); I != E; ++I) {
1699 const CXXMethodDecl *MD = I->first;
1700 const MethodInfo &MI = I->second;
1701 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001702 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1703 = MI.VTableIndex - AddressPoint;
1704 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1705 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001706 } else {
1707 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1708 }
1709 }
1710 }
1711
Peter Collingbournecfd23562011-09-26 01:57:12 +00001712 // Compute 'this' pointer adjustments.
1713 ComputeThisAdjustments();
1714
1715 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001716 while (true) {
1717 AddressPoints.insert(std::make_pair(
1718 BaseSubobject(RD, OffsetInLayoutClass),
1719 AddressPoint));
1720
1721 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1722 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1723
1724 if (!PrimaryBase)
1725 break;
1726
1727 if (Layout.isPrimaryBaseVirtual()) {
1728 // Check if this virtual primary base is a primary base in the layout
1729 // class. If it's not, we don't want to add it.
1730 const ASTRecordLayout &LayoutClassLayout =
1731 Context.getASTRecordLayout(LayoutClass);
1732
1733 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1734 OffsetInLayoutClass) {
1735 // We don't want to add this class (or any of its primary bases).
1736 break;
1737 }
1738 }
1739
1740 RD = PrimaryBase;
1741 }
1742
1743 // Layout secondary vtables.
1744 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1745}
1746
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001747void
1748ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1749 bool BaseIsMorallyVirtual,
1750 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001751 // Itanium C++ ABI 2.5.2:
1752 // Following the primary virtual table of a derived class are secondary
1753 // virtual tables for each of its proper base classes, except any primary
1754 // base(s) with which it shares its primary virtual table.
1755
1756 const CXXRecordDecl *RD = Base.getBase();
1757 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1758 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1759
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001760 for (const auto &B : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001761 // Ignore virtual bases, we'll emit them later.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001762 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001763 continue;
1764
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001765 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001766
1767 // Ignore bases that don't have a vtable.
1768 if (!BaseDecl->isDynamicClass())
1769 continue;
1770
1771 if (isBuildingConstructorVTable()) {
1772 // Itanium C++ ABI 2.6.4:
1773 // Some of the base class subobjects may not need construction virtual
1774 // tables, which will therefore not be present in the construction
1775 // virtual table group, even though the subobject virtual tables are
1776 // present in the main virtual table group for the complete object.
1777 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1778 continue;
1779 }
1780
1781 // Get the base offset of this base.
1782 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1783 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1784
1785 CharUnits BaseOffsetInLayoutClass =
1786 OffsetInLayoutClass + RelativeBaseOffset;
1787
1788 // Don't emit a secondary vtable for a primary base. We might however want
1789 // to emit secondary vtables for other bases of this base.
1790 if (BaseDecl == PrimaryBase) {
1791 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1792 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1793 continue;
1794 }
1795
1796 // Layout the primary vtable (and any secondary vtables) for this base.
1797 LayoutPrimaryAndSecondaryVTables(
1798 BaseSubobject(BaseDecl, BaseOffset),
1799 BaseIsMorallyVirtual,
1800 /*BaseIsVirtualInLayoutClass=*/false,
1801 BaseOffsetInLayoutClass);
1802 }
1803}
1804
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001805void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1806 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1807 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001808 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1809
1810 // Check if this base has a primary base.
1811 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1812
1813 // Check if it's virtual.
1814 if (Layout.isPrimaryBaseVirtual()) {
1815 bool IsPrimaryVirtualBase = true;
1816
1817 if (isBuildingConstructorVTable()) {
1818 // Check if the base is actually a primary base in the class we use for
1819 // layout.
1820 const ASTRecordLayout &LayoutClassLayout =
1821 Context.getASTRecordLayout(LayoutClass);
1822
1823 CharUnits PrimaryBaseOffsetInLayoutClass =
1824 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1825
1826 // We know that the base is not a primary base in the layout class if
1827 // the base offsets are different.
1828 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1829 IsPrimaryVirtualBase = false;
1830 }
1831
1832 if (IsPrimaryVirtualBase)
1833 PrimaryVirtualBases.insert(PrimaryBase);
1834 }
1835 }
1836
1837 // Traverse bases, looking for more primary virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001838 for (const auto &B : RD->bases()) {
1839 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001840
1841 CharUnits BaseOffsetInLayoutClass;
1842
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001843 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001844 if (!VBases.insert(BaseDecl))
1845 continue;
1846
1847 const ASTRecordLayout &LayoutClassLayout =
1848 Context.getASTRecordLayout(LayoutClass);
1849
1850 BaseOffsetInLayoutClass =
1851 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1852 } else {
1853 BaseOffsetInLayoutClass =
1854 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1855 }
1856
1857 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1858 }
1859}
1860
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001861void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1862 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001863 // Itanium C++ ABI 2.5.2:
1864 // Then come the virtual base virtual tables, also in inheritance graph
1865 // order, and again excluding primary bases (which share virtual tables with
1866 // the classes for which they are primary).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001867 for (const auto &B : RD->bases()) {
1868 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001869
1870 // Check if this base needs a vtable. (If it's virtual, not a primary base
1871 // of some other class, and we haven't visited it before).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001872 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001873 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1874 const ASTRecordLayout &MostDerivedClassLayout =
1875 Context.getASTRecordLayout(MostDerivedClass);
1876 CharUnits BaseOffset =
1877 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1878
1879 const ASTRecordLayout &LayoutClassLayout =
1880 Context.getASTRecordLayout(LayoutClass);
1881 CharUnits BaseOffsetInLayoutClass =
1882 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1883
1884 LayoutPrimaryAndSecondaryVTables(
1885 BaseSubobject(BaseDecl, BaseOffset),
1886 /*BaseIsMorallyVirtual=*/true,
1887 /*BaseIsVirtualInLayoutClass=*/true,
1888 BaseOffsetInLayoutClass);
1889 }
1890
1891 // We only need to check the base for virtual base vtables if it actually
1892 // has virtual bases.
1893 if (BaseDecl->getNumVBases())
1894 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1895 }
1896}
1897
1898/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001899void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001900 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001901 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001902
1903 if (isBuildingConstructorVTable()) {
1904 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001905 MostDerivedClass->printQualifiedName(Out);
1906 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001907 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001908 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001909 } else {
1910 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001911 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001912 }
1913 Out << "' (" << Components.size() << " entries).\n";
1914
1915 // Iterate through the address points and insert them into a new map where
1916 // they are keyed by the index and not the base object.
1917 // Since an address point can be shared by multiple subobjects, we use an
1918 // STL multimap.
1919 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1920 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1921 E = AddressPoints.end(); I != E; ++I) {
1922 const BaseSubobject& Base = I->first;
1923 uint64_t Index = I->second;
1924
1925 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1926 }
1927
1928 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1929 uint64_t Index = I;
1930
1931 Out << llvm::format("%4d | ", I);
1932
1933 const VTableComponent &Component = Components[I];
1934
1935 // Dump the component.
1936 switch (Component.getKind()) {
1937
1938 case VTableComponent::CK_VCallOffset:
1939 Out << "vcall_offset ("
1940 << Component.getVCallOffset().getQuantity()
1941 << ")";
1942 break;
1943
1944 case VTableComponent::CK_VBaseOffset:
1945 Out << "vbase_offset ("
1946 << Component.getVBaseOffset().getQuantity()
1947 << ")";
1948 break;
1949
1950 case VTableComponent::CK_OffsetToTop:
1951 Out << "offset_to_top ("
1952 << Component.getOffsetToTop().getQuantity()
1953 << ")";
1954 break;
1955
1956 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001957 Component.getRTTIDecl()->printQualifiedName(Out);
1958 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001959 break;
1960
1961 case VTableComponent::CK_FunctionPointer: {
1962 const CXXMethodDecl *MD = Component.getFunctionDecl();
1963
1964 std::string Str =
1965 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1966 MD);
1967 Out << Str;
1968 if (MD->isPure())
1969 Out << " [pure]";
1970
David Blaikie596d2ca2012-10-16 20:25:33 +00001971 if (MD->isDeleted())
1972 Out << " [deleted]";
1973
Peter Collingbournecfd23562011-09-26 01:57:12 +00001974 ThunkInfo Thunk = VTableThunks.lookup(I);
1975 if (!Thunk.isEmpty()) {
1976 // If this function pointer has a return adjustment, dump it.
1977 if (!Thunk.Return.isEmpty()) {
1978 Out << "\n [return adjustment: ";
1979 Out << Thunk.Return.NonVirtual << " non-virtual";
1980
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001981 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1982 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001983 Out << " vbase offset offset";
1984 }
1985
1986 Out << ']';
1987 }
1988
1989 // If this function pointer has a 'this' pointer adjustment, dump it.
1990 if (!Thunk.This.isEmpty()) {
1991 Out << "\n [this adjustment: ";
1992 Out << Thunk.This.NonVirtual << " non-virtual";
1993
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001994 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1995 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001996 Out << " vcall offset offset";
1997 }
1998
1999 Out << ']';
2000 }
2001 }
2002
2003 break;
2004 }
2005
2006 case VTableComponent::CK_CompleteDtorPointer:
2007 case VTableComponent::CK_DeletingDtorPointer: {
2008 bool IsComplete =
2009 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2010
2011 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2012
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002013 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002014 if (IsComplete)
2015 Out << "() [complete]";
2016 else
2017 Out << "() [deleting]";
2018
2019 if (DD->isPure())
2020 Out << " [pure]";
2021
2022 ThunkInfo Thunk = VTableThunks.lookup(I);
2023 if (!Thunk.isEmpty()) {
2024 // If this destructor has a 'this' pointer adjustment, dump it.
2025 if (!Thunk.This.isEmpty()) {
2026 Out << "\n [this adjustment: ";
2027 Out << Thunk.This.NonVirtual << " non-virtual";
2028
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002029 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2030 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002031 Out << " vcall offset offset";
2032 }
2033
2034 Out << ']';
2035 }
2036 }
2037
2038 break;
2039 }
2040
2041 case VTableComponent::CK_UnusedFunctionPointer: {
2042 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2043
2044 std::string Str =
2045 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2046 MD);
2047 Out << "[unused] " << Str;
2048 if (MD->isPure())
2049 Out << " [pure]";
2050 }
2051
2052 }
2053
2054 Out << '\n';
2055
2056 // Dump the next address point.
2057 uint64_t NextIndex = Index + 1;
2058 if (AddressPointsByIndex.count(NextIndex)) {
2059 if (AddressPointsByIndex.count(NextIndex) == 1) {
2060 const BaseSubobject &Base =
2061 AddressPointsByIndex.find(NextIndex)->second;
2062
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002063 Out << " -- (";
2064 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002065 Out << ", " << Base.getBaseOffset().getQuantity();
2066 Out << ") vtable address --\n";
2067 } else {
2068 CharUnits BaseOffset =
2069 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2070
2071 // We store the class names in a set to get a stable order.
2072 std::set<std::string> ClassNames;
2073 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2074 AddressPointsByIndex.lower_bound(NextIndex), E =
2075 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2076 assert(I->second.getBaseOffset() == BaseOffset &&
2077 "Invalid base offset!");
2078 const CXXRecordDecl *RD = I->second.getBase();
2079 ClassNames.insert(RD->getQualifiedNameAsString());
2080 }
2081
2082 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2083 E = ClassNames.end(); I != E; ++I) {
2084 Out << " -- (" << *I;
2085 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2086 }
2087 }
2088 }
2089 }
2090
2091 Out << '\n';
2092
2093 if (isBuildingConstructorVTable())
2094 return;
2095
2096 if (MostDerivedClass->getNumVBases()) {
2097 // We store the virtual base class names and their offsets in a map to get
2098 // a stable order.
2099
2100 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2101 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2102 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2103 std::string ClassName = I->first->getQualifiedNameAsString();
2104 CharUnits OffsetOffset = I->second;
2105 ClassNamesAndOffsets.insert(
2106 std::make_pair(ClassName, OffsetOffset));
2107 }
2108
2109 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002110 MostDerivedClass->printQualifiedName(Out);
2111 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002112 Out << ClassNamesAndOffsets.size();
2113 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2114
2115 for (std::map<std::string, CharUnits>::const_iterator I =
2116 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2117 I != E; ++I)
2118 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2119
2120 Out << "\n";
2121 }
2122
2123 if (!Thunks.empty()) {
2124 // We store the method names in a map to get a stable order.
2125 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2126
2127 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2128 I != E; ++I) {
2129 const CXXMethodDecl *MD = I->first;
2130 std::string MethodName =
2131 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2132 MD);
2133
2134 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2135 }
2136
2137 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2138 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2139 I != E; ++I) {
2140 const std::string &MethodName = I->first;
2141 const CXXMethodDecl *MD = I->second;
2142
2143 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002144 std::sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002145 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2146 assert(LHS.Method == 0 && RHS.Method == 0);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002147 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002148 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002149
2150 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2151 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2152
2153 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2154 const ThunkInfo &Thunk = ThunksVector[I];
2155
2156 Out << llvm::format("%4d | ", I);
2157
2158 // If this function pointer has a return pointer adjustment, dump it.
2159 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002160 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002161 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002162 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2163 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002164 Out << " vbase offset offset";
2165 }
2166
2167 if (!Thunk.This.isEmpty())
2168 Out << "\n ";
2169 }
2170
2171 // If this function pointer has a 'this' pointer adjustment, dump it.
2172 if (!Thunk.This.isEmpty()) {
2173 Out << "this adjustment: ";
2174 Out << Thunk.This.NonVirtual << " non-virtual";
2175
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002176 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2177 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002178 Out << " vcall offset offset";
2179 }
2180 }
2181
2182 Out << '\n';
2183 }
2184
2185 Out << '\n';
2186 }
2187 }
2188
2189 // Compute the vtable indices for all the member functions.
2190 // Store them in a map keyed by the index so we'll get a sorted table.
2191 std::map<uint64_t, std::string> IndicesMap;
2192
Aaron Ballman2b124d12014-03-13 16:36:16 +00002193 for (const auto *MD : MostDerivedClass->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002194 // We only want virtual member functions.
2195 if (!MD->isVirtual())
2196 continue;
2197
2198 std::string MethodName =
2199 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2200 MD);
2201
2202 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002203 GlobalDecl GD(DD, Dtor_Complete);
2204 assert(MethodVTableIndices.count(GD));
2205 uint64_t VTableIndex = MethodVTableIndices[GD];
2206 IndicesMap[VTableIndex] = MethodName + " [complete]";
2207 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002208 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002209 assert(MethodVTableIndices.count(MD));
2210 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002211 }
2212 }
2213
2214 // Print the vtable indices for all the member functions.
2215 if (!IndicesMap.empty()) {
2216 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002217 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002218 Out << "' (" << IndicesMap.size() << " entries).\n";
2219
2220 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2221 E = IndicesMap.end(); I != E; ++I) {
2222 uint64_t VTableIndex = I->first;
2223 const std::string &MethodName = I->second;
2224
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002225 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002226 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002227 }
2228 }
2229
2230 Out << '\n';
2231}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002232}
2233
2234VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2235 const VTableComponent *VTableComponents,
2236 uint64_t NumVTableThunks,
2237 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002238 const AddressPointsMapTy &AddressPoints,
2239 bool IsMicrosoftABI)
Peter Collingbournecfd23562011-09-26 01:57:12 +00002240 : NumVTableComponents(NumVTableComponents),
2241 VTableComponents(new VTableComponent[NumVTableComponents]),
2242 NumVTableThunks(NumVTableThunks),
2243 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002244 AddressPoints(AddressPoints),
2245 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002246 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramere2980632012-04-14 14:13:43 +00002247 this->VTableComponents.get());
2248 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2249 this->VTableThunks.get());
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002250 std::sort(this->VTableThunks.get(),
2251 this->VTableThunks.get() + NumVTableThunks,
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002252 [](const VTableLayout::VTableThunkTy &LHS,
2253 const VTableLayout::VTableThunkTy &RHS) {
2254 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2255 "Different thunks should have unique indices!");
2256 return LHS.first < RHS.first;
2257 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002258}
2259
Benjamin Kramere2980632012-04-14 14:13:43 +00002260VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002261
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002262ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002263 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002264
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002265ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002266 llvm::DeleteContainerSeconds(VTableLayouts);
2267}
2268
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002269uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002270 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2271 if (I != MethodVTableIndices.end())
2272 return I->second;
2273
2274 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2275
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002276 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002277
2278 I = MethodVTableIndices.find(GD);
2279 assert(I != MethodVTableIndices.end() && "Did not find index!");
2280 return I->second;
2281}
2282
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002283CharUnits
2284ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2285 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002286 ClassPairTy ClassPair(RD, VBase);
2287
2288 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2289 VirtualBaseClassOffsetOffsets.find(ClassPair);
2290 if (I != VirtualBaseClassOffsetOffsets.end())
2291 return I->second;
2292
2293 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2294 BaseSubobject(RD, CharUnits::Zero()),
2295 /*BaseIsVirtual=*/false,
2296 /*OffsetInLayoutClass=*/CharUnits::Zero());
2297
2298 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2299 Builder.getVBaseOffsetOffsets().begin(),
2300 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2301 // Insert all types.
2302 ClassPairTy ClassPair(RD, I->first);
2303
2304 VirtualBaseClassOffsetOffsets.insert(
2305 std::make_pair(ClassPair, I->second));
2306 }
2307
2308 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2309 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2310
2311 return I->second;
2312}
2313
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002314static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002315 SmallVector<VTableLayout::VTableThunkTy, 1>
2316 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002317
2318 return new VTableLayout(Builder.getNumVTableComponents(),
2319 Builder.vtable_component_begin(),
2320 VTableThunks.size(),
2321 VTableThunks.data(),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002322 Builder.getAddressPoints(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002323 /*IsMicrosoftABI=*/false);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002324}
2325
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002326void
2327ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002328 const VTableLayout *&Entry = VTableLayouts[RD];
2329
2330 // Check if we've computed this information before.
2331 if (Entry)
2332 return;
2333
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002334 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2335 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002336 Entry = CreateVTableLayout(Builder);
2337
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002338 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2339 Builder.vtable_indices_end());
2340
Peter Collingbournecfd23562011-09-26 01:57:12 +00002341 // Add the known thunks.
2342 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2343
2344 // If we don't have the vbase information for this class, insert it.
2345 // getVirtualBaseOffsetOffset will compute it separately without computing
2346 // the rest of the vtable related information.
2347 if (!RD->getNumVBases())
2348 return;
2349
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002350 const CXXRecordDecl *VBase =
2351 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002352
2353 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2354 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002355
2356 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2357 I = Builder.getVBaseOffsetOffsets().begin(),
2358 E = Builder.getVBaseOffsetOffsets().end();
2359 I != E; ++I) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002360 // Insert all types.
2361 ClassPairTy ClassPair(RD, I->first);
2362
2363 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2364 }
2365}
2366
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002367VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2368 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2369 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2370 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2371 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002372 return CreateVTableLayout(Builder);
2373}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002374
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002375namespace {
2376
2377// Vtables in the Microsoft ABI are different from the Itanium ABI.
2378//
2379// The main differences are:
2380// 1. Separate vftable and vbtable.
2381//
2382// 2. Each subobject with a vfptr gets its own vftable rather than an address
2383// point in a single vtable shared between all the subobjects.
2384// Each vftable is represented by a separate section and virtual calls
2385// must be done using the vftable which has a slot for the function to be
2386// called.
2387//
2388// 3. Virtual method definitions expect their 'this' parameter to point to the
2389// first vfptr whose table provides a compatible overridden method. In many
2390// cases, this permits the original vf-table entry to directly call
2391// the method instead of passing through a thunk.
2392//
2393// A compatible overridden method is one which does not have a non-trivial
2394// covariant-return adjustment.
2395//
2396// The first vfptr is the one with the lowest offset in the complete-object
2397// layout of the defining class, and the method definition will subtract
2398// that constant offset from the parameter value to get the real 'this'
2399// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2400// function defined in a virtual base is overridden in a more derived
2401// virtual base and these bases have a reverse order in the complete
2402// object), the vf-table may require a this-adjustment thunk.
2403//
2404// 4. vftables do not contain new entries for overrides that merely require
2405// this-adjustment. Together with #3, this keeps vf-tables smaller and
2406// eliminates the need for this-adjustment thunks in many cases, at the cost
2407// of often requiring redundant work to adjust the "this" pointer.
2408//
2409// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2410// Vtordisps are emitted into the class layout if a class has
2411// a) a user-defined ctor/dtor
2412// and
2413// b) a method overriding a method in a virtual base.
2414
2415class VFTableBuilder {
2416public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002417 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002418
2419 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2420 MethodVFTableLocationsTy;
2421
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002422 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2423 method_locations_range;
2424
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002425private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002426 /// VTables - Global vtable information.
2427 MicrosoftVTableContext &VTables;
2428
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002429 /// Context - The ASTContext which we will use for layout information.
2430 ASTContext &Context;
2431
2432 /// MostDerivedClass - The most derived class for which we're building this
2433 /// vtable.
2434 const CXXRecordDecl *MostDerivedClass;
2435
2436 const ASTRecordLayout &MostDerivedClassLayout;
2437
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002438 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002439
2440 /// FinalOverriders - The final overriders of the most derived class.
2441 const FinalOverriders Overriders;
2442
2443 /// Components - The components of the vftable being built.
2444 SmallVector<VTableComponent, 64> Components;
2445
2446 MethodVFTableLocationsTy MethodVFTableLocations;
2447
2448 /// MethodInfo - Contains information about a method in a vtable.
2449 /// (Used for computing 'this' pointer adjustment thunks.
2450 struct MethodInfo {
2451 /// VBTableIndex - The nonzero index in the vbtable that
2452 /// this method's base has, or zero.
2453 const uint64_t VBTableIndex;
2454
2455 /// VFTableIndex - The index in the vftable that this method has.
2456 const uint64_t VFTableIndex;
2457
2458 /// Shadowed - Indicates if this vftable slot is shadowed by
2459 /// a slot for a covariant-return override. If so, it shouldn't be printed
2460 /// or used for vcalls in the most derived class.
2461 bool Shadowed;
2462
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002463 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2464 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002465 Shadowed(false) {}
2466
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002467 MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002468 };
2469
2470 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2471
2472 /// MethodInfoMap - The information for all methods in the vftable we're
2473 /// currently building.
2474 MethodInfoMapTy MethodInfoMap;
2475
2476 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2477
2478 /// VTableThunks - The thunks by vftable index in the vftable currently being
2479 /// built.
2480 VTableThunksMapTy VTableThunks;
2481
2482 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2483 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2484
2485 /// Thunks - A map that contains all the thunks needed for all methods in the
2486 /// most derived class for which the vftable is currently being built.
2487 ThunksMapTy Thunks;
2488
2489 /// AddThunk - Add a thunk for the given method.
2490 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2491 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2492
2493 // Check if we have this thunk already.
2494 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2495 ThunksVector.end())
2496 return;
2497
2498 ThunksVector.push_back(Thunk);
2499 }
2500
2501 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002502 /// method, relative to the beginning of the MostDerivedClass.
2503 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002504
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002505 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2506 CharUnits ThisOffset, ThisAdjustment &TA);
2507
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002508 /// AddMethod - Add a single virtual member function to the vftable
2509 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002510 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002511 if (!TI.isEmpty()) {
2512 VTableThunks[Components.size()] = TI;
2513 AddThunk(MD, TI);
2514 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002515 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002516 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002517 "Destructor can't have return adjustment!");
2518 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2519 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002520 Components.push_back(VTableComponent::MakeFunction(MD));
2521 }
2522 }
2523
Reid Kleckner558cab22013-12-27 19:45:53 +00002524 bool NeedsReturnAdjustingThunk(const CXXMethodDecl *MD);
Reid Kleckner604c8b42013-12-27 19:43:59 +00002525
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002526 /// AddMethods - Add the methods of this base subobject and the relevant
2527 /// subbases to the vftable we're currently laying out.
2528 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2529 const CXXRecordDecl *LastVBase,
2530 BasesSetVectorTy &VisitedBases);
2531
2532 void LayoutVFTable() {
2533 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2534 // pointing to the middle of a section.
2535
2536 BasesSetVectorTy VisitedBases;
2537 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2538 VisitedBases);
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002539 assert(Components.size() && "vftable can't be empty");
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002540
2541 assert(MethodVFTableLocations.empty());
2542 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2543 E = MethodInfoMap.end(); I != E; ++I) {
2544 const CXXMethodDecl *MD = I->first;
2545 const MethodInfo &MI = I->second;
2546 // Skip the methods that the MostDerivedClass didn't override
2547 // and the entries shadowed by return adjusting thunks.
2548 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2549 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002550 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2551 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002552 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2553 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2554 } else {
2555 MethodVFTableLocations[MD] = Loc;
2556 }
2557 }
2558 }
2559
2560 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2561 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2562 unsigned DiagID = Diags.getCustomDiagID(
2563 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2564 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2565 }
2566
2567public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002568 VFTableBuilder(MicrosoftVTableContext &VTables,
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002569 const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002570 : VTables(VTables),
2571 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002572 MostDerivedClass(MostDerivedClass),
2573 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002574 WhichVFPtr(*Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002575 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2576 LayoutVFTable();
2577
2578 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002579 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002580 }
2581
2582 uint64_t getNumThunks() const { return Thunks.size(); }
2583
2584 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2585
2586 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2587
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002588 method_locations_range vtable_locations() const {
2589 return method_locations_range(MethodVFTableLocations.begin(),
2590 MethodVFTableLocations.end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002591 }
2592
2593 uint64_t getNumVTableComponents() const { return Components.size(); }
2594
2595 const VTableComponent *vtable_component_begin() const {
2596 return Components.begin();
2597 }
2598
2599 const VTableComponent *vtable_component_end() const {
2600 return Components.end();
2601 }
2602
2603 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2604 return VTableThunks.begin();
2605 }
2606
2607 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2608 return VTableThunks.end();
2609 }
2610
2611 void dumpLayout(raw_ostream &);
2612};
2613
Reid Klecknerb40a27d2014-01-03 00:14:35 +00002614} // end namespace
2615
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002616/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2617/// that define the given method.
2618struct InitialOverriddenDefinitionCollector {
2619 BasesSetVectorTy Bases;
2620 OverriddenMethodsSetTy VisitedOverriddenMethods;
2621
2622 bool visit(const CXXMethodDecl *OverriddenMD) {
2623 if (OverriddenMD->size_overridden_methods() == 0)
2624 Bases.insert(OverriddenMD->getParent());
2625 // Don't recurse on this method if we've already collected it.
2626 return VisitedOverriddenMethods.insert(OverriddenMD);
2627 }
2628};
2629
2630static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2631 CXXBasePath &Path, void *BasesSet) {
2632 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2633 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2634}
2635
2636CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002637VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002638 InitialOverriddenDefinitionCollector Collector;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002639 visitAllOverriddenMethods(Overrider.Method, Collector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002640
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002641 // If there are no overrides then 'this' is located
2642 // in the base that defines the method.
2643 if (Collector.Bases.size() == 0)
2644 return Overrider.Offset;
2645
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002646 CXXBasePaths Paths;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002647 Overrider.Method->getParent()->lookupInBases(BaseInSet, &Collector.Bases,
2648 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002649
2650 // This will hold the smallest this offset among overridees of MD.
2651 // This implies that an offset of a non-virtual base will dominate an offset
2652 // of a virtual base to potentially reduce the number of thunks required
2653 // in the derived classes that inherit this method.
2654 CharUnits Ret;
2655 bool First = true;
2656
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002657 const ASTRecordLayout &OverriderRDLayout =
2658 Context.getASTRecordLayout(Overrider.Method->getParent());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002659 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2660 I != E; ++I) {
2661 const CXXBasePath &Path = (*I);
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002662 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002663 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002664
2665 // For each path from the overrider to the parents of the overridden methods,
2666 // traverse the path, calculating the this offset in the most derived class.
2667 for (int J = 0, F = Path.size(); J != F; ++J) {
2668 const CXXBasePathElement &Element = Path[J];
2669 QualType CurTy = Element.Base->getType();
2670 const CXXRecordDecl *PrevRD = Element.Class,
2671 *CurRD = CurTy->getAsCXXRecordDecl();
2672 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2673
2674 if (Element.Base->isVirtual()) {
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002675 // The interesting things begin when you have virtual inheritance.
2676 // The final overrider will use a static adjustment equal to the offset
2677 // of the vbase in the final overrider class.
2678 // For example, if the final overrider is in a vbase B of the most
2679 // derived class and it overrides a method of the B's own vbase A,
2680 // it uses A* as "this". In its prologue, it can cast A* to B* with
2681 // a static offset. This offset is used regardless of the actual
2682 // offset of A from B in the most derived class, requiring an
2683 // this-adjusting thunk in the vftable if A and B are laid out
2684 // differently in the most derived class.
2685 LastVBaseOffset = ThisOffset =
2686 Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002687 } else {
2688 ThisOffset += Layout.getBaseClassOffset(CurRD);
2689 }
2690 }
2691
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002692 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002693 if (LastVBaseOffset.isZero()) {
2694 // If a "Base" class has at least one non-virtual base with a virtual
2695 // destructor, the "Base" virtual destructor will take the address
2696 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002697 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002698 } else {
2699 // A virtual destructor of a virtual base takes the address of the
2700 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002701 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002702 }
2703 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002704
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002705 if (Ret > ThisOffset || First) {
2706 First = false;
2707 Ret = ThisOffset;
2708 }
2709 }
2710
2711 assert(!First && "Method not found in the given subobject?");
2712 return Ret;
2713}
2714
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002715void VFTableBuilder::CalculateVtordispAdjustment(
2716 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2717 ThisAdjustment &TA) {
2718 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2719 MostDerivedClassLayout.getVBaseOffsetsMap();
2720 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002721 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002722 assert(VBaseMapEntry != VBaseMap.end());
2723
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002724 // If there's no vtordisp or the final overrider is defined in the same vbase
2725 // as the initial declaration, we don't need any vtordisp adjustment.
2726 if (!VBaseMapEntry->second.hasVtorDisp() ||
2727 Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002728 return;
2729
2730 // OK, now we know we need to use a vtordisp thunk.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002731 // The implicit vtordisp field is located right before the vbase.
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002732 CharUnits VFPtrVBaseOffset = VBaseMapEntry->second.VBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002733 TA.Virtual.Microsoft.VtordispOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002734 (VFPtrVBaseOffset - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002735
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002736 // A simple vtordisp thunk will suffice if the final overrider is defined
2737 // in either the most derived class or its non-virtual base.
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002738 if (Overrider.Method->getParent() == MostDerivedClass ||
2739 !Overrider.VirtualBase)
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002740 return;
2741
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002742 // Otherwise, we need to do use the dynamic offset of the final overrider
2743 // in order to get "this" adjustment right.
2744 TA.Virtual.Microsoft.VBPtrOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002745 (VFPtrVBaseOffset + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002746 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2747 TA.Virtual.Microsoft.VBOffsetOffset =
2748 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002749 VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002750
2751 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2752}
2753
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002754static void GroupNewVirtualOverloads(
2755 const CXXRecordDecl *RD,
2756 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2757 // Put the virtual methods into VirtualMethods in the proper order:
2758 // 1) Group overloads by declaration name. New groups are added to the
2759 // vftable in the order of their first declarations in this class
Reid Kleckner6701de22014-02-19 22:06:10 +00002760 // (including overrides and non-virtual methods).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002761 // 2) In each group, new overloads appear in the reverse order of declaration.
2762 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2763 SmallVector<MethodGroup, 10> Groups;
2764 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2765 VisitedGroupIndicesTy VisitedGroupIndices;
Aaron Ballman2b124d12014-03-13 16:36:16 +00002766 for (const auto *MD : RD->methods()) {
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002767 VisitedGroupIndicesTy::iterator J;
2768 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002769 std::tie(J, Inserted) = VisitedGroupIndices.insert(
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002770 std::make_pair(MD->getDeclName(), Groups.size()));
2771 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002772 Groups.push_back(MethodGroup());
Aaron Ballman2b124d12014-03-13 16:36:16 +00002773 if (MD->isVirtual())
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002774 Groups[J->second].push_back(MD);
2775 }
2776
2777 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2778 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2779}
2780
Reid Kleckner604c8b42013-12-27 19:43:59 +00002781/// We need a return adjusting thunk for this method if its return type is
2782/// not trivially convertible to the return type of any of its overridden
2783/// methods.
2784bool VFTableBuilder::NeedsReturnAdjustingThunk(const CXXMethodDecl *MD) {
2785 OverriddenMethodsSetTy OverriddenMethods;
2786 ComputeAllOverriddenMethods(MD, OverriddenMethods);
2787 for (OverriddenMethodsSetTy::iterator I = OverriddenMethods.begin(),
2788 E = OverriddenMethods.end();
2789 I != E; ++I) {
2790 const CXXMethodDecl *OverriddenMD = *I;
2791 BaseOffset Adjustment =
2792 ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD);
2793 if (!Adjustment.isEmpty())
2794 return true;
2795 }
2796 return false;
2797}
2798
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002799static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2800 for (const auto &B : RD->bases()) {
2801 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2802 return true;
2803 }
2804 return false;
2805}
2806
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002807void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2808 const CXXRecordDecl *LastVBase,
2809 BasesSetVectorTy &VisitedBases) {
2810 const CXXRecordDecl *RD = Base.getBase();
2811 if (!RD->isPolymorphic())
2812 return;
2813
2814 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2815
2816 // See if this class expands a vftable of the base we look at, which is either
2817 // the one defined by the vfptr base path or the primary base of the current class.
2818 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2819 CharUnits NextBaseOffset;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002820 if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2821 NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002822 if (isDirectVBase(NextBase, RD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002823 NextLastVBase = NextBase;
2824 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2825 } else {
2826 NextBaseOffset =
2827 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2828 }
2829 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2830 assert(!Layout.isPrimaryBaseVirtual() &&
2831 "No primary virtual bases in this ABI");
2832 NextBase = PrimaryBase;
2833 NextBaseOffset = Base.getBaseOffset();
2834 }
2835
2836 if (NextBase) {
2837 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2838 NextLastVBase, VisitedBases);
2839 if (!VisitedBases.insert(NextBase))
2840 llvm_unreachable("Found a duplicate primary base!");
2841 }
2842
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002843 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2844 // Put virtual methods in the proper order.
2845 GroupNewVirtualOverloads(RD, VirtualMethods);
2846
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002847 // Now go through all virtual member functions and add them to the current
2848 // vftable. This is done by
2849 // - replacing overridden methods in their existing slots, as long as they
2850 // don't require return adjustment; calculating This adjustment if needed.
2851 // - adding new slots for methods of the current base not present in any
2852 // sub-bases;
2853 // - adding new slots for methods that require Return adjustment.
2854 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002855 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2856 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002857
2858 FinalOverriders::OverriderInfo Overrider =
2859 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002860 const CXXMethodDecl *OverriderMD = Overrider.Method;
2861 const CXXMethodDecl *OverriddenMD =
2862 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002863
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002864 ThisAdjustment ThisAdjustmentOffset;
2865 bool ReturnAdjustingThunk = false;
2866 CharUnits ThisOffset = ComputeThisOffset(Overrider);
2867 ThisAdjustmentOffset.NonVirtual =
2868 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
2869 if ((OverriddenMD || OverriderMD != MD) &&
2870 WhichVFPtr.getVBaseWithVPtr())
2871 CalculateVtordispAdjustment(Overrider, ThisOffset, ThisAdjustmentOffset);
2872
2873 if (OverriddenMD) {
2874 // If MD overrides anything in this vftable, we need to update the entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002875 MethodInfoMapTy::iterator OverriddenMDIterator =
2876 MethodInfoMap.find(OverriddenMD);
2877
2878 // If the overridden method went to a different vftable, skip it.
2879 if (OverriddenMDIterator == MethodInfoMap.end())
2880 continue;
2881
2882 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2883
Reid Kleckner604c8b42013-12-27 19:43:59 +00002884 if (!NeedsReturnAdjustingThunk(MD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002885 // No return adjustment needed - just replace the overridden method info
2886 // with the current info.
2887 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2888 OverriddenMethodInfo.VFTableIndex);
2889 MethodInfoMap.erase(OverriddenMDIterator);
2890
2891 assert(!MethodInfoMap.count(MD) &&
2892 "Should not have method info for this method yet!");
2893 MethodInfoMap.insert(std::make_pair(MD, MI));
2894 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002895 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002896
Reid Kleckner31a9f742013-12-27 20:29:16 +00002897 // In case we need a return adjustment, we'll add a new slot for
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002898 // the overrider. Mark the overriden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00002899 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002900
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002901 // Force a special name mangling for a return-adjusting thunk
2902 // unless the method is the final overrider without this adjustment.
2903 ReturnAdjustingThunk =
2904 !(MD == OverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002905 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002906 MD->size_overridden_methods()) {
2907 // Skip methods that don't belong to the vftable of the current class,
2908 // e.g. each method that wasn't seen in any of the visited sub-bases
2909 // but overrides multiple methods of other sub-bases.
2910 continue;
2911 }
2912
2913 // If we got here, MD is a method not seen in any of the sub-bases or
2914 // it requires return adjustment. Insert the method info for this method.
2915 unsigned VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002916 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002917 MethodInfo MI(VBIndex, Components.size());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002918
2919 assert(!MethodInfoMap.count(MD) &&
2920 "Should not have method info for this method yet!");
2921 MethodInfoMap.insert(std::make_pair(MD, MI));
2922
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002923 // Check if this overrider needs a return adjustment.
2924 // We don't want to do this for pure virtual member functions.
2925 BaseOffset ReturnAdjustmentOffset;
2926 ReturnAdjustment ReturnAdjustment;
2927 if (!OverriderMD->isPure()) {
2928 ReturnAdjustmentOffset =
2929 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2930 }
2931 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002932 ReturnAdjustingThunk = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002933 ReturnAdjustment.NonVirtual =
2934 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2935 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002936 const ASTRecordLayout &DerivedLayout =
2937 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
2938 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
2939 DerivedLayout.getVBPtrOffset().getQuantity();
2940 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002941 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2942 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002943 }
2944 }
2945
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002946 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002947 ReturnAdjustingThunk ? MD : 0));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002948 }
2949}
2950
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002951static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
2952 for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002953 E = Path.rend(); I != E; ++I) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002954 Out << "'";
2955 (*I)->printQualifiedName(Out);
2956 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002957 }
2958}
2959
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002960static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
2961 bool ContinueFirstLine) {
2962 const ReturnAdjustment &R = TI.Return;
2963 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002964 const char *LinePrefix = "\n ";
2965 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002966 if (!ContinueFirstLine)
2967 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002968 Out << "[return adjustment (to type '"
2969 << TI.Method->getReturnType().getCanonicalType().getAsString()
2970 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002971 if (R.Virtual.Microsoft.VBPtrOffset)
2972 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
2973 if (R.Virtual.Microsoft.VBIndex)
2974 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
2975 Out << R.NonVirtual << " non-virtual]";
2976 Multiline = true;
2977 }
2978
2979 const ThisAdjustment &T = TI.This;
2980 if (!T.isEmpty()) {
2981 if (Multiline || !ContinueFirstLine)
2982 Out << LinePrefix;
2983 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002984 if (!TI.This.Virtual.isEmpty()) {
2985 assert(T.Virtual.Microsoft.VtordispOffset < 0);
2986 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
2987 if (T.Virtual.Microsoft.VBPtrOffset) {
2988 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002989 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002990 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
2991 Out << LinePrefix << " vboffset at "
2992 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
2993 }
2994 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002995 Out << T.NonVirtual << " non-virtual]";
2996 }
2997}
2998
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002999void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3000 Out << "VFTable for ";
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003001 PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003002 Out << "'";
3003 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003004 Out << "' (" << Components.size()
3005 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003006
3007 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3008 Out << llvm::format("%4d | ", I);
3009
3010 const VTableComponent &Component = Components[I];
3011
3012 // Dump the component.
3013 switch (Component.getKind()) {
3014 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003015 Component.getRTTIDecl()->printQualifiedName(Out);
3016 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003017 break;
3018
3019 case VTableComponent::CK_FunctionPointer: {
3020 const CXXMethodDecl *MD = Component.getFunctionDecl();
3021
Reid Kleckner604c8b42013-12-27 19:43:59 +00003022 // FIXME: Figure out how to print the real thunk type, since they can
3023 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003024 std::string Str = PredefinedExpr::ComputeName(
3025 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3026 Out << Str;
3027 if (MD->isPure())
3028 Out << " [pure]";
3029
3030 if (MD->isDeleted()) {
3031 ErrorUnsupported("deleted methods", MD->getLocation());
3032 Out << " [deleted]";
3033 }
3034
3035 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003036 if (!Thunk.isEmpty())
3037 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003038
3039 break;
3040 }
3041
3042 case VTableComponent::CK_DeletingDtorPointer: {
3043 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3044
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003045 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003046 Out << "() [scalar deleting]";
3047
3048 if (DD->isPure())
3049 Out << " [pure]";
3050
3051 ThunkInfo Thunk = VTableThunks.lookup(I);
3052 if (!Thunk.isEmpty()) {
3053 assert(Thunk.Return.isEmpty() &&
3054 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003055 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003056 }
3057
3058 break;
3059 }
3060
3061 default:
3062 DiagnosticsEngine &Diags = Context.getDiagnostics();
3063 unsigned DiagID = Diags.getCustomDiagID(
3064 DiagnosticsEngine::Error,
3065 "Unexpected vftable component type %0 for component number %1");
3066 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3067 << I << Component.getKind();
3068 }
3069
3070 Out << '\n';
3071 }
3072
3073 Out << '\n';
3074
3075 if (!Thunks.empty()) {
3076 // We store the method names in a map to get a stable order.
3077 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3078
3079 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3080 I != E; ++I) {
3081 const CXXMethodDecl *MD = I->first;
3082 std::string MethodName = PredefinedExpr::ComputeName(
3083 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3084
3085 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3086 }
3087
3088 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3089 I = MethodNamesAndDecls.begin(),
3090 E = MethodNamesAndDecls.end();
3091 I != E; ++I) {
3092 const std::string &MethodName = I->first;
3093 const CXXMethodDecl *MD = I->second;
3094
3095 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003096 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003097 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3098 // Keep different thunks with the same adjustments in the order they
3099 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003100 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003101 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003102
3103 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3104 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3105
3106 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3107 const ThunkInfo &Thunk = ThunksVector[I];
3108
3109 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003110 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003111 Out << '\n';
3112 }
3113
3114 Out << '\n';
3115 }
3116 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003117
3118 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003119}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003120
Reid Kleckner5f080942014-01-03 23:42:00 +00003121static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3122 const llvm::ArrayRef<const CXXRecordDecl *> &B) {
3123 for (llvm::ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(),
3124 E = B.end();
3125 I != E; ++I) {
3126 if (A.count(*I))
3127 return true;
3128 }
3129 return false;
3130}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003131
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003132static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003133
Reid Kleckner5f080942014-01-03 23:42:00 +00003134/// Produces MSVC-compatible vbtable data. The symbols produced by this
3135/// algorithm match those produced by MSVC 2012 and newer, which is different
3136/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003137///
3138/// MSVC 2012 appears to minimize the vbtable names using the following
3139/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3140/// left to right, to find all of the subobjects which contain a vbptr field.
3141/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3142/// record with a vbptr creates an initially empty path.
3143///
3144/// To combine paths from child nodes, the paths are compared to check for
3145/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3146/// components in the same order. Each group of ambiguous paths is extended by
3147/// appending the class of the base from which it came. If the current class
3148/// node produced an ambiguous path, its path is extended with the current class.
3149/// After extending paths, MSVC again checks for ambiguity, and extends any
3150/// ambiguous path which wasn't already extended. Because each node yields an
3151/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3152/// to produce an unambiguous set of paths.
3153///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003154/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003155void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3156 const CXXRecordDecl *RD,
3157 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003158 assert(Paths.empty());
3159 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003160
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003161 // Base case: this subobject has its own vptr.
3162 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3163 Paths.push_back(new VPtrInfo(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003164
Reid Kleckner5f080942014-01-03 23:42:00 +00003165 // Recursive case: get all the vbtables from our bases and remove anything
3166 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003167 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003168 for (const auto &B : RD->bases()) {
3169 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3170 if (B.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003171 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003172
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003173 if (!Base->isDynamicClass())
3174 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003175
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003176 const VPtrInfoVector &BasePaths =
3177 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3178
Reid Klecknerfd385402014-04-17 22:47:52 +00003179 for (VPtrInfo *BaseInfo : BasePaths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003180 // Don't include the path if it goes through a virtual base that we've
3181 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003182 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003183 continue;
3184
3185 // Copy the path and adjust it as necessary.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003186 VPtrInfo *P = new VPtrInfo(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003187
3188 // We mangle Base into the path if the path would've been ambiguous and it
3189 // wasn't already extended with Base.
3190 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3191 P->NextBaseToMangle = Base;
3192
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003193 // Keep track of the full path.
3194 // FIXME: Why do we need this?
3195 P->PathToBaseWithVPtr.insert(P->PathToBaseWithVPtr.begin(), Base);
3196
Reid Klecknerfd385402014-04-17 22:47:52 +00003197 // Keep track of which vtable the derived class is going to extend with
3198 // new methods or bases. We append to either the vftable of our primary
3199 // base, or the first non-virtual base that has a vbtable.
3200 if (P->ReusingBase == Base &&
3201 Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003202 : Layout.getPrimaryBase()))
Reid Kleckner5f080942014-01-03 23:42:00 +00003203 P->ReusingBase = RD;
Reid Klecknerfd385402014-04-17 22:47:52 +00003204
3205 // Keep track of the full adjustment from the MDC to this vtable. The
3206 // adjustment is captured by an optional vbase and a non-virtual offset.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003207 if (B.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003208 P->ContainingVBases.push_back(Base);
3209 else if (P->ContainingVBases.empty())
3210 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3211
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003212 // Update the full offset in the MDC.
3213 P->FullOffsetInMDC = P->NonVirtualOffset;
3214 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3215 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3216
Reid Kleckner5f080942014-01-03 23:42:00 +00003217 Paths.push_back(P);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003218 }
3219
Timur Iskhodzhanov9ae7d3b2014-03-31 11:01:51 +00003220 if (B.isVirtual())
3221 VBasesSeen.insert(Base);
3222
Reid Kleckner5f080942014-01-03 23:42:00 +00003223 // After visiting any direct base, we've transitively visited all of its
3224 // morally virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003225 for (const auto &VB : Base->vbases())
3226 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003227 }
3228
Reid Kleckner5f080942014-01-03 23:42:00 +00003229 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3230 // paths in ambiguous buckets.
3231 bool Changed = true;
3232 while (Changed)
3233 Changed = rebucketPaths(Paths);
3234}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003235
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003236static bool extendPath(VPtrInfo *P) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003237 if (P->NextBaseToMangle) {
3238 P->MangledPath.push_back(P->NextBaseToMangle);
3239 P->NextBaseToMangle = 0; // Prevent the path from being extended twice.
3240 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003241 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003242 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003243}
3244
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003245static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003246 // What we're essentially doing here is bucketing together ambiguous paths.
3247 // Any bucket with more than one path in it gets extended by NextBase, which
3248 // is usually the direct base of the inherited the vbptr. This code uses a
3249 // sorted vector to implement a multiset to form the buckets. Note that the
3250 // ordering is based on pointers, but it doesn't change our output order. The
3251 // current algorithm is designed to match MSVC 2012's names.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003252 VPtrInfoVector PathsSorted(Paths);
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003253 std::sort(PathsSorted.begin(), PathsSorted.end(),
3254 [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3255 return LHS->MangledPath < RHS->MangledPath;
3256 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003257 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003258 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3259 // Scan forward to find the end of the bucket.
3260 size_t BucketStart = I;
3261 do {
3262 ++I;
Reid Kleckner5f080942014-01-03 23:42:00 +00003263 } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3264 PathsSorted[I]->MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003265
3266 // If this bucket has multiple paths, extend them all.
3267 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003268 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003269 Changed |= extendPath(PathsSorted[II]);
3270 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003271 }
3272 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003273 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003274}
3275
3276MicrosoftVTableContext::~MicrosoftVTableContext() {
Reid Kleckner33311282014-02-28 23:26:22 +00003277 llvm::DeleteContainerSeconds(VFPtrLocations);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003278 llvm::DeleteContainerSeconds(VFTableLayouts);
3279 llvm::DeleteContainerSeconds(VBaseInfo);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003280}
3281
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003282void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003283 const CXXRecordDecl *RD) {
3284 assert(RD->isDynamicClass());
3285
3286 // Check if we've computed this information before.
3287 if (VFPtrLocations.count(RD))
3288 return;
3289
3290 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3291
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003292 VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3293 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3294 VFPtrLocations[RD] = VFPtrs;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003295
3296 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003297 for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003298 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003299 VFTableBuilder Builder(*this, RD, *I);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003300
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003301 VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003302 assert(VFTableLayouts.count(id) == 0);
3303 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3304 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003305 VFTableLayouts[id] = new VTableLayout(
3306 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3307 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003308 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003309
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003310 for (const auto &Loc : Builder.vtable_locations()) {
3311 GlobalDecl GD = Loc.first;
3312 MethodVFTableLocation NewLoc = Loc.second;
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003313 auto M = NewMethodLocations.find(GD);
3314 if (M == NewMethodLocations.end() || NewLoc < M->second)
3315 NewMethodLocations[GD] = NewLoc;
3316 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003317 }
3318
3319 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3320 NewMethodLocations.end());
3321 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003322 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003323}
3324
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003325void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003326 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3327 raw_ostream &Out) {
3328 // Compute the vtable indices for all the member functions.
3329 // Store them in a map keyed by the location so we'll get a sorted table.
3330 std::map<MethodVFTableLocation, std::string> IndicesMap;
3331 bool HasNonzeroOffset = false;
3332
3333 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3334 E = NewMethods.end(); I != E; ++I) {
3335 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3336 assert(MD->isVirtual());
3337
3338 std::string MethodName = PredefinedExpr::ComputeName(
3339 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3340
3341 if (isa<CXXDestructorDecl>(MD)) {
3342 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3343 } else {
3344 IndicesMap[I->second] = MethodName;
3345 }
3346
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003347 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003348 HasNonzeroOffset = true;
3349 }
3350
3351 // Print the vtable indices for all the member functions.
3352 if (!IndicesMap.empty()) {
3353 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003354 Out << "'";
3355 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003356 Out << "' (" << IndicesMap.size()
3357 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003358
3359 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3360 uint64_t LastVBIndex = 0;
3361 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3362 I = IndicesMap.begin(),
3363 E = IndicesMap.end();
3364 I != E; ++I) {
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003365 CharUnits VFPtrOffset = I->first.VFPtrOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003366 uint64_t VBIndex = I->first.VBTableIndex;
3367 if (HasNonzeroOffset &&
3368 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3369 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3370 Out << " -- accessible via ";
3371 if (VBIndex)
3372 Out << "vbtable index " << VBIndex << ", ";
3373 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3374 LastVFPtrOffset = VFPtrOffset;
3375 LastVBIndex = VBIndex;
3376 }
3377
3378 uint64_t VTableIndex = I->first.Index;
3379 const std::string &MethodName = I->second;
3380 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3381 }
3382 Out << '\n';
3383 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003384
3385 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003386}
3387
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003388const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003389 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003390 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003391
Reid Kleckner5f080942014-01-03 23:42:00 +00003392 {
3393 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3394 // as it may be modified and rehashed under us.
3395 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3396 if (Entry)
3397 return Entry;
3398 Entry = VBI = new VirtualBaseInfo();
3399 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003400
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003401 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003402
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003403 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003404 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003405 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003406 // If the Derived class shares the vbptr with a non-virtual base, the shared
3407 // virtual bases come first so that the layout is the same.
3408 const VirtualBaseInfo *BaseInfo =
3409 computeVBTableRelatedInformation(VBPtrBase);
Reid Kleckner5f080942014-01-03 23:42:00 +00003410 VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3411 BaseInfo->VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003412 }
3413
3414 // New vbases are added to the end of the vbtable.
3415 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003416 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003417 for (const auto &VB : RD->vbases()) {
3418 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003419 if (!VBI->VBTableIndices.count(CurVBase))
3420 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003421 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003422
Reid Kleckner5f080942014-01-03 23:42:00 +00003423 return VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003424}
3425
3426unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3427 const CXXRecordDecl *VBase) {
3428 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3429 assert(VBInfo->VBTableIndices.count(VBase));
3430 return VBInfo->VBTableIndices.find(VBase)->second;
3431}
3432
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003433const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003434MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003435 return computeVBTableRelatedInformation(RD)->VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003436}
3437
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003438const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003439MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003440 computeVTableRelatedInformation(RD);
3441
3442 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003443 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003444}
3445
3446const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003447MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3448 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003449 computeVTableRelatedInformation(RD);
3450
3451 VFTableIdTy id(RD, VFPtrOffset);
3452 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3453 return *VFTableLayouts[id];
3454}
3455
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003456const MicrosoftVTableContext::MethodVFTableLocation &
3457MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003458 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3459 "Only use this method for virtual methods or dtors");
3460 if (isa<CXXDestructorDecl>(GD.getDecl()))
3461 assert(GD.getDtorType() == Dtor_Deleting);
3462
3463 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3464 if (I != MethodVFTableLocations.end())
3465 return I->second;
3466
3467 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3468
3469 computeVTableRelatedInformation(RD);
3470
3471 I = MethodVFTableLocations.find(GD);
3472 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3473 return I->second;
3474}