blob: c28aeefd99db4895c0555c486bde0fc6f4f0b5bf [file] [log] [blame]
Peter Collingbourne24018462011-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 Kramerd4f51982012-07-04 18:45:14 +000015#include "clang/AST/ASTContext.h"
Peter Collingbourne24018462011-09-26 01:57:12 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/Support/Format.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000020#include "llvm/Support/raw_ostream.h"
Peter Collingbourne24018462011-09-26 01:57:12 +000021#include <algorithm>
22#include <cstdio>
23
24using namespace clang;
25
26#define DUMP_OVERRIDERS 0
27
28namespace {
29
30/// BaseOffset - Represents an offset from a derived class to a direct or
31/// indirect base class.
32struct BaseOffset {
33 /// DerivedClass - The derived class.
34 const CXXRecordDecl *DerivedClass;
35
36 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +000037 /// involves virtual base classes, this holds the declaration of the last
38 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbourne24018462011-09-26 01:57:12 +000039 const CXXRecordDecl *VirtualBase;
40
41 /// NonVirtualOffset - The offset from the derived class to the base class.
42 /// (Or the offset from the virtual base class to the base class, if the
43 /// path from the derived class to the base class involves a virtual base
44 /// class.
45 CharUnits NonVirtualOffset;
46
47 BaseOffset() : DerivedClass(0), VirtualBase(0),
48 NonVirtualOffset(CharUnits::Zero()) { }
49 BaseOffset(const CXXRecordDecl *DerivedClass,
50 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
51 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
52 NonVirtualOffset(NonVirtualOffset) { }
53
54 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
55};
56
57/// FinalOverriders - Contains the final overrider member functions for all
58/// member functions in the base subobjects of a class.
59class FinalOverriders {
60public:
61 /// OverriderInfo - Information about a final overrider.
62 struct OverriderInfo {
63 /// Method - The method decl of the overrider.
64 const CXXMethodDecl *Method;
65
Timur Iskhodzhanov635de282013-07-30 09:46:19 +000066 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbourne24018462011-09-26 01:57:12 +000067 CharUnits Offset;
68
69 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
70 };
71
72private:
73 /// MostDerivedClass - The most derived class for which the final overriders
74 /// are stored.
75 const CXXRecordDecl *MostDerivedClass;
76
77 /// MostDerivedClassOffset - If we're building final overriders for a
78 /// construction vtable, this holds the offset from the layout class to the
79 /// most derived class.
80 const CharUnits MostDerivedClassOffset;
81
82 /// LayoutClass - The class we're using for layout information. Will be
83 /// different than the most derived class if the final overriders are for a
84 /// construction vtable.
85 const CXXRecordDecl *LayoutClass;
86
87 ASTContext &Context;
88
89 /// MostDerivedClassLayout - the AST record layout of the most derived class.
90 const ASTRecordLayout &MostDerivedClassLayout;
91
92 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
93 /// in a base subobject.
94 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
95
96 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
97 OverriderInfo> OverridersMapTy;
98
99 /// OverridersMap - The final overriders for all virtual member functions of
100 /// all the base subobjects of the most derived class.
101 OverridersMapTy OverridersMap;
102
103 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
104 /// as a record decl and a subobject number) and its offsets in the most
105 /// derived class as well as the layout class.
106 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
107 CharUnits> SubobjectOffsetMapTy;
108
109 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
110
111 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
112 /// given base.
113 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
114 CharUnits OffsetInLayoutClass,
115 SubobjectOffsetMapTy &SubobjectOffsets,
116 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
117 SubobjectCountMapTy &SubobjectCounts);
118
119 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
120
121 /// dump - dump the final overriders for a base subobject, and all its direct
122 /// and indirect base subobjects.
123 void dump(raw_ostream &Out, BaseSubobject Base,
124 VisitedVirtualBasesSetTy& VisitedVirtualBases);
125
126public:
127 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
128 CharUnits MostDerivedClassOffset,
129 const CXXRecordDecl *LayoutClass);
130
131 /// getOverrider - Get the final overrider for the given method declaration in
132 /// the subobject with the given base offset.
133 OverriderInfo getOverrider(const CXXMethodDecl *MD,
134 CharUnits BaseOffset) const {
135 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
136 "Did not find overrider!");
137
138 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
139 }
140
141 /// dump - dump the final overriders.
142 void dump() {
143 VisitedVirtualBasesSetTy VisitedVirtualBases;
144 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
145 VisitedVirtualBases);
146 }
147
148};
149
Peter Collingbourne24018462011-09-26 01:57:12 +0000150FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
151 CharUnits MostDerivedClassOffset,
152 const CXXRecordDecl *LayoutClass)
153 : MostDerivedClass(MostDerivedClass),
154 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
155 Context(MostDerivedClass->getASTContext()),
156 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
157
158 // Compute base offsets.
159 SubobjectOffsetMapTy SubobjectOffsets;
160 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
161 SubobjectCountMapTy SubobjectCounts;
162 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
163 /*IsVirtual=*/false,
164 MostDerivedClassOffset,
165 SubobjectOffsets, SubobjectLayoutClassOffsets,
166 SubobjectCounts);
167
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000168 // Get the final overriders.
Peter Collingbourne24018462011-09-26 01:57:12 +0000169 CXXFinalOverriderMap FinalOverriders;
170 MostDerivedClass->getFinalOverriders(FinalOverriders);
171
172 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
173 E = FinalOverriders.end(); I != E; ++I) {
174 const CXXMethodDecl *MD = I->first;
175 const OverridingMethods& Methods = I->second;
176
177 for (OverridingMethods::const_iterator I = Methods.begin(),
178 E = Methods.end(); I != E; ++I) {
179 unsigned SubobjectNumber = I->first;
180 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
181 SubobjectNumber)) &&
182 "Did not find subobject offset!");
183
184 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
185 SubobjectNumber)];
186
187 assert(I->second.size() == 1 && "Final overrider is not unique!");
188 const UniqueVirtualMethod &Method = I->second.front();
189
190 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
191 assert(SubobjectLayoutClassOffsets.count(
192 std::make_pair(OverriderRD, Method.Subobject))
193 && "Did not find subobject offset!");
194 CharUnits OverriderOffset =
195 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
196 Method.Subobject)];
197
198 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
199 assert(!Overrider.Method && "Overrider should not exist yet!");
200
201 Overrider.Offset = OverriderOffset;
202 Overrider.Method = Method.Method;
203 }
204 }
205
206#if DUMP_OVERRIDERS
207 // And dump them (for now).
208 dump();
209#endif
210}
211
212static BaseOffset ComputeBaseOffset(ASTContext &Context,
213 const CXXRecordDecl *DerivedRD,
214 const CXXBasePath &Path) {
215 CharUnits NonVirtualOffset = CharUnits::Zero();
216
217 unsigned NonVirtualStart = 0;
218 const CXXRecordDecl *VirtualBase = 0;
219
220 // First, look for the virtual base class.
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000221 for (int I = Path.size(), E = 0; I != E; --I) {
222 const CXXBasePathElement &Element = Path[I - 1];
223
Peter Collingbourne24018462011-09-26 01:57:12 +0000224 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000225 NonVirtualStart = I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000226 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000227 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000228 break;
Peter Collingbourne24018462011-09-26 01:57:12 +0000229 }
230 }
231
232 // Now compute the non-virtual offset.
233 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
234 const CXXBasePathElement &Element = Path[I];
235
236 // Check the base class offset.
237 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
238
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000239 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000240
241 NonVirtualOffset += Layout.getBaseClassOffset(Base);
242 }
243
244 // FIXME: This should probably use CharUnits or something. Maybe we should
245 // even change the base offsets in ASTRecordLayout to be specified in
246 // CharUnits.
247 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
248
249}
250
251static BaseOffset ComputeBaseOffset(ASTContext &Context,
252 const CXXRecordDecl *BaseRD,
253 const CXXRecordDecl *DerivedRD) {
254 CXXBasePaths Paths(/*FindAmbiguities=*/false,
255 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer922cec22013-02-03 18:55:34 +0000256
257 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +0000258 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +0000259
260 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
261}
262
263static BaseOffset
264ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
265 const CXXMethodDecl *DerivedMD,
266 const CXXMethodDecl *BaseMD) {
267 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
268 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
269
270 // Canonicalize the return types.
271 CanQualType CanDerivedReturnType =
272 Context.getCanonicalType(DerivedFT->getResultType());
273 CanQualType CanBaseReturnType =
274 Context.getCanonicalType(BaseFT->getResultType());
275
276 assert(CanDerivedReturnType->getTypeClass() ==
277 CanBaseReturnType->getTypeClass() &&
278 "Types must have same type class!");
279
280 if (CanDerivedReturnType == CanBaseReturnType) {
281 // No adjustment needed.
282 return BaseOffset();
283 }
284
285 if (isa<ReferenceType>(CanDerivedReturnType)) {
286 CanDerivedReturnType =
287 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
288 CanBaseReturnType =
289 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
290 } else if (isa<PointerType>(CanDerivedReturnType)) {
291 CanDerivedReturnType =
292 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
293 CanBaseReturnType =
294 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
295 } else {
296 llvm_unreachable("Unexpected return type!");
297 }
298
299 // We need to compare unqualified types here; consider
300 // const T *Base::foo();
301 // T *Derived::foo();
302 if (CanDerivedReturnType.getUnqualifiedType() ==
303 CanBaseReturnType.getUnqualifiedType()) {
304 // No adjustment needed.
305 return BaseOffset();
306 }
307
308 const CXXRecordDecl *DerivedRD =
309 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
310
311 const CXXRecordDecl *BaseRD =
312 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
313
314 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
315}
316
317void
318FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
319 CharUnits OffsetInLayoutClass,
320 SubobjectOffsetMapTy &SubobjectOffsets,
321 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
322 SubobjectCountMapTy &SubobjectCounts) {
323 const CXXRecordDecl *RD = Base.getBase();
324
325 unsigned SubobjectNumber = 0;
326 if (!IsVirtual)
327 SubobjectNumber = ++SubobjectCounts[RD];
328
329 // Set up the subobject to offset mapping.
330 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
331 && "Subobject offset already exists!");
332 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
333 && "Subobject offset already exists!");
334
335 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
336 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
337 OffsetInLayoutClass;
338
339 // Traverse our bases.
340 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
341 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000342 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000343
344 CharUnits BaseOffset;
345 CharUnits BaseOffsetInLayoutClass;
346 if (I->isVirtual()) {
347 // Check if we've visited this virtual base before.
348 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
349 continue;
350
351 const ASTRecordLayout &LayoutClassLayout =
352 Context.getASTRecordLayout(LayoutClass);
353
354 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
355 BaseOffsetInLayoutClass =
356 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
357 } else {
358 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
359 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
360
361 BaseOffset = Base.getBaseOffset() + Offset;
362 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
363 }
364
365 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
366 I->isVirtual(), BaseOffsetInLayoutClass,
367 SubobjectOffsets, SubobjectLayoutClassOffsets,
368 SubobjectCounts);
369 }
370}
371
372void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
373 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
374 const CXXRecordDecl *RD = Base.getBase();
375 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
376
377 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
378 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000379 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000380
381 // Ignore bases that don't have any virtual member functions.
382 if (!BaseDecl->isPolymorphic())
383 continue;
384
385 CharUnits BaseOffset;
386 if (I->isVirtual()) {
387 if (!VisitedVirtualBases.insert(BaseDecl)) {
388 // We've visited this base before.
389 continue;
390 }
391
392 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
393 } else {
394 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
395 }
396
397 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
398 }
399
400 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
401 Out << Base.getBaseOffset().getQuantity() << ")\n";
402
403 // Now dump the overriders for this base subobject.
404 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
405 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000406 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000407
408 if (!MD->isVirtual())
409 continue;
410
411 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
412
413 Out << " " << MD->getQualifiedNameAsString() << " - (";
414 Out << Overrider.Method->getQualifiedNameAsString();
Timur Iskhodzhanovc65ee8f2013-06-05 06:40:07 +0000415 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbourne24018462011-09-26 01:57:12 +0000416
417 BaseOffset Offset;
418 if (!Overrider.Method->isPure())
419 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
420
421 if (!Offset.isEmpty()) {
422 Out << " [ret-adj: ";
423 if (Offset.VirtualBase)
424 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
425
426 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
427 }
428
429 Out << "\n";
430 }
431}
432
433/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
434struct VCallOffsetMap {
435
436 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
437
438 /// Offsets - Keeps track of methods and their offsets.
439 // FIXME: This should be a real map and not a vector.
440 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
441
442 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
443 /// can share the same vcall offset.
444 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
445 const CXXMethodDecl *RHS);
446
447public:
448 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
449 /// add was successful, or false if there was already a member function with
450 /// the same signature in the map.
451 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
452
453 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
454 /// vtable address point) for the given virtual member function.
455 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
456
457 // empty - Return whether the offset map is empty or not.
458 bool empty() const { return Offsets.empty(); }
459};
460
461static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
462 const CXXMethodDecl *RHS) {
John McCall260a3e42012-03-21 06:57:19 +0000463 const FunctionProtoType *LT =
464 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
465 const FunctionProtoType *RT =
466 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbourne24018462011-09-26 01:57:12 +0000467
468 // Fast-path matches in the canonical types.
469 if (LT == RT) return true;
470
471 // Force the signatures to match. We can't rely on the overrides
472 // list here because there isn't necessarily an inheritance
473 // relationship between the two methods.
John McCall260a3e42012-03-21 06:57:19 +0000474 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Peter Collingbourne24018462011-09-26 01:57:12 +0000475 LT->getNumArgs() != RT->getNumArgs())
476 return false;
477 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
478 if (LT->getArgType(I) != RT->getArgType(I))
479 return false;
480 return true;
481}
482
483bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
484 const CXXMethodDecl *RHS) {
485 assert(LHS->isVirtual() && "LHS must be virtual!");
486 assert(RHS->isVirtual() && "LHS must be virtual!");
487
488 // A destructor can share a vcall offset with another destructor.
489 if (isa<CXXDestructorDecl>(LHS))
490 return isa<CXXDestructorDecl>(RHS);
491
492 // FIXME: We need to check more things here.
493
494 // The methods must have the same name.
495 DeclarationName LHSName = LHS->getDeclName();
496 DeclarationName RHSName = RHS->getDeclName();
497 if (LHSName != RHSName)
498 return false;
499
500 // And the same signatures.
501 return HasSameVirtualSignature(LHS, RHS);
502}
503
504bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
505 CharUnits OffsetOffset) {
506 // Check if we can reuse an offset.
507 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
508 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
509 return false;
510 }
511
512 // Add the offset.
513 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
514 return true;
515}
516
517CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
518 // Look for an offset.
519 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
520 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
521 return Offsets[I].second;
522 }
523
524 llvm_unreachable("Should always find a vcall offset offset!");
525}
526
527/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
528class VCallAndVBaseOffsetBuilder {
529public:
530 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
531 VBaseOffsetOffsetsMapTy;
532
533private:
534 /// MostDerivedClass - The most derived class for which we're building vcall
535 /// and vbase offsets.
536 const CXXRecordDecl *MostDerivedClass;
537
538 /// LayoutClass - The class we're using for layout information. Will be
539 /// different than the most derived class if we're building a construction
540 /// vtable.
541 const CXXRecordDecl *LayoutClass;
542
543 /// Context - The ASTContext which we will use for layout information.
544 ASTContext &Context;
545
546 /// Components - vcall and vbase offset components
547 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
548 VTableComponentVectorTy Components;
549
550 /// VisitedVirtualBases - Visited virtual bases.
551 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
552
553 /// VCallOffsets - Keeps track of vcall offsets.
554 VCallOffsetMap VCallOffsets;
555
556
557 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
558 /// relative to the address point.
559 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
560
561 /// FinalOverriders - The final overriders of the most derived class.
562 /// (Can be null when we're not building a vtable of the most derived class).
563 const FinalOverriders *Overriders;
564
565 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
566 /// given base subobject.
567 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
568 CharUnits RealBaseOffset);
569
570 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
571 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
572
573 /// AddVBaseOffsets - Add vbase offsets for the given class.
574 void AddVBaseOffsets(const CXXRecordDecl *Base,
575 CharUnits OffsetInLayoutClass);
576
577 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
578 /// chars, relative to the vtable address point.
579 CharUnits getCurrentOffsetOffset() const;
580
581public:
582 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
583 const CXXRecordDecl *LayoutClass,
584 const FinalOverriders *Overriders,
585 BaseSubobject Base, bool BaseIsVirtual,
586 CharUnits OffsetInLayoutClass)
587 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
588 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
589
590 // Add vcall and vbase offsets.
591 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
592 }
593
594 /// Methods for iterating over the components.
595 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
596 const_iterator components_begin() const { return Components.rbegin(); }
597 const_iterator components_end() const { return Components.rend(); }
598
599 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
600 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
601 return VBaseOffsetOffsets;
602 }
603};
604
605void
606VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
607 bool BaseIsVirtual,
608 CharUnits RealBaseOffset) {
609 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
610
611 // Itanium C++ ABI 2.5.2:
612 // ..in classes sharing a virtual table with a primary base class, the vcall
613 // and vbase offsets added by the derived class all come before the vcall
614 // and vbase offsets required by the base class, so that the latter may be
615 // laid out as required by the base class without regard to additions from
616 // the derived class(es).
617
618 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
619 // emit them for the primary base first).
620 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
621 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
622
623 CharUnits PrimaryBaseOffset;
624
625 // Get the base offset of the primary base.
626 if (PrimaryBaseIsVirtual) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000627 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000628 "Primary vbase should have a zero offset!");
629
630 const ASTRecordLayout &MostDerivedClassLayout =
631 Context.getASTRecordLayout(MostDerivedClass);
632
633 PrimaryBaseOffset =
634 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
635 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000636 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000637 "Primary base should have a zero offset!");
638
639 PrimaryBaseOffset = Base.getBaseOffset();
640 }
641
642 AddVCallAndVBaseOffsets(
643 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
644 PrimaryBaseIsVirtual, RealBaseOffset);
645 }
646
647 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
648
649 // We only want to add vcall offsets for virtual bases.
650 if (BaseIsVirtual)
651 AddVCallOffsets(Base, RealBaseOffset);
652}
653
654CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
655 // OffsetIndex is the index of this vcall or vbase offset, relative to the
656 // vtable address point. (We subtract 3 to account for the information just
657 // above the address point, the RTTI info, the offset to top, and the
658 // vcall offset itself).
659 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
660
661 CharUnits PointerWidth =
662 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
663 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
664 return OffsetOffset;
665}
666
667void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
668 CharUnits VBaseOffset) {
669 const CXXRecordDecl *RD = Base.getBase();
670 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
671
672 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
673
674 // Handle the primary base first.
675 // We only want to add vcall offsets if the base is non-virtual; a virtual
676 // primary base will have its vcall and vbase offsets emitted already.
677 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
678 // Get the base offset of the primary base.
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000679 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000680 "Primary base should have a zero offset!");
681
682 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
683 VBaseOffset);
684 }
685
686 // Add the vcall offsets.
687 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
688 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000689 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000690
691 if (!MD->isVirtual())
692 continue;
693
694 CharUnits OffsetOffset = getCurrentOffsetOffset();
695
696 // Don't add a vcall offset if we already have one for this member function
697 // signature.
698 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
699 continue;
700
701 CharUnits Offset = CharUnits::Zero();
702
703 if (Overriders) {
704 // Get the final overrider.
705 FinalOverriders::OverriderInfo Overrider =
706 Overriders->getOverrider(MD, Base.getBaseOffset());
707
708 /// The vcall offset is the offset from the virtual base to the object
709 /// where the function was overridden.
710 Offset = Overrider.Offset - VBaseOffset;
711 }
712
713 Components.push_back(
714 VTableComponent::MakeVCallOffset(Offset));
715 }
716
717 // And iterate over all non-virtual bases (ignoring the primary base).
718 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
719 E = RD->bases_end(); I != E; ++I) {
720
721 if (I->isVirtual())
722 continue;
723
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000724 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000725 if (BaseDecl == PrimaryBase)
726 continue;
727
728 // Get the base offset of this base.
729 CharUnits BaseOffset = Base.getBaseOffset() +
730 Layout.getBaseClassOffset(BaseDecl);
731
732 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
733 VBaseOffset);
734 }
735}
736
737void
738VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
739 CharUnits OffsetInLayoutClass) {
740 const ASTRecordLayout &LayoutClassLayout =
741 Context.getASTRecordLayout(LayoutClass);
742
743 // Add vbase offsets.
744 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
745 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000746 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000747
748 // Check if this is a virtual base that we haven't visited before.
749 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
750 CharUnits Offset =
751 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
752
753 // Add the vbase offset offset.
754 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
755 "vbase offset offset already exists!");
756
757 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
758 VBaseOffsetOffsets.insert(
759 std::make_pair(BaseDecl, VBaseOffsetOffset));
760
761 Components.push_back(
762 VTableComponent::MakeVBaseOffset(Offset));
763 }
764
765 // Check the base class looking for more vbase offsets.
766 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
767 }
768}
769
770/// VTableBuilder - Class for building vtable layout information.
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000771// FIXME: rename to ItaniumVTableBuilder.
Peter Collingbourne24018462011-09-26 01:57:12 +0000772class VTableBuilder {
773public:
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 Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000785 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
786
Peter Collingbourne24018462011-09-26 01:57:12 +0000787private:
788 /// VTables - Global vtable information.
789 VTableContext &VTables;
790
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 Iskhodzhanov2aae5ba2013-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 Collingbourne24018462011-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:
986 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
987 CharUnits MostDerivedClassOffset,
988 bool MostDerivedClassIsVirtual, const
989 CXXRecordDecl *LayoutClass)
990 : VTables(VTables), MostDerivedClass(MostDerivedClass),
991 MostDerivedClassOffset(MostDerivedClassOffset),
992 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
993 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
994 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
995
996 LayoutVTable();
997
David Blaikie4e4d0842012-03-11 07:00:24 +0000998 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +0000999 dumpLayout(llvm::errs());
1000 }
1001
1002 uint64_t getNumThunks() const {
1003 return Thunks.size();
1004 }
1005
1006 ThunksMapTy::const_iterator thunks_begin() const {
1007 return Thunks.begin();
1008 }
1009
1010 ThunksMapTy::const_iterator thunks_end() const {
1011 return Thunks.end();
1012 }
1013
1014 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1015 return VBaseOffsetOffsets;
1016 }
1017
1018 const AddressPointsMapTy &getAddressPoints() const {
1019 return AddressPoints;
1020 }
1021
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001022 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1023 return MethodVTableIndices.begin();
1024 }
1025
1026 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1027 return MethodVTableIndices.end();
1028 }
1029
Peter Collingbourne24018462011-09-26 01:57:12 +00001030 /// getNumVTableComponents - Return the number of components in the vtable
1031 /// currently built.
1032 uint64_t getNumVTableComponents() const {
1033 return Components.size();
1034 }
1035
1036 const VTableComponent *vtable_component_begin() const {
1037 return Components.begin();
1038 }
1039
1040 const VTableComponent *vtable_component_end() const {
1041 return Components.end();
1042 }
1043
1044 AddressPointsMapTy::const_iterator address_points_begin() const {
1045 return AddressPoints.begin();
1046 }
1047
1048 AddressPointsMapTy::const_iterator address_points_end() const {
1049 return AddressPoints.end();
1050 }
1051
1052 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1053 return VTableThunks.begin();
1054 }
1055
1056 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1057 return VTableThunks.end();
1058 }
1059
1060 /// dumpLayout - Dump the vtable layout.
1061 void dumpLayout(raw_ostream&);
1062};
1063
1064void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1065 assert(!isBuildingConstructorVTable() &&
1066 "Can't add thunks for construction vtable");
1067
Craig Topper6b9240e2013-07-05 19:34:19 +00001068 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1069
Peter Collingbourne24018462011-09-26 01:57:12 +00001070 // Check if we have this thunk already.
1071 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1072 ThunksVector.end())
1073 return;
1074
1075 ThunksVector.push_back(Thunk);
1076}
1077
1078typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1079
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001080/// Visit all the methods overridden by the given method recursively,
1081/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1082/// indicating whether to continue the recursion for the given overridden
1083/// method (i.e. returning false stops the iteration).
1084template <class VisitorTy>
1085static void
1086visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001087 assert(MD->isVirtual() && "Method is not virtual!");
1088
1089 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1090 E = MD->end_overridden_methods(); I != E; ++I) {
1091 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001092 if (!Visitor.visit(OverriddenMD))
1093 continue;
1094 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbourne24018462011-09-26 01:57:12 +00001095 }
1096}
1097
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001098namespace {
1099 struct OverriddenMethodsCollector {
1100 OverriddenMethodsSetTy *Methods;
1101
1102 bool visit(const CXXMethodDecl *MD) {
1103 // Don't recurse on this method if we've already collected it.
1104 return Methods->insert(MD);
1105 }
1106 };
1107}
1108
1109/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1110/// the overridden methods that the function decl overrides.
1111static void
1112ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1113 OverriddenMethodsSetTy& OverriddenMethods) {
1114 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1115 visitAllOverriddenMethods(MD, Collector);
1116}
1117
Peter Collingbourne24018462011-09-26 01:57:12 +00001118void VTableBuilder::ComputeThisAdjustments() {
1119 // Now go through the method info map and see if any of the methods need
1120 // 'this' pointer adjustments.
1121 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1122 E = MethodInfoMap.end(); I != E; ++I) {
1123 const CXXMethodDecl *MD = I->first;
1124 const MethodInfo &MethodInfo = I->second;
1125
1126 // Ignore adjustments for unused function pointers.
1127 uint64_t VTableIndex = MethodInfo.VTableIndex;
1128 if (Components[VTableIndex].getKind() ==
1129 VTableComponent::CK_UnusedFunctionPointer)
1130 continue;
1131
1132 // Get the final overrider for this method.
1133 FinalOverriders::OverriderInfo Overrider =
1134 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1135
1136 // Check if we need an adjustment at all.
1137 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1138 // When a return thunk is needed by a derived class that overrides a
1139 // virtual base, gcc uses a virtual 'this' adjustment as well.
1140 // While the thunk itself might be needed by vtables in subclasses or
1141 // in construction vtables, there doesn't seem to be a reason for using
1142 // the thunk in this vtable. Still, we do so to match gcc.
1143 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1144 continue;
1145 }
1146
1147 ThisAdjustment ThisAdjustment =
1148 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1149
1150 if (ThisAdjustment.isEmpty())
1151 continue;
1152
1153 // Add it.
1154 VTableThunks[VTableIndex].This = ThisAdjustment;
1155
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001156 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001157 // Add an adjustment for the deleting destructor as well.
1158 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1159 }
1160 }
1161
1162 /// Clear the method info map.
1163 MethodInfoMap.clear();
1164
1165 if (isBuildingConstructorVTable()) {
1166 // We don't need to store thunk information for construction vtables.
1167 return;
1168 }
1169
1170 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1171 E = VTableThunks.end(); I != E; ++I) {
1172 const VTableComponent &Component = Components[I->first];
1173 const ThunkInfo &Thunk = I->second;
1174 const CXXMethodDecl *MD;
1175
1176 switch (Component.getKind()) {
1177 default:
1178 llvm_unreachable("Unexpected vtable component kind!");
1179 case VTableComponent::CK_FunctionPointer:
1180 MD = Component.getFunctionDecl();
1181 break;
1182 case VTableComponent::CK_CompleteDtorPointer:
1183 MD = Component.getDestructorDecl();
1184 break;
1185 case VTableComponent::CK_DeletingDtorPointer:
1186 // We've already added the thunk when we saw the complete dtor pointer.
1187 continue;
1188 }
1189
1190 if (MD->getParent() == MostDerivedClass)
1191 AddThunk(MD, Thunk);
1192 }
1193}
1194
1195ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1196 ReturnAdjustment Adjustment;
1197
1198 if (!Offset.isEmpty()) {
1199 if (Offset.VirtualBase) {
1200 // Get the virtual base offset offset.
1201 if (Offset.DerivedClass == MostDerivedClass) {
1202 // We can get the offset offset directly from our map.
1203 Adjustment.VBaseOffsetOffset =
1204 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1205 } else {
1206 Adjustment.VBaseOffsetOffset =
1207 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1208 Offset.VirtualBase).getQuantity();
1209 }
1210 }
1211
1212 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1213 }
1214
1215 return Adjustment;
1216}
1217
1218BaseOffset
1219VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1220 BaseSubobject Derived) const {
1221 const CXXRecordDecl *BaseRD = Base.getBase();
1222 const CXXRecordDecl *DerivedRD = Derived.getBase();
1223
1224 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1225 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1226
Benjamin Kramer922cec22013-02-03 18:55:34 +00001227 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +00001228 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +00001229
1230 // We have to go through all the paths, and see which one leads us to the
1231 // right base subobject.
1232 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1233 I != E; ++I) {
1234 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1235
1236 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1237
1238 if (Offset.VirtualBase) {
1239 // If we have a virtual base class, the non-virtual offset is relative
1240 // to the virtual base class offset.
1241 const ASTRecordLayout &LayoutClassLayout =
1242 Context.getASTRecordLayout(LayoutClass);
1243
1244 /// Get the virtual base offset, relative to the most derived class
1245 /// layout.
1246 OffsetToBaseSubobject +=
1247 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1248 } else {
1249 // Otherwise, the non-virtual offset is relative to the derived class
1250 // offset.
1251 OffsetToBaseSubobject += Derived.getBaseOffset();
1252 }
1253
1254 // Check if this path gives us the right base subobject.
1255 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1256 // Since we're going from the base class _to_ the derived class, we'll
1257 // invert the non-virtual offset here.
1258 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1259 return Offset;
1260 }
1261 }
1262
1263 return BaseOffset();
1264}
1265
1266ThisAdjustment
1267VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1268 CharUnits BaseOffsetInLayoutClass,
1269 FinalOverriders::OverriderInfo Overrider) {
1270 // Ignore adjustments for pure virtual member functions.
1271 if (Overrider.Method->isPure())
1272 return ThisAdjustment();
1273
1274 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1275 BaseOffsetInLayoutClass);
1276
1277 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1278 Overrider.Offset);
1279
1280 // Compute the adjustment offset.
1281 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1282 OverriderBaseSubobject);
1283 if (Offset.isEmpty())
1284 return ThisAdjustment();
1285
1286 ThisAdjustment Adjustment;
1287
1288 if (Offset.VirtualBase) {
1289 // Get the vcall offset map for this virtual base.
1290 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1291
1292 if (VCallOffsets.empty()) {
1293 // We don't have vcall offsets for this virtual base, go ahead and
1294 // build them.
1295 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1296 /*FinalOverriders=*/0,
1297 BaseSubobject(Offset.VirtualBase,
1298 CharUnits::Zero()),
1299 /*BaseIsVirtual=*/true,
1300 /*OffsetInLayoutClass=*/
1301 CharUnits::Zero());
1302
1303 VCallOffsets = Builder.getVCallOffsets();
1304 }
1305
1306 Adjustment.VCallOffsetOffset =
1307 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1308 }
1309
1310 // Set the non-virtual part of the adjustment.
1311 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1312
1313 return Adjustment;
1314}
1315
1316void
1317VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1318 ReturnAdjustment ReturnAdjustment) {
1319 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1320 assert(ReturnAdjustment.isEmpty() &&
1321 "Destructor can't have return adjustment!");
1322
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001323 // Add both the complete destructor and the deleting destructor.
1324 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1325 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbourne24018462011-09-26 01:57:12 +00001326 } else {
1327 // Add the return adjustment if necessary.
1328 if (!ReturnAdjustment.isEmpty())
1329 VTableThunks[Components.size()].Return = ReturnAdjustment;
1330
1331 // Add the function.
1332 Components.push_back(VTableComponent::MakeFunction(MD));
1333 }
1334}
1335
1336/// OverridesIndirectMethodInBase - Return whether the given member function
1337/// overrides any methods in the set of given bases.
1338/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1339/// For example, if we have:
1340///
1341/// struct A { virtual void f(); }
1342/// struct B : A { virtual void f(); }
1343/// struct C : B { virtual void f(); }
1344///
1345/// OverridesIndirectMethodInBase will return true if given C::f as the method
1346/// and { A } as the set of bases.
1347static bool
1348OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1349 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1350 if (Bases.count(MD->getParent()))
1351 return true;
1352
1353 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1354 E = MD->end_overridden_methods(); I != E; ++I) {
1355 const CXXMethodDecl *OverriddenMD = *I;
1356
1357 // Check "indirect overriders".
1358 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1359 return true;
1360 }
1361
1362 return false;
1363}
1364
1365bool
1366VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1367 CharUnits BaseOffsetInLayoutClass,
1368 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1369 CharUnits FirstBaseOffsetInLayoutClass) const {
1370 // 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;
1383
1384 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1385
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 Kramerd4f51982012-07-04 18:45:14 +00001399 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-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 Kramerd4f51982012-07-04 18:45:14 +00001413 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-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 Iskhodzhanov635de282013-07-30 09:46:19 +00001428typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1429
Peter Collingbourne24018462011-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 Iskhodzhanov635de282013-07-30 09:46:19 +00001432/// The Bases are expected to be sorted in a base-to-derived order.
1433static const CXXMethodDecl *
Peter Collingbourne24018462011-09-26 01:57:12 +00001434FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001435 BasesSetVectorTy &Bases) {
Peter Collingbourne24018462011-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 Iskhodzhanov635de282013-07-30 09:46:19 +00001442 // Now check the overridden methods.
Peter Collingbourne24018462011-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;
1454}
1455
1456void
1457VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1458 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1459 CharUnits FirstBaseOffsetInLayoutClass,
1460 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov2aae5ba2013-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 Collingbourne24018462011-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 Kramerd4f51982012-07-04 18:45:14 +00001477 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-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 Kramerd4f51982012-07-04 18:45:14 +00001492 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-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 Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001507 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1508
1509 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1510 NewVirtualFunctionsTy NewVirtualFunctions;
1511
Peter Collingbourne24018462011-09-26 01:57:12 +00001512 // Now go through all virtual member functions and add them.
1513 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1514 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001515 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001516
1517 if (!MD->isVirtual())
1518 continue;
1519
1520 // Get the final overrider.
1521 FinalOverriders::OverriderInfo Overrider =
1522 Overriders.getOverrider(MD, Base.getBaseOffset());
1523
1524 // Check if this virtual member function overrides a method in a primary
1525 // base. If this is the case, and the return type doesn't require adjustment
1526 // then we can just use the member function from the primary base.
1527 if (const CXXMethodDecl *OverriddenMD =
1528 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1529 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1530 OverriddenMD).isEmpty()) {
1531 // Replace the method info of the overridden method with our own
1532 // method.
1533 assert(MethodInfoMap.count(OverriddenMD) &&
1534 "Did not find the overridden method!");
1535 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1536
1537 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1538 OverriddenMethodInfo.VTableIndex);
1539
1540 assert(!MethodInfoMap.count(MD) &&
1541 "Should not have method info for this method yet!");
1542
1543 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1544 MethodInfoMap.erase(OverriddenMD);
1545
1546 // If the overridden method exists in a virtual base class or a direct
1547 // or indirect base class of a virtual base class, we need to emit a
1548 // thunk if we ever have a class hierarchy where the base class is not
1549 // a primary base in the complete object.
1550 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1551 // Compute the this adjustment.
1552 ThisAdjustment ThisAdjustment =
1553 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1554 Overrider);
1555
1556 if (ThisAdjustment.VCallOffsetOffset &&
1557 Overrider.Method->getParent() == MostDerivedClass) {
1558
1559 // There's no return adjustment from OverriddenMD and MD,
1560 // but that doesn't mean there isn't one between MD and
1561 // the final overrider.
1562 BaseOffset ReturnAdjustmentOffset =
1563 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1564 ReturnAdjustment ReturnAdjustment =
1565 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1566
1567 // This is a virtual thunk for the most derived class, add it.
1568 AddThunk(Overrider.Method,
1569 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1570 }
1571 }
1572
1573 continue;
1574 }
1575 }
1576
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001577 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1578 if (MD->isImplicit()) {
1579 // Itanium C++ ABI 2.5.2:
1580 // If a class has an implicitly-defined virtual destructor,
1581 // its entries come after the declared virtual function pointers.
1582
1583 assert(!ImplicitVirtualDtor &&
1584 "Did already see an implicit virtual dtor!");
1585 ImplicitVirtualDtor = DD;
1586 continue;
1587 }
1588 }
1589
1590 NewVirtualFunctions.push_back(MD);
1591 }
1592
1593 if (ImplicitVirtualDtor)
1594 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1595
1596 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1597 E = NewVirtualFunctions.end(); I != E; ++I) {
1598 const CXXMethodDecl *MD = *I;
1599
1600 // Get the final overrider.
1601 FinalOverriders::OverriderInfo Overrider =
1602 Overriders.getOverrider(MD, Base.getBaseOffset());
1603
Peter Collingbourne24018462011-09-26 01:57:12 +00001604 // Insert the method info for this method.
1605 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1606 Components.size());
1607
1608 assert(!MethodInfoMap.count(MD) &&
1609 "Should not have method info for this method yet!");
1610 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1611
1612 // Check if this overrider is going to be used.
1613 const CXXMethodDecl *OverriderMD = Overrider.Method;
1614 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1615 FirstBaseInPrimaryBaseChain,
1616 FirstBaseOffsetInLayoutClass)) {
1617 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1618 continue;
1619 }
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001620
Peter Collingbourne24018462011-09-26 01:57:12 +00001621 // Check if this overrider needs a return adjustment.
1622 // We don't want to do this for pure virtual member functions.
1623 BaseOffset ReturnAdjustmentOffset;
1624 if (!OverriderMD->isPure()) {
1625 ReturnAdjustmentOffset =
1626 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1627 }
1628
1629 ReturnAdjustment ReturnAdjustment =
1630 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1631
1632 AddMethod(Overrider.Method, ReturnAdjustment);
1633 }
1634}
1635
1636void VTableBuilder::LayoutVTable() {
1637 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1638 CharUnits::Zero()),
1639 /*BaseIsMorallyVirtual=*/false,
1640 MostDerivedClassIsVirtual,
1641 MostDerivedClassOffset);
1642
1643 VisitedVirtualBasesSetTy VBases;
1644
1645 // Determine the primary virtual bases.
1646 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1647 VBases);
1648 VBases.clear();
1649
1650 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1651
1652 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001653 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001654 if (IsAppleKext)
1655 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1656}
1657
1658void
1659VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1660 bool BaseIsMorallyVirtual,
1661 bool BaseIsVirtualInLayoutClass,
1662 CharUnits OffsetInLayoutClass) {
1663 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1664
1665 // Add vcall and vbase offsets for this vtable.
1666 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1667 Base, BaseIsVirtualInLayoutClass,
1668 OffsetInLayoutClass);
1669 Components.append(Builder.components_begin(), Builder.components_end());
1670
1671 // Check if we need to add these vcall offsets.
1672 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1673 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1674
1675 if (VCallOffsets.empty())
1676 VCallOffsets = Builder.getVCallOffsets();
1677 }
1678
1679 // If we're laying out the most derived class we want to keep track of the
1680 // virtual base class offset offsets.
1681 if (Base.getBase() == MostDerivedClass)
1682 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1683
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001684 // Add the offset to top.
1685 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1686 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001687
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001688 // Next, add the RTTI.
1689 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001690
Peter Collingbourne24018462011-09-26 01:57:12 +00001691 uint64_t AddressPoint = Components.size();
1692
1693 // Now go through all virtual member functions and add them.
1694 PrimaryBasesSetVectorTy PrimaryBases;
1695 AddMethods(Base, OffsetInLayoutClass,
1696 Base.getBase(), OffsetInLayoutClass,
1697 PrimaryBases);
1698
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001699 const CXXRecordDecl *RD = Base.getBase();
1700 if (RD == MostDerivedClass) {
1701 assert(MethodVTableIndices.empty());
1702 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1703 E = MethodInfoMap.end(); I != E; ++I) {
1704 const CXXMethodDecl *MD = I->first;
1705 const MethodInfo &MI = I->second;
1706 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001707 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1708 = MI.VTableIndex - AddressPoint;
1709 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1710 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001711 } else {
1712 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1713 }
1714 }
1715 }
1716
Peter Collingbourne24018462011-09-26 01:57:12 +00001717 // Compute 'this' pointer adjustments.
1718 ComputeThisAdjustments();
1719
1720 // Add all address points.
Peter Collingbourne24018462011-09-26 01:57:12 +00001721 while (true) {
1722 AddressPoints.insert(std::make_pair(
1723 BaseSubobject(RD, OffsetInLayoutClass),
1724 AddressPoint));
1725
1726 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1727 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1728
1729 if (!PrimaryBase)
1730 break;
1731
1732 if (Layout.isPrimaryBaseVirtual()) {
1733 // Check if this virtual primary base is a primary base in the layout
1734 // class. If it's not, we don't want to add it.
1735 const ASTRecordLayout &LayoutClassLayout =
1736 Context.getASTRecordLayout(LayoutClass);
1737
1738 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1739 OffsetInLayoutClass) {
1740 // We don't want to add this class (or any of its primary bases).
1741 break;
1742 }
1743 }
1744
1745 RD = PrimaryBase;
1746 }
1747
1748 // Layout secondary vtables.
1749 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1750}
1751
1752void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1753 bool BaseIsMorallyVirtual,
1754 CharUnits OffsetInLayoutClass) {
1755 // Itanium C++ ABI 2.5.2:
1756 // Following the primary virtual table of a derived class are secondary
1757 // virtual tables for each of its proper base classes, except any primary
1758 // base(s) with which it shares its primary virtual table.
1759
1760 const CXXRecordDecl *RD = Base.getBase();
1761 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1762 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1763
1764 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1765 E = RD->bases_end(); I != E; ++I) {
1766 // Ignore virtual bases, we'll emit them later.
1767 if (I->isVirtual())
1768 continue;
1769
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001770 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001771
1772 // Ignore bases that don't have a vtable.
1773 if (!BaseDecl->isDynamicClass())
1774 continue;
1775
1776 if (isBuildingConstructorVTable()) {
1777 // Itanium C++ ABI 2.6.4:
1778 // Some of the base class subobjects may not need construction virtual
1779 // tables, which will therefore not be present in the construction
1780 // virtual table group, even though the subobject virtual tables are
1781 // present in the main virtual table group for the complete object.
1782 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1783 continue;
1784 }
1785
1786 // Get the base offset of this base.
1787 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1788 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1789
1790 CharUnits BaseOffsetInLayoutClass =
1791 OffsetInLayoutClass + RelativeBaseOffset;
1792
1793 // Don't emit a secondary vtable for a primary base. We might however want
1794 // to emit secondary vtables for other bases of this base.
1795 if (BaseDecl == PrimaryBase) {
1796 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1797 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1798 continue;
1799 }
1800
1801 // Layout the primary vtable (and any secondary vtables) for this base.
1802 LayoutPrimaryAndSecondaryVTables(
1803 BaseSubobject(BaseDecl, BaseOffset),
1804 BaseIsMorallyVirtual,
1805 /*BaseIsVirtualInLayoutClass=*/false,
1806 BaseOffsetInLayoutClass);
1807 }
1808}
1809
1810void
1811VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1812 CharUnits OffsetInLayoutClass,
1813 VisitedVirtualBasesSetTy &VBases) {
1814 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1815
1816 // Check if this base has a primary base.
1817 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1818
1819 // Check if it's virtual.
1820 if (Layout.isPrimaryBaseVirtual()) {
1821 bool IsPrimaryVirtualBase = true;
1822
1823 if (isBuildingConstructorVTable()) {
1824 // Check if the base is actually a primary base in the class we use for
1825 // layout.
1826 const ASTRecordLayout &LayoutClassLayout =
1827 Context.getASTRecordLayout(LayoutClass);
1828
1829 CharUnits PrimaryBaseOffsetInLayoutClass =
1830 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1831
1832 // We know that the base is not a primary base in the layout class if
1833 // the base offsets are different.
1834 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1835 IsPrimaryVirtualBase = false;
1836 }
1837
1838 if (IsPrimaryVirtualBase)
1839 PrimaryVirtualBases.insert(PrimaryBase);
1840 }
1841 }
1842
1843 // Traverse bases, looking for more primary virtual bases.
1844 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1845 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001846 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001847
1848 CharUnits BaseOffsetInLayoutClass;
1849
1850 if (I->isVirtual()) {
1851 if (!VBases.insert(BaseDecl))
1852 continue;
1853
1854 const ASTRecordLayout &LayoutClassLayout =
1855 Context.getASTRecordLayout(LayoutClass);
1856
1857 BaseOffsetInLayoutClass =
1858 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1859 } else {
1860 BaseOffsetInLayoutClass =
1861 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1862 }
1863
1864 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1865 }
1866}
1867
1868void
1869VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1870 VisitedVirtualBasesSetTy &VBases) {
1871 // Itanium C++ ABI 2.5.2:
1872 // Then come the virtual base virtual tables, also in inheritance graph
1873 // order, and again excluding primary bases (which share virtual tables with
1874 // the classes for which they are primary).
1875 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1876 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001877 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001878
1879 // Check if this base needs a vtable. (If it's virtual, not a primary base
1880 // of some other class, and we haven't visited it before).
1881 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1882 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1883 const ASTRecordLayout &MostDerivedClassLayout =
1884 Context.getASTRecordLayout(MostDerivedClass);
1885 CharUnits BaseOffset =
1886 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1887
1888 const ASTRecordLayout &LayoutClassLayout =
1889 Context.getASTRecordLayout(LayoutClass);
1890 CharUnits BaseOffsetInLayoutClass =
1891 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1892
1893 LayoutPrimaryAndSecondaryVTables(
1894 BaseSubobject(BaseDecl, BaseOffset),
1895 /*BaseIsMorallyVirtual=*/true,
1896 /*BaseIsVirtualInLayoutClass=*/true,
1897 BaseOffsetInLayoutClass);
1898 }
1899
1900 // We only need to check the base for virtual base vtables if it actually
1901 // has virtual bases.
1902 if (BaseDecl->getNumVBases())
1903 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1904 }
1905}
1906
1907/// dumpLayout - Dump the vtable layout.
1908void VTableBuilder::dumpLayout(raw_ostream& Out) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00001909 // FIXME: write more tests that actually use the dumpLayout output to prevent
1910 // VTableBuilder regressions.
Peter Collingbourne24018462011-09-26 01:57:12 +00001911
1912 if (isBuildingConstructorVTable()) {
1913 Out << "Construction vtable for ('";
1914 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1915 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1916 Out << LayoutClass->getQualifiedNameAsString();
1917 } else {
1918 Out << "Vtable for '";
1919 Out << MostDerivedClass->getQualifiedNameAsString();
1920 }
1921 Out << "' (" << Components.size() << " entries).\n";
1922
1923 // Iterate through the address points and insert them into a new map where
1924 // they are keyed by the index and not the base object.
1925 // Since an address point can be shared by multiple subobjects, we use an
1926 // STL multimap.
1927 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1928 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1929 E = AddressPoints.end(); I != E; ++I) {
1930 const BaseSubobject& Base = I->first;
1931 uint64_t Index = I->second;
1932
1933 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1934 }
1935
1936 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1937 uint64_t Index = I;
1938
1939 Out << llvm::format("%4d | ", I);
1940
1941 const VTableComponent &Component = Components[I];
1942
1943 // Dump the component.
1944 switch (Component.getKind()) {
1945
1946 case VTableComponent::CK_VCallOffset:
1947 Out << "vcall_offset ("
1948 << Component.getVCallOffset().getQuantity()
1949 << ")";
1950 break;
1951
1952 case VTableComponent::CK_VBaseOffset:
1953 Out << "vbase_offset ("
1954 << Component.getVBaseOffset().getQuantity()
1955 << ")";
1956 break;
1957
1958 case VTableComponent::CK_OffsetToTop:
1959 Out << "offset_to_top ("
1960 << Component.getOffsetToTop().getQuantity()
1961 << ")";
1962 break;
1963
1964 case VTableComponent::CK_RTTI:
1965 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1966 break;
1967
1968 case VTableComponent::CK_FunctionPointer: {
1969 const CXXMethodDecl *MD = Component.getFunctionDecl();
1970
1971 std::string Str =
1972 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1973 MD);
1974 Out << Str;
1975 if (MD->isPure())
1976 Out << " [pure]";
1977
David Blaikied954ab42012-10-16 20:25:33 +00001978 if (MD->isDeleted())
1979 Out << " [deleted]";
1980
Peter Collingbourne24018462011-09-26 01:57:12 +00001981 ThunkInfo Thunk = VTableThunks.lookup(I);
1982 if (!Thunk.isEmpty()) {
1983 // If this function pointer has a return adjustment, dump it.
1984 if (!Thunk.Return.isEmpty()) {
1985 Out << "\n [return adjustment: ";
1986 Out << Thunk.Return.NonVirtual << " non-virtual";
1987
1988 if (Thunk.Return.VBaseOffsetOffset) {
1989 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1990 Out << " vbase offset offset";
1991 }
1992
1993 Out << ']';
1994 }
1995
1996 // If this function pointer has a 'this' pointer adjustment, dump it.
1997 if (!Thunk.This.isEmpty()) {
1998 Out << "\n [this adjustment: ";
1999 Out << Thunk.This.NonVirtual << " non-virtual";
2000
2001 if (Thunk.This.VCallOffsetOffset) {
2002 Out << ", " << Thunk.This.VCallOffsetOffset;
2003 Out << " vcall offset offset";
2004 }
2005
2006 Out << ']';
2007 }
2008 }
2009
2010 break;
2011 }
2012
2013 case VTableComponent::CK_CompleteDtorPointer:
2014 case VTableComponent::CK_DeletingDtorPointer: {
2015 bool IsComplete =
2016 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2017
2018 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2019
2020 Out << DD->getQualifiedNameAsString();
2021 if (IsComplete)
2022 Out << "() [complete]";
2023 else
2024 Out << "() [deleting]";
2025
2026 if (DD->isPure())
2027 Out << " [pure]";
2028
2029 ThunkInfo Thunk = VTableThunks.lookup(I);
2030 if (!Thunk.isEmpty()) {
2031 // If this destructor has a 'this' pointer adjustment, dump it.
2032 if (!Thunk.This.isEmpty()) {
2033 Out << "\n [this adjustment: ";
2034 Out << Thunk.This.NonVirtual << " non-virtual";
2035
2036 if (Thunk.This.VCallOffsetOffset) {
2037 Out << ", " << Thunk.This.VCallOffsetOffset;
2038 Out << " vcall offset offset";
2039 }
2040
2041 Out << ']';
2042 }
2043 }
2044
2045 break;
2046 }
2047
2048 case VTableComponent::CK_UnusedFunctionPointer: {
2049 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2050
2051 std::string Str =
2052 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2053 MD);
2054 Out << "[unused] " << Str;
2055 if (MD->isPure())
2056 Out << " [pure]";
2057 }
2058
2059 }
2060
2061 Out << '\n';
2062
2063 // Dump the next address point.
2064 uint64_t NextIndex = Index + 1;
2065 if (AddressPointsByIndex.count(NextIndex)) {
2066 if (AddressPointsByIndex.count(NextIndex) == 1) {
2067 const BaseSubobject &Base =
2068 AddressPointsByIndex.find(NextIndex)->second;
2069
2070 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2071 Out << ", " << Base.getBaseOffset().getQuantity();
2072 Out << ") vtable address --\n";
2073 } else {
2074 CharUnits BaseOffset =
2075 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2076
2077 // We store the class names in a set to get a stable order.
2078 std::set<std::string> ClassNames;
2079 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2080 AddressPointsByIndex.lower_bound(NextIndex), E =
2081 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2082 assert(I->second.getBaseOffset() == BaseOffset &&
2083 "Invalid base offset!");
2084 const CXXRecordDecl *RD = I->second.getBase();
2085 ClassNames.insert(RD->getQualifiedNameAsString());
2086 }
2087
2088 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2089 E = ClassNames.end(); I != E; ++I) {
2090 Out << " -- (" << *I;
2091 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2092 }
2093 }
2094 }
2095 }
2096
2097 Out << '\n';
2098
2099 if (isBuildingConstructorVTable())
2100 return;
2101
2102 if (MostDerivedClass->getNumVBases()) {
2103 // We store the virtual base class names and their offsets in a map to get
2104 // a stable order.
2105
2106 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2107 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2108 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2109 std::string ClassName = I->first->getQualifiedNameAsString();
2110 CharUnits OffsetOffset = I->second;
2111 ClassNamesAndOffsets.insert(
2112 std::make_pair(ClassName, OffsetOffset));
2113 }
2114
2115 Out << "Virtual base offset offsets for '";
2116 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2117 Out << ClassNamesAndOffsets.size();
2118 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2119
2120 for (std::map<std::string, CharUnits>::const_iterator I =
2121 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2122 I != E; ++I)
2123 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2124
2125 Out << "\n";
2126 }
2127
2128 if (!Thunks.empty()) {
2129 // We store the method names in a map to get a stable order.
2130 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2131
2132 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2133 I != E; ++I) {
2134 const CXXMethodDecl *MD = I->first;
2135 std::string MethodName =
2136 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2137 MD);
2138
2139 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2140 }
2141
2142 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2143 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2144 I != E; ++I) {
2145 const std::string &MethodName = I->first;
2146 const CXXMethodDecl *MD = I->second;
2147
2148 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2149 std::sort(ThunksVector.begin(), ThunksVector.end());
2150
2151 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2152 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2153
2154 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2155 const ThunkInfo &Thunk = ThunksVector[I];
2156
2157 Out << llvm::format("%4d | ", I);
2158
2159 // If this function pointer has a return pointer adjustment, dump it.
2160 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00002161 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbourne24018462011-09-26 01:57:12 +00002162 Out << " non-virtual";
2163 if (Thunk.Return.VBaseOffsetOffset) {
2164 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2165 Out << " vbase offset offset";
2166 }
2167
2168 if (!Thunk.This.isEmpty())
2169 Out << "\n ";
2170 }
2171
2172 // If this function pointer has a 'this' pointer adjustment, dump it.
2173 if (!Thunk.This.isEmpty()) {
2174 Out << "this adjustment: ";
2175 Out << Thunk.This.NonVirtual << " non-virtual";
2176
2177 if (Thunk.This.VCallOffsetOffset) {
2178 Out << ", " << Thunk.This.VCallOffsetOffset;
2179 Out << " vcall offset offset";
2180 }
2181 }
2182
2183 Out << '\n';
2184 }
2185
2186 Out << '\n';
2187 }
2188 }
2189
2190 // Compute the vtable indices for all the member functions.
2191 // Store them in a map keyed by the index so we'll get a sorted table.
2192 std::map<uint64_t, std::string> IndicesMap;
2193
2194 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2195 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002196 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002197
2198 // We only want virtual member functions.
2199 if (!MD->isVirtual())
2200 continue;
2201
2202 std::string MethodName =
2203 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2204 MD);
2205
2206 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002207 GlobalDecl GD(DD, Dtor_Complete);
2208 assert(MethodVTableIndices.count(GD));
2209 uint64_t VTableIndex = MethodVTableIndices[GD];
2210 IndicesMap[VTableIndex] = MethodName + " [complete]";
2211 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbourne24018462011-09-26 01:57:12 +00002212 } else {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002213 assert(MethodVTableIndices.count(MD));
2214 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbourne24018462011-09-26 01:57:12 +00002215 }
2216 }
2217
2218 // Print the vtable indices for all the member functions.
2219 if (!IndicesMap.empty()) {
2220 Out << "VTable indices for '";
2221 Out << MostDerivedClass->getQualifiedNameAsString();
2222 Out << "' (" << IndicesMap.size() << " entries).\n";
2223
2224 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2225 E = IndicesMap.end(); I != E; ++I) {
2226 uint64_t VTableIndex = I->first;
2227 const std::string &MethodName = I->second;
2228
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002229 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer79a55012012-03-10 02:06:27 +00002230 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002231 }
2232 }
2233
2234 Out << '\n';
2235}
2236
2237}
2238
2239VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2240 const VTableComponent *VTableComponents,
2241 uint64_t NumVTableThunks,
2242 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002243 const AddressPointsMapTy &AddressPoints,
2244 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002245 : NumVTableComponents(NumVTableComponents),
2246 VTableComponents(new VTableComponent[NumVTableComponents]),
2247 NumVTableThunks(NumVTableThunks),
2248 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002249 AddressPoints(AddressPoints),
2250 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002251 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002252 this->VTableComponents.get());
2253 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2254 this->VTableThunks.get());
Peter Collingbourne24018462011-09-26 01:57:12 +00002255}
2256
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002257VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002258
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002259VTableContext::VTableContext(ASTContext &Context)
Eli Friedman0a598fd2013-06-27 20:48:08 +00002260 : IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
John McCallb8b2c9d2013-01-25 22:30:49 +00002261}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002262
Peter Collingbourne24018462011-09-26 01:57:12 +00002263VTableContext::~VTableContext() {
2264 llvm::DeleteContainerSeconds(VTableLayouts);
2265}
2266
Peter Collingbourne24018462011-09-26 01:57:12 +00002267uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2268 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2269 if (I != MethodVTableIndices.end())
2270 return I->second;
2271
2272 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2273
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002274 computeVTableRelatedInformation(RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002275
2276 I = MethodVTableIndices.find(GD);
2277 assert(I != MethodVTableIndices.end() && "Did not find index!");
2278 return I->second;
2279}
2280
2281CharUnits
2282VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2283 const CXXRecordDecl *VBase) {
2284 ClassPairTy ClassPair(RD, VBase);
2285
2286 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2287 VirtualBaseClassOffsetOffsets.find(ClassPair);
2288 if (I != VirtualBaseClassOffsetOffsets.end())
2289 return I->second;
2290
2291 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2292 BaseSubobject(RD, CharUnits::Zero()),
2293 /*BaseIsVirtual=*/false,
2294 /*OffsetInLayoutClass=*/CharUnits::Zero());
2295
2296 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2297 Builder.getVBaseOffsetOffsets().begin(),
2298 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2299 // Insert all types.
2300 ClassPairTy ClassPair(RD, I->first);
2301
2302 VirtualBaseClassOffsetOffsets.insert(
2303 std::make_pair(ClassPair, I->second));
2304 }
2305
2306 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2307 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2308
2309 return I->second;
2310}
2311
2312static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2313 SmallVector<VTableLayout::VTableThunkTy, 1>
2314 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2315 std::sort(VTableThunks.begin(), VTableThunks.end());
2316
2317 return new VTableLayout(Builder.getNumVTableComponents(),
2318 Builder.vtable_component_begin(),
2319 VTableThunks.size(),
2320 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002321 Builder.getAddressPoints(),
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002322 /*IsMicrosoftABI=*/false);
Peter Collingbourne24018462011-09-26 01:57:12 +00002323}
2324
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002325void VTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002326 assert(!IsMicrosoftABI && "Shouldn't be called in this ABI!");
2327
Peter Collingbourne24018462011-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
2334 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2335 /*MostDerivedClassIsVirtual=*/0, RD);
2336 Entry = CreateVTableLayout(Builder);
2337
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002338 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2339 Builder.vtable_indices_end());
2340
Peter Collingbourne24018462011-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 Iskhodzhanov432d4882013-07-02 16:00:40 +00002350 const CXXRecordDecl *VBase =
2351 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00002352
2353 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2354 return;
2355
2356 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2357 Builder.getVBaseOffsetOffsets().begin(),
2358 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2359 // Insert all types.
2360 ClassPairTy ClassPair(RD, I->first);
2361
2362 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2363 }
2364}
2365
Peter Collingbourne24018462011-09-26 01:57:12 +00002366VTableLayout *VTableContext::createConstructionVTableLayout(
2367 const CXXRecordDecl *MostDerivedClass,
2368 CharUnits MostDerivedClassOffset,
2369 bool MostDerivedClassIsVirtual,
2370 const CXXRecordDecl *LayoutClass) {
2371 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2372 MostDerivedClassIsVirtual, LayoutClass);
2373 return CreateVTableLayout(Builder);
2374}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002375
2376unsigned clang::GetVBTableIndex(const CXXRecordDecl *Derived,
2377 const CXXRecordDecl *VBase) {
2378 unsigned VBTableIndex = 1; // Start with one to skip the self entry.
2379 for (CXXRecordDecl::base_class_const_iterator I = Derived->vbases_begin(),
2380 E = Derived->vbases_end(); I != E; ++I) {
2381 if (I->getType()->getAsCXXRecordDecl() == VBase)
2382 return VBTableIndex;
2383 ++VBTableIndex;
2384 }
2385 llvm_unreachable("VBase must be a vbase of Derived");
2386}
2387
2388namespace {
2389
2390// Vtables in the Microsoft ABI are different from the Itanium ABI.
2391//
2392// The main differences are:
2393// 1. Separate vftable and vbtable.
2394//
2395// 2. Each subobject with a vfptr gets its own vftable rather than an address
2396// point in a single vtable shared between all the subobjects.
2397// Each vftable is represented by a separate section and virtual calls
2398// must be done using the vftable which has a slot for the function to be
2399// called.
2400//
2401// 3. Virtual method definitions expect their 'this' parameter to point to the
2402// first vfptr whose table provides a compatible overridden method. In many
2403// cases, this permits the original vf-table entry to directly call
2404// the method instead of passing through a thunk.
2405//
2406// A compatible overridden method is one which does not have a non-trivial
2407// covariant-return adjustment.
2408//
2409// The first vfptr is the one with the lowest offset in the complete-object
2410// layout of the defining class, and the method definition will subtract
2411// that constant offset from the parameter value to get the real 'this'
2412// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2413// function defined in a virtual base is overridden in a more derived
2414// virtual base and these bases have a reverse order in the complete
2415// object), the vf-table may require a this-adjustment thunk.
2416//
2417// 4. vftables do not contain new entries for overrides that merely require
2418// this-adjustment. Together with #3, this keeps vf-tables smaller and
2419// eliminates the need for this-adjustment thunks in many cases, at the cost
2420// of often requiring redundant work to adjust the "this" pointer.
2421//
2422// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2423// Vtordisps are emitted into the class layout if a class has
2424// a) a user-defined ctor/dtor
2425// and
2426// b) a method overriding a method in a virtual base.
2427
2428class VFTableBuilder {
2429public:
2430 typedef MicrosoftVFTableContext::MethodVFTableLocation MethodVFTableLocation;
2431
2432 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2433 MethodVFTableLocationsTy;
2434
2435private:
2436 /// Context - The ASTContext which we will use for layout information.
2437 ASTContext &Context;
2438
2439 /// MostDerivedClass - The most derived class for which we're building this
2440 /// vtable.
2441 const CXXRecordDecl *MostDerivedClass;
2442
2443 const ASTRecordLayout &MostDerivedClassLayout;
2444
2445 VFPtrInfo WhichVFPtr;
2446
2447 /// FinalOverriders - The final overriders of the most derived class.
2448 const FinalOverriders Overriders;
2449
2450 /// Components - The components of the vftable being built.
2451 SmallVector<VTableComponent, 64> Components;
2452
2453 MethodVFTableLocationsTy MethodVFTableLocations;
2454
2455 /// MethodInfo - Contains information about a method in a vtable.
2456 /// (Used for computing 'this' pointer adjustment thunks.
2457 struct MethodInfo {
2458 /// VBTableIndex - The nonzero index in the vbtable that
2459 /// this method's base has, or zero.
2460 const uint64_t VBTableIndex;
2461
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002462 /// VBase - If nonnull, holds the last vbase which contains the vfptr that
2463 /// the method definition is adjusted to.
2464 const CXXRecordDecl *VBase;
2465
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002466 /// VFTableIndex - The index in the vftable that this method has.
2467 const uint64_t VFTableIndex;
2468
2469 /// Shadowed - Indicates if this vftable slot is shadowed by
2470 /// a slot for a covariant-return override. If so, it shouldn't be printed
2471 /// or used for vcalls in the most derived class.
2472 bool Shadowed;
2473
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002474 MethodInfo(uint64_t VBTableIndex, const CXXRecordDecl *VBase,
2475 uint64_t VFTableIndex)
2476 : VBTableIndex(VBTableIndex), VBase(VBase), VFTableIndex(VFTableIndex),
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002477 Shadowed(false) {}
2478
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002479 MethodInfo()
2480 : VBTableIndex(0), VBase(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002481 };
2482
2483 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2484
2485 /// MethodInfoMap - The information for all methods in the vftable we're
2486 /// currently building.
2487 MethodInfoMapTy MethodInfoMap;
2488
2489 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2490
2491 /// VTableThunks - The thunks by vftable index in the vftable currently being
2492 /// built.
2493 VTableThunksMapTy VTableThunks;
2494
2495 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2496 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2497
2498 /// Thunks - A map that contains all the thunks needed for all methods in the
2499 /// most derived class for which the vftable is currently being built.
2500 ThunksMapTy Thunks;
2501
2502 /// AddThunk - Add a thunk for the given method.
2503 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2504 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2505
2506 // Check if we have this thunk already.
2507 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2508 ThunksVector.end())
2509 return;
2510
2511 ThunksVector.push_back(Thunk);
2512 }
2513
2514 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2515 /// method in the given subobject, relative to the beginning of the
2516 /// MostDerivedClass.
2517 CharUnits ComputeThisOffset(const CXXMethodDecl *MD,
2518 BaseSubobject Base,
2519 FinalOverriders::OverriderInfo Overrider);
2520
2521 /// AddMethod - Add a single virtual member function to the vftable
2522 /// components vector.
2523 void AddMethod(const CXXMethodDecl *MD, ThisAdjustment ThisAdjustment,
2524 ReturnAdjustment ReturnAdjustment) {
2525 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2526 assert(ReturnAdjustment.isEmpty() &&
2527 "Destructor can't have return adjustment!");
2528 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2529 } else {
2530 // Add the return adjustment if necessary.
2531 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
2532 VTableThunks[Components.size()].Return = ReturnAdjustment;
2533 VTableThunks[Components.size()].This = ThisAdjustment;
2534 }
2535 Components.push_back(VTableComponent::MakeFunction(MD));
2536 }
2537 }
2538
2539 /// AddMethods - Add the methods of this base subobject and the relevant
2540 /// subbases to the vftable we're currently laying out.
2541 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2542 const CXXRecordDecl *LastVBase,
2543 BasesSetVectorTy &VisitedBases);
2544
2545 void LayoutVFTable() {
2546 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2547 // pointing to the middle of a section.
2548
2549 BasesSetVectorTy VisitedBases;
2550 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2551 VisitedBases);
2552
2553 assert(MethodVFTableLocations.empty());
2554 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2555 E = MethodInfoMap.end(); I != E; ++I) {
2556 const CXXMethodDecl *MD = I->first;
2557 const MethodInfo &MI = I->second;
2558 // Skip the methods that the MostDerivedClass didn't override
2559 // and the entries shadowed by return adjusting thunks.
2560 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2561 continue;
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002562 MethodVFTableLocation Loc(MI.VBTableIndex, MI.VBase,
2563 WhichVFPtr.VFPtrOffset, MI.VFTableIndex);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002564 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2565 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2566 } else {
2567 MethodVFTableLocations[MD] = Loc;
2568 }
2569 }
2570 }
2571
2572 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2573 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2574 unsigned DiagID = Diags.getCustomDiagID(
2575 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2576 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2577 }
2578
2579public:
2580 VFTableBuilder(const CXXRecordDecl *MostDerivedClass, VFPtrInfo Which)
2581 : Context(MostDerivedClass->getASTContext()),
2582 MostDerivedClass(MostDerivedClass),
2583 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2584 WhichVFPtr(Which),
2585 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2586 LayoutVFTable();
2587
2588 if (Context.getLangOpts().DumpVTableLayouts)
2589 dumpLayout(llvm::errs());
2590 }
2591
2592 uint64_t getNumThunks() const { return Thunks.size(); }
2593
2594 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2595
2596 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2597
2598 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2599 return MethodVFTableLocations.begin();
2600 }
2601
2602 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2603 return MethodVFTableLocations.end();
2604 }
2605
2606 uint64_t getNumVTableComponents() const { return Components.size(); }
2607
2608 const VTableComponent *vtable_component_begin() const {
2609 return Components.begin();
2610 }
2611
2612 const VTableComponent *vtable_component_end() const {
2613 return Components.end();
2614 }
2615
2616 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2617 return VTableThunks.begin();
2618 }
2619
2620 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2621 return VTableThunks.end();
2622 }
2623
2624 void dumpLayout(raw_ostream &);
2625};
2626
2627/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2628/// that define the given method.
2629struct InitialOverriddenDefinitionCollector {
2630 BasesSetVectorTy Bases;
2631 OverriddenMethodsSetTy VisitedOverriddenMethods;
2632
2633 bool visit(const CXXMethodDecl *OverriddenMD) {
2634 if (OverriddenMD->size_overridden_methods() == 0)
2635 Bases.insert(OverriddenMD->getParent());
2636 // Don't recurse on this method if we've already collected it.
2637 return VisitedOverriddenMethods.insert(OverriddenMD);
2638 }
2639};
2640
2641static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2642 CXXBasePath &Path, void *BasesSet) {
2643 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2644 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2645}
2646
2647CharUnits
2648VFTableBuilder::ComputeThisOffset(const CXXMethodDecl *MD,
2649 BaseSubobject Base,
2650 FinalOverriders::OverriderInfo Overrider) {
2651 // Complete object virtual destructors are always emitted in the most derived
2652 // class, thus don't have this offset.
2653 if (isa<CXXDestructorDecl>(MD))
2654 return CharUnits();
2655
2656 InitialOverriddenDefinitionCollector Collector;
2657 visitAllOverriddenMethods(MD, Collector);
2658
2659 CXXBasePaths Paths;
2660 Base.getBase()->lookupInBases(BaseInSet, &Collector.Bases, Paths);
2661
2662 // This will hold the smallest this offset among overridees of MD.
2663 // This implies that an offset of a non-virtual base will dominate an offset
2664 // of a virtual base to potentially reduce the number of thunks required
2665 // in the derived classes that inherit this method.
2666 CharUnits Ret;
2667 bool First = true;
2668
2669 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2670 I != E; ++I) {
2671 const CXXBasePath &Path = (*I);
2672 CharUnits ThisOffset = Base.getBaseOffset();
2673
2674 // For each path from the overrider to the parents of the overridden methods,
2675 // traverse the path, calculating the this offset in the most derived class.
2676 for (int J = 0, F = Path.size(); J != F; ++J) {
2677 const CXXBasePathElement &Element = Path[J];
2678 QualType CurTy = Element.Base->getType();
2679 const CXXRecordDecl *PrevRD = Element.Class,
2680 *CurRD = CurTy->getAsCXXRecordDecl();
2681 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2682
2683 if (Element.Base->isVirtual()) {
2684 if (Overrider.Method->getParent() == PrevRD) {
2685 // This one's interesting. If the final overrider is in a vbase B of the
2686 // most derived class and it overrides a method of the B's own vbase A,
2687 // it uses A* as "this". In its prologue, it can cast A* to B* with
2688 // a static offset. This offset is used regardless of the actual
2689 // offset of A from B in the most derived class, requiring an
2690 // this-adjusting thunk in the vftable if A and B are laid out
2691 // differently in the most derived class.
2692 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2693 } else {
2694 ThisOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
2695 }
2696 } else {
2697 ThisOffset += Layout.getBaseClassOffset(CurRD);
2698 }
2699 }
2700
2701 if (Ret > ThisOffset || First) {
2702 First = false;
2703 Ret = ThisOffset;
2704 }
2705 }
2706
2707 assert(!First && "Method not found in the given subobject?");
2708 return Ret;
2709}
2710
2711static const CXXMethodDecl*
2712FindDirectlyOverriddenMethodInBases(const CXXMethodDecl *MD,
2713 BasesSetVectorTy &Bases) {
2714 // We can't just iterate over the overridden methods and return the first one
2715 // which has its parent in Bases, e.g. this doesn't work when we have
2716 // multiple subobjects of the same type that have its virtual function
2717 // overridden.
2718 for (int I = Bases.size(), E = 0; I != E; --I) {
2719 const CXXRecordDecl *CurrentBase = Bases[I - 1];
2720
2721 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2722 E = MD->end_overridden_methods(); I != E; ++I) {
2723 const CXXMethodDecl *OverriddenMD = *I;
2724
2725 if (OverriddenMD->getParent() == CurrentBase)
2726 return OverriddenMD;
2727 }
2728 }
2729
2730 return 0;
2731}
2732
2733void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2734 const CXXRecordDecl *LastVBase,
2735 BasesSetVectorTy &VisitedBases) {
2736 const CXXRecordDecl *RD = Base.getBase();
2737 if (!RD->isPolymorphic())
2738 return;
2739
2740 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2741
2742 // See if this class expands a vftable of the base we look at, which is either
2743 // the one defined by the vfptr base path or the primary base of the current class.
2744 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2745 CharUnits NextBaseOffset;
2746 if (BaseDepth < WhichVFPtr.PathToBaseWithVFPtr.size()) {
2747 NextBase = WhichVFPtr.PathToBaseWithVFPtr[BaseDepth];
2748 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2749 NextLastVBase = NextBase;
2750 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2751 } else {
2752 NextBaseOffset =
2753 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2754 }
2755 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2756 assert(!Layout.isPrimaryBaseVirtual() &&
2757 "No primary virtual bases in this ABI");
2758 NextBase = PrimaryBase;
2759 NextBaseOffset = Base.getBaseOffset();
2760 }
2761
2762 if (NextBase) {
2763 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2764 NextLastVBase, VisitedBases);
2765 if (!VisitedBases.insert(NextBase))
2766 llvm_unreachable("Found a duplicate primary base!");
2767 }
2768
2769 // Now go through all virtual member functions and add them to the current
2770 // vftable. This is done by
2771 // - replacing overridden methods in their existing slots, as long as they
2772 // don't require return adjustment; calculating This adjustment if needed.
2773 // - adding new slots for methods of the current base not present in any
2774 // sub-bases;
2775 // - adding new slots for methods that require Return adjustment.
2776 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
2777 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2778 E = RD->method_end(); I != E; ++I) {
2779 const CXXMethodDecl *MD = *I;
2780
2781 if (!MD->isVirtual())
2782 continue;
2783
2784 FinalOverriders::OverriderInfo Overrider =
2785 Overriders.getOverrider(MD, Base.getBaseOffset());
2786 ThisAdjustment ThisAdjustmentOffset;
2787
2788 // Check if this virtual member function overrides
2789 // a method in one of the visited bases.
2790 if (const CXXMethodDecl *OverriddenMD =
2791 FindDirectlyOverriddenMethodInBases(MD, VisitedBases)) {
2792 MethodInfoMapTy::iterator OverriddenMDIterator =
2793 MethodInfoMap.find(OverriddenMD);
2794
2795 // If the overridden method went to a different vftable, skip it.
2796 if (OverriddenMDIterator == MethodInfoMap.end())
2797 continue;
2798
2799 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2800
2801 // Create a this-adjusting thunk if needed.
2802 CharUnits TI = ComputeThisOffset(MD, Base, Overrider);
2803 if (TI != WhichVFPtr.VFPtrFullOffset) {
2804 ThisAdjustmentOffset.NonVirtual =
2805 (TI - WhichVFPtr.VFPtrFullOffset).getQuantity();
2806 VTableThunks[OverriddenMethodInfo.VFTableIndex].This =
2807 ThisAdjustmentOffset;
2808 AddThunk(MD, VTableThunks[OverriddenMethodInfo.VFTableIndex]);
2809 }
2810
2811 if (ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD)
2812 .isEmpty()) {
2813 // No return adjustment needed - just replace the overridden method info
2814 // with the current info.
2815 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002816 OverriddenMethodInfo.VBase,
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002817 OverriddenMethodInfo.VFTableIndex);
2818 MethodInfoMap.erase(OverriddenMDIterator);
2819
2820 assert(!MethodInfoMap.count(MD) &&
2821 "Should not have method info for this method yet!");
2822 MethodInfoMap.insert(std::make_pair(MD, MI));
2823 continue;
2824 } else {
2825 // In case we need a return adjustment, we'll add a new slot for
2826 // the overrider and put a return-adjusting thunk where the overridden
2827 // method was in the vftable.
2828 // For now, just mark the overriden method as shadowed by a new slot.
2829 OverriddenMethodInfo.Shadowed = true;
2830
2831 // Also apply this adjustment to the shadowed slots.
2832 if (!ThisAdjustmentOffset.isEmpty()) {
2833 // FIXME: this is O(N^2), can be O(N).
2834 const CXXMethodDecl *SubOverride = OverriddenMD;
2835 while ((SubOverride =
2836 FindDirectlyOverriddenMethodInBases(SubOverride, VisitedBases))) {
2837 MethodInfoMapTy::iterator SubOverrideIterator =
2838 MethodInfoMap.find(SubOverride);
2839 if (SubOverrideIterator == MethodInfoMap.end())
2840 break;
2841 MethodInfo &SubOverrideMI = SubOverrideIterator->second;
2842 assert(SubOverrideMI.Shadowed);
2843 VTableThunks[SubOverrideMI.VFTableIndex].This =
2844 ThisAdjustmentOffset;
2845 AddThunk(MD, VTableThunks[SubOverrideMI.VFTableIndex]);
2846 }
2847 }
2848 }
2849 } else if (Base.getBaseOffset() != WhichVFPtr.VFPtrFullOffset ||
2850 MD->size_overridden_methods()) {
2851 // Skip methods that don't belong to the vftable of the current class,
2852 // e.g. each method that wasn't seen in any of the visited sub-bases
2853 // but overrides multiple methods of other sub-bases.
2854 continue;
2855 }
2856
2857 // If we got here, MD is a method not seen in any of the sub-bases or
2858 // it requires return adjustment. Insert the method info for this method.
2859 unsigned VBIndex =
2860 LastVBase ? GetVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002861 MethodInfo MI(VBIndex, LastVBase, Components.size());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002862
2863 assert(!MethodInfoMap.count(MD) &&
2864 "Should not have method info for this method yet!");
2865 MethodInfoMap.insert(std::make_pair(MD, MI));
2866
2867 const CXXMethodDecl *OverriderMD = Overrider.Method;
2868
2869 // Check if this overrider needs a return adjustment.
2870 // We don't want to do this for pure virtual member functions.
2871 BaseOffset ReturnAdjustmentOffset;
2872 ReturnAdjustment ReturnAdjustment;
2873 if (!OverriderMD->isPure()) {
2874 ReturnAdjustmentOffset =
2875 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2876 }
2877 if (!ReturnAdjustmentOffset.isEmpty()) {
2878 ReturnAdjustment.NonVirtual =
2879 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2880 if (ReturnAdjustmentOffset.VirtualBase) {
2881 // FIXME: We might want to create a VBIndex alias for VBaseOffsetOffset
2882 // in the ReturnAdjustment struct.
2883 ReturnAdjustment.VBaseOffsetOffset =
2884 GetVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2885 ReturnAdjustmentOffset.VirtualBase);
2886 }
2887 }
2888
2889 AddMethod(Overrider.Method, ThisAdjustmentOffset, ReturnAdjustment);
2890 }
2891}
2892
2893void PrintBasePath(const VFPtrInfo::BasePath &Path, raw_ostream &Out) {
2894 for (VFPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
2895 E = Path.rend(); I != E; ++I) {
2896 Out << "'" << (*I)->getQualifiedNameAsString() << "' in ";
2897 }
2898}
2899
2900void VFTableBuilder::dumpLayout(raw_ostream &Out) {
2901 Out << "VFTable for ";
2902 PrintBasePath(WhichVFPtr.PathToBaseWithVFPtr, Out);
2903 Out << "'" << MostDerivedClass->getQualifiedNameAsString();
2904 Out << "' (" << Components.size() << " entries).\n";
2905
2906 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2907 Out << llvm::format("%4d | ", I);
2908
2909 const VTableComponent &Component = Components[I];
2910
2911 // Dump the component.
2912 switch (Component.getKind()) {
2913 case VTableComponent::CK_RTTI:
2914 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2915 break;
2916
2917 case VTableComponent::CK_FunctionPointer: {
2918 const CXXMethodDecl *MD = Component.getFunctionDecl();
2919
2920 std::string Str = PredefinedExpr::ComputeName(
2921 PredefinedExpr::PrettyFunctionNoVirtual, MD);
2922 Out << Str;
2923 if (MD->isPure())
2924 Out << " [pure]";
2925
2926 if (MD->isDeleted()) {
2927 ErrorUnsupported("deleted methods", MD->getLocation());
2928 Out << " [deleted]";
2929 }
2930
2931 ThunkInfo Thunk = VTableThunks.lookup(I);
2932 if (!Thunk.isEmpty()) {
2933 // If this function pointer has a return adjustment, dump it.
2934 if (!Thunk.Return.isEmpty()) {
2935 Out << "\n [return adjustment: ";
2936 if (Thunk.Return.VBaseOffsetOffset)
2937 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
2938 Out << Thunk.Return.NonVirtual << " non-virtual]";
2939 }
2940
2941 // If this function pointer has a 'this' pointer adjustment, dump it.
2942 if (!Thunk.This.isEmpty()) {
2943 assert(!Thunk.This.VCallOffsetOffset &&
2944 "No virtual this adjustment in this ABI");
2945 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
2946 << " non-virtual]";
2947 }
2948 }
2949
2950 break;
2951 }
2952
2953 case VTableComponent::CK_DeletingDtorPointer: {
2954 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2955
2956 Out << DD->getQualifiedNameAsString();
2957 Out << "() [scalar deleting]";
2958
2959 if (DD->isPure())
2960 Out << " [pure]";
2961
2962 ThunkInfo Thunk = VTableThunks.lookup(I);
2963 if (!Thunk.isEmpty()) {
2964 assert(Thunk.Return.isEmpty() &&
2965 "No return adjustment needed for destructors!");
2966 // If this destructor has a 'this' pointer adjustment, dump it.
2967 if (!Thunk.This.isEmpty()) {
2968 assert(!Thunk.This.VCallOffsetOffset &&
2969 "No virtual this adjustment in this ABI");
2970 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
2971 << " non-virtual]";
2972 }
2973 }
2974
2975 break;
2976 }
2977
2978 default:
2979 DiagnosticsEngine &Diags = Context.getDiagnostics();
2980 unsigned DiagID = Diags.getCustomDiagID(
2981 DiagnosticsEngine::Error,
2982 "Unexpected vftable component type %0 for component number %1");
2983 Diags.Report(MostDerivedClass->getLocation(), DiagID)
2984 << I << Component.getKind();
2985 }
2986
2987 Out << '\n';
2988 }
2989
2990 Out << '\n';
2991
2992 if (!Thunks.empty()) {
2993 // We store the method names in a map to get a stable order.
2994 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2995
2996 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2997 I != E; ++I) {
2998 const CXXMethodDecl *MD = I->first;
2999 std::string MethodName = PredefinedExpr::ComputeName(
3000 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3001
3002 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3003 }
3004
3005 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3006 I = MethodNamesAndDecls.begin(),
3007 E = MethodNamesAndDecls.end();
3008 I != E; ++I) {
3009 const std::string &MethodName = I->first;
3010 const CXXMethodDecl *MD = I->second;
3011
3012 ThunkInfoVectorTy ThunksVector = Thunks[MD];
3013 std::sort(ThunksVector.begin(), ThunksVector.end());
3014
3015 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3016 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3017
3018 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3019 const ThunkInfo &Thunk = ThunksVector[I];
3020
3021 Out << llvm::format("%4d | ", I);
3022
3023 // If this function pointer has a return pointer adjustment, dump it.
3024 if (!Thunk.Return.isEmpty()) {
3025 Out << "return adjustment: ";
3026 if (Thunk.Return.VBaseOffsetOffset)
3027 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
3028 Out << Thunk.Return.NonVirtual << " non-virtual";
3029
3030 if (!Thunk.This.isEmpty())
3031 Out << "\n ";
3032 }
3033
3034 // If this function pointer has a 'this' pointer adjustment, dump it.
3035 if (!Thunk.This.isEmpty()) {
3036 assert(!Thunk.This.VCallOffsetOffset &&
3037 "No virtual this adjustment in this ABI");
3038 Out << "this adjustment: ";
3039 Out << Thunk.This.NonVirtual << " non-virtual";
3040 }
3041
3042 Out << '\n';
3043 }
3044
3045 Out << '\n';
3046 }
3047 }
3048}
3049}
3050
3051static void EnumerateVFPtrs(
3052 ASTContext &Context, const CXXRecordDecl *MostDerivedClass,
3053 const ASTRecordLayout &MostDerivedClassLayout,
3054 BaseSubobject Base, const CXXRecordDecl *LastVBase,
3055 const VFPtrInfo::BasePath &PathFromCompleteClass,
3056 BasesSetVectorTy &VisitedVBases,
3057 MicrosoftVFTableContext::VFPtrListTy &Result) {
3058 const CXXRecordDecl *CurrentClass = Base.getBase();
3059 CharUnits OffsetInCompleteClass = Base.getBaseOffset();
3060 const ASTRecordLayout &CurrentClassLayout =
3061 Context.getASTRecordLayout(CurrentClass);
3062
3063 if (CurrentClassLayout.hasOwnVFPtr()) {
3064 if (LastVBase) {
3065 uint64_t VBIndex = GetVBTableIndex(MostDerivedClass, LastVBase);
3066 assert(VBIndex > 0 && "vbases must have vbindex!");
3067 CharUnits VFPtrOffset =
3068 OffsetInCompleteClass -
3069 MostDerivedClassLayout.getVBaseClassOffset(LastVBase);
3070 Result.push_back(VFPtrInfo(VBIndex, LastVBase, VFPtrOffset,
3071 PathFromCompleteClass, OffsetInCompleteClass));
3072 } else {
3073 Result.push_back(VFPtrInfo(OffsetInCompleteClass, PathFromCompleteClass));
3074 }
3075 }
3076
3077 for (CXXRecordDecl::base_class_const_iterator I = CurrentClass->bases_begin(),
3078 E = CurrentClass->bases_end(); I != E; ++I) {
3079 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
3080
3081 CharUnits NextBaseOffset;
3082 const CXXRecordDecl *NextLastVBase;
3083 if (I->isVirtual()) {
3084 if (VisitedVBases.count(BaseDecl))
3085 continue;
3086 VisitedVBases.insert(BaseDecl);
3087 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
3088 NextLastVBase = BaseDecl;
3089 } else {
3090 NextBaseOffset = OffsetInCompleteClass +
3091 CurrentClassLayout.getBaseClassOffset(BaseDecl);
3092 NextLastVBase = LastVBase;
3093 }
3094
3095 VFPtrInfo::BasePath NewPath = PathFromCompleteClass;
3096 NewPath.push_back(BaseDecl);
3097 BaseSubobject NextBase(BaseDecl, NextBaseOffset);
3098
3099 EnumerateVFPtrs(Context, MostDerivedClass, MostDerivedClassLayout, NextBase,
3100 NextLastVBase, NewPath, VisitedVBases, Result);
3101 }
3102}
3103
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003104/// CalculatePathToMangle - Calculate the subset of records that should be used
3105/// to mangle the vftable for the given vfptr.
3106/// Should only be called if a class has multiple vftables.
3107static void
3108CalculatePathToMangle(const CXXRecordDecl *RD, VFPtrInfo &VFPtr) {
3109 // FIXME: In some rare cases this code produces a slightly incorrect mangling.
3110 // It's very likely that the vbtable mangling code can be adjusted to mangle
3111 // both vftables and vbtables correctly.
3112
3113 VFPtrInfo::BasePath &FullPath = VFPtr.PathToBaseWithVFPtr;
3114 if (FullPath.empty()) {
3115 // Mangle the class's own vftable.
3116 assert(RD->getNumVBases() &&
3117 "Something's wrong: if the most derived "
3118 "class has more than one vftable, it can only have its own "
3119 "vftable if it has vbases");
3120 VFPtr.PathToMangle.push_back(RD);
3121 return;
3122 }
3123
3124 unsigned Begin = 0;
3125
3126 // First, skip all the bases before the vbase.
3127 if (VFPtr.LastVBase) {
3128 while (FullPath[Begin] != VFPtr.LastVBase) {
3129 Begin++;
3130 assert(Begin < FullPath.size());
3131 }
3132 }
3133
3134 // Then, put the rest of the base path in the reverse order.
3135 for (unsigned I = FullPath.size(); I != Begin; --I) {
3136 const CXXRecordDecl *CurBase = FullPath[I - 1],
3137 *ItsBase = (I == 1) ? RD : FullPath[I - 2];
3138 bool BaseIsVirtual = false;
3139 for (CXXRecordDecl::base_class_const_iterator J = ItsBase->bases_begin(),
3140 F = ItsBase->bases_end(); J != F; ++J) {
3141 if (J->getType()->getAsCXXRecordDecl() == CurBase) {
3142 BaseIsVirtual = J->isVirtual();
3143 break;
3144 }
3145 }
3146
3147 // Should skip the current base if it is a non-virtual base with no siblings.
3148 if (BaseIsVirtual || ItsBase->getNumBases() != 1)
3149 VFPtr.PathToMangle.push_back(CurBase);
3150 }
3151}
3152
Benjamin Kramer3b142da2013-08-01 11:08:06 +00003153static void EnumerateVFPtrs(ASTContext &Context, const CXXRecordDecl *ForClass,
3154 MicrosoftVFTableContext::VFPtrListTy &Result) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003155 Result.clear();
3156 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(ForClass);
3157 BasesSetVectorTy VisitedVBases;
3158 EnumerateVFPtrs(Context, ForClass, ClassLayout,
3159 BaseSubobject(ForClass, CharUnits::Zero()), 0,
3160 VFPtrInfo::BasePath(), VisitedVBases, Result);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003161 if (Result.size() > 1) {
3162 for (unsigned I = 0, E = Result.size(); I != E; ++I)
3163 CalculatePathToMangle(ForClass, Result[I]);
3164 }
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003165}
3166
3167void MicrosoftVFTableContext::computeVTableRelatedInformation(
3168 const CXXRecordDecl *RD) {
3169 assert(RD->isDynamicClass());
3170
3171 // Check if we've computed this information before.
3172 if (VFPtrLocations.count(RD))
3173 return;
3174
3175 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3176
3177 VFPtrListTy &VFPtrs = VFPtrLocations[RD];
3178 EnumerateVFPtrs(Context, RD, VFPtrs);
3179
3180 MethodVFTableLocationsTy NewMethodLocations;
3181 for (VFPtrListTy::iterator I = VFPtrs.begin(), E = VFPtrs.end();
3182 I != E; ++I) {
3183 VFTableBuilder Builder(RD, *I);
3184
3185 VFTableIdTy id(RD, I->VFPtrFullOffset);
3186 assert(VFTableLayouts.count(id) == 0);
3187 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3188 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
3189 std::sort(VTableThunks.begin(), VTableThunks.end());
3190 VFTableLayouts[id] = new VTableLayout(
3191 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3192 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3193 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3194 Builder.vtable_indices_end());
3195 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3196 }
3197
3198 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3199 NewMethodLocations.end());
3200 if (Context.getLangOpts().DumpVTableLayouts)
3201 dumpMethodLocations(RD, NewMethodLocations, llvm::errs());
3202}
3203
3204void MicrosoftVFTableContext::dumpMethodLocations(
3205 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3206 raw_ostream &Out) {
3207 // Compute the vtable indices for all the member functions.
3208 // Store them in a map keyed by the location so we'll get a sorted table.
3209 std::map<MethodVFTableLocation, std::string> IndicesMap;
3210 bool HasNonzeroOffset = false;
3211
3212 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3213 E = NewMethods.end(); I != E; ++I) {
3214 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3215 assert(MD->isVirtual());
3216
3217 std::string MethodName = PredefinedExpr::ComputeName(
3218 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3219
3220 if (isa<CXXDestructorDecl>(MD)) {
3221 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3222 } else {
3223 IndicesMap[I->second] = MethodName;
3224 }
3225
3226 if (!I->second.VFTableOffset.isZero() || I->second.VBTableIndex != 0)
3227 HasNonzeroOffset = true;
3228 }
3229
3230 // Print the vtable indices for all the member functions.
3231 if (!IndicesMap.empty()) {
3232 Out << "VFTable indices for ";
3233 Out << "'" << RD->getQualifiedNameAsString();
3234 Out << "' (" << IndicesMap.size() << " entries).\n";
3235
3236 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3237 uint64_t LastVBIndex = 0;
3238 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3239 I = IndicesMap.begin(),
3240 E = IndicesMap.end();
3241 I != E; ++I) {
3242 CharUnits VFPtrOffset = I->first.VFTableOffset;
3243 uint64_t VBIndex = I->first.VBTableIndex;
3244 if (HasNonzeroOffset &&
3245 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3246 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3247 Out << " -- accessible via ";
3248 if (VBIndex)
3249 Out << "vbtable index " << VBIndex << ", ";
3250 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3251 LastVFPtrOffset = VFPtrOffset;
3252 LastVBIndex = VBIndex;
3253 }
3254
3255 uint64_t VTableIndex = I->first.Index;
3256 const std::string &MethodName = I->second;
3257 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3258 }
3259 Out << '\n';
3260 }
3261}
3262
3263const MicrosoftVFTableContext::VFPtrListTy &
3264MicrosoftVFTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3265 computeVTableRelatedInformation(RD);
3266
3267 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3268 return VFPtrLocations[RD];
3269}
3270
3271const VTableLayout &
3272MicrosoftVFTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3273 CharUnits VFPtrOffset) {
3274 computeVTableRelatedInformation(RD);
3275
3276 VFTableIdTy id(RD, VFPtrOffset);
3277 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3278 return *VFTableLayouts[id];
3279}
3280
3281const MicrosoftVFTableContext::MethodVFTableLocation &
3282MicrosoftVFTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3283 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3284 "Only use this method for virtual methods or dtors");
3285 if (isa<CXXDestructorDecl>(GD.getDecl()))
3286 assert(GD.getDtorType() == Dtor_Deleting);
3287
3288 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3289 if (I != MethodVFTableLocations.end())
3290 return I->second;
3291
3292 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3293
3294 computeVTableRelatedInformation(RD);
3295
3296 I = MethodVFTableLocations.find(GD);
3297 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3298 return I->second;
3299}