blob: 69a70a1760dab6e45f929f94a93ce9d9b059610c [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
66 /// Offset - the base offset of the overrider in the layout class.
67 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.
771class VTableBuilder {
772public:
773 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
774 /// primary bases.
775 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
776 PrimaryBasesSetVectorTy;
777
778 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
779 VBaseOffsetOffsetsMapTy;
780
781 typedef llvm::DenseMap<BaseSubobject, uint64_t>
782 AddressPointsMapTy;
783
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000784 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
785
Peter Collingbourne24018462011-09-26 01:57:12 +0000786private:
787 /// VTables - Global vtable information.
788 VTableContext &VTables;
789
790 /// MostDerivedClass - The most derived class for which we're building this
791 /// vtable.
792 const CXXRecordDecl *MostDerivedClass;
793
794 /// MostDerivedClassOffset - If we're building a construction vtable, this
795 /// holds the offset from the layout class to the most derived class.
796 const CharUnits MostDerivedClassOffset;
797
798 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
799 /// base. (This only makes sense when building a construction vtable).
800 bool MostDerivedClassIsVirtual;
801
802 /// LayoutClass - The class we're using for layout information. Will be
803 /// different than the most derived class if we're building a construction
804 /// vtable.
805 const CXXRecordDecl *LayoutClass;
806
807 /// Context - The ASTContext which we will use for layout information.
808 ASTContext &Context;
809
810 /// FinalOverriders - The final overriders of the most derived class.
811 const FinalOverriders Overriders;
812
813 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
814 /// bases in this vtable.
815 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
816
817 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
818 /// the most derived class.
819 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
820
821 /// Components - The components of the vtable being built.
822 SmallVector<VTableComponent, 64> Components;
823
824 /// AddressPoints - Address points for the vtable being built.
825 AddressPointsMapTy AddressPoints;
826
827 /// MethodInfo - Contains information about a method in a vtable.
828 /// (Used for computing 'this' pointer adjustment thunks.
829 struct MethodInfo {
830 /// BaseOffset - The base offset of this method.
831 const CharUnits BaseOffset;
832
833 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
834 /// method.
835 const CharUnits BaseOffsetInLayoutClass;
836
837 /// VTableIndex - The index in the vtable that this method has.
838 /// (For destructors, this is the index of the complete destructor).
839 const uint64_t VTableIndex;
840
841 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
842 uint64_t VTableIndex)
843 : BaseOffset(BaseOffset),
844 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
845 VTableIndex(VTableIndex) { }
846
847 MethodInfo()
848 : BaseOffset(CharUnits::Zero()),
849 BaseOffsetInLayoutClass(CharUnits::Zero()),
850 VTableIndex(0) { }
851 };
852
853 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
854
855 /// MethodInfoMap - The information for all methods in the vtable we're
856 /// currently building.
857 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000858
859 /// MethodVTableIndices - Contains the index (relative to the vtable address
860 /// point) where the function pointer for a virtual function is stored.
861 MethodVTableIndicesTy MethodVTableIndices;
862
Peter Collingbourne24018462011-09-26 01:57:12 +0000863 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
864
865 /// VTableThunks - The thunks by vtable index in the vtable currently being
866 /// built.
867 VTableThunksMapTy VTableThunks;
868
869 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
870 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
871
872 /// Thunks - A map that contains all the thunks needed for all methods in the
873 /// most derived class for which the vtable is currently being built.
874 ThunksMapTy Thunks;
875
876 /// AddThunk - Add a thunk for the given method.
877 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
878
879 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
880 /// part of the vtable we're currently building.
881 void ComputeThisAdjustments();
882
883 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
884
885 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
886 /// some other base.
887 VisitedVirtualBasesSetTy PrimaryVirtualBases;
888
889 /// ComputeReturnAdjustment - Compute the return adjustment given a return
890 /// adjustment base offset.
891 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
892
893 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
894 /// the 'this' pointer from the base subobject to the derived subobject.
895 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
896 BaseSubobject Derived) const;
897
898 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
899 /// given virtual member function, its offset in the layout class and its
900 /// final overrider.
901 ThisAdjustment
902 ComputeThisAdjustment(const CXXMethodDecl *MD,
903 CharUnits BaseOffsetInLayoutClass,
904 FinalOverriders::OverriderInfo Overrider);
905
906 /// AddMethod - Add a single virtual member function to the vtable
907 /// components vector.
908 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
909
910 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
911 /// part of the vtable.
912 ///
913 /// Itanium C++ ABI 2.5.2:
914 ///
915 /// struct A { virtual void f(); };
916 /// struct B : virtual public A { int i; };
917 /// struct C : virtual public A { int j; };
918 /// struct D : public B, public C {};
919 ///
920 /// When B and C are declared, A is a primary base in each case, so although
921 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
922 /// adjustment is required and no thunk is generated. However, inside D
923 /// objects, A is no longer a primary base of C, so if we allowed calls to
924 /// C::f() to use the copy of A's vtable in the C subobject, we would need
925 /// to adjust this from C* to B::A*, which would require a third-party
926 /// thunk. Since we require that a call to C::f() first convert to A*,
927 /// C-in-D's copy of A's vtable is never referenced, so this is not
928 /// necessary.
929 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
930 CharUnits BaseOffsetInLayoutClass,
931 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
932 CharUnits FirstBaseOffsetInLayoutClass) const;
933
934
935 /// AddMethods - Add the methods of this base subobject and all its
936 /// primary bases to the vtable components vector.
937 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
938 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
939 CharUnits FirstBaseOffsetInLayoutClass,
940 PrimaryBasesSetVectorTy &PrimaryBases);
941
942 // LayoutVTable - Layout the vtable for the given base class, including its
943 // secondary vtables and any vtables for virtual bases.
944 void LayoutVTable();
945
946 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
947 /// given base subobject, as well as all its secondary vtables.
948 ///
949 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
950 /// or a direct or indirect base of a virtual base.
951 ///
952 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
953 /// in the layout class.
954 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
955 bool BaseIsMorallyVirtual,
956 bool BaseIsVirtualInLayoutClass,
957 CharUnits OffsetInLayoutClass);
958
959 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
960 /// subobject.
961 ///
962 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
963 /// or a direct or indirect base of a virtual base.
964 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
965 CharUnits OffsetInLayoutClass);
966
967 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
968 /// class hierarchy.
969 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
970 CharUnits OffsetInLayoutClass,
971 VisitedVirtualBasesSetTy &VBases);
972
973 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
974 /// given base (excluding any primary bases).
975 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
976 VisitedVirtualBasesSetTy &VBases);
977
978 /// isBuildingConstructionVTable - Return whether this vtable builder is
979 /// building a construction vtable.
980 bool isBuildingConstructorVTable() const {
981 return MostDerivedClass != LayoutClass;
982 }
983
984public:
985 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
986 CharUnits MostDerivedClassOffset,
987 bool MostDerivedClassIsVirtual, const
988 CXXRecordDecl *LayoutClass)
989 : VTables(VTables), MostDerivedClass(MostDerivedClass),
990 MostDerivedClassOffset(MostDerivedClassOffset),
991 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
992 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
993 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
994
995 LayoutVTable();
996
David Blaikie4e4d0842012-03-11 07:00:24 +0000997 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +0000998 dumpLayout(llvm::errs());
999 }
1000
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001001 bool isMicrosoftABI() const {
1002 return VTables.isMicrosoftABI();
1003 }
1004
Peter Collingbourne24018462011-09-26 01:57:12 +00001005 uint64_t getNumThunks() const {
1006 return Thunks.size();
1007 }
1008
1009 ThunksMapTy::const_iterator thunks_begin() const {
1010 return Thunks.begin();
1011 }
1012
1013 ThunksMapTy::const_iterator thunks_end() const {
1014 return Thunks.end();
1015 }
1016
1017 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1018 return VBaseOffsetOffsets;
1019 }
1020
1021 const AddressPointsMapTy &getAddressPoints() const {
1022 return AddressPoints;
1023 }
1024
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001025 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1026 return MethodVTableIndices.begin();
1027 }
1028
1029 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1030 return MethodVTableIndices.end();
1031 }
1032
Peter Collingbourne24018462011-09-26 01:57:12 +00001033 /// getNumVTableComponents - Return the number of components in the vtable
1034 /// currently built.
1035 uint64_t getNumVTableComponents() const {
1036 return Components.size();
1037 }
1038
1039 const VTableComponent *vtable_component_begin() const {
1040 return Components.begin();
1041 }
1042
1043 const VTableComponent *vtable_component_end() const {
1044 return Components.end();
1045 }
1046
1047 AddressPointsMapTy::const_iterator address_points_begin() const {
1048 return AddressPoints.begin();
1049 }
1050
1051 AddressPointsMapTy::const_iterator address_points_end() const {
1052 return AddressPoints.end();
1053 }
1054
1055 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1056 return VTableThunks.begin();
1057 }
1058
1059 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1060 return VTableThunks.end();
1061 }
1062
1063 /// dumpLayout - Dump the vtable layout.
1064 void dumpLayout(raw_ostream&);
1065};
1066
1067void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1068 assert(!isBuildingConstructorVTable() &&
1069 "Can't add thunks for construction vtable");
1070
Craig Topper6b9240e2013-07-05 19:34:19 +00001071 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1072
Peter Collingbourne24018462011-09-26 01:57:12 +00001073 // Check if we have this thunk already.
1074 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1075 ThunksVector.end())
1076 return;
1077
1078 ThunksVector.push_back(Thunk);
1079}
1080
1081typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1082
1083/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1084/// the overridden methods that the function decl overrides.
1085static void
1086ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1087 OverriddenMethodsSetTy& OverriddenMethods) {
1088 assert(MD->isVirtual() && "Method is not virtual!");
1089
1090 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1091 E = MD->end_overridden_methods(); I != E; ++I) {
1092 const CXXMethodDecl *OverriddenMD = *I;
1093
1094 OverriddenMethods.insert(OverriddenMD);
1095
1096 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1097 }
1098}
1099
1100void VTableBuilder::ComputeThisAdjustments() {
1101 // Now go through the method info map and see if any of the methods need
1102 // 'this' pointer adjustments.
1103 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1104 E = MethodInfoMap.end(); I != E; ++I) {
1105 const CXXMethodDecl *MD = I->first;
1106 const MethodInfo &MethodInfo = I->second;
1107
1108 // Ignore adjustments for unused function pointers.
1109 uint64_t VTableIndex = MethodInfo.VTableIndex;
1110 if (Components[VTableIndex].getKind() ==
1111 VTableComponent::CK_UnusedFunctionPointer)
1112 continue;
1113
1114 // Get the final overrider for this method.
1115 FinalOverriders::OverriderInfo Overrider =
1116 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1117
1118 // Check if we need an adjustment at all.
1119 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1120 // When a return thunk is needed by a derived class that overrides a
1121 // virtual base, gcc uses a virtual 'this' adjustment as well.
1122 // While the thunk itself might be needed by vtables in subclasses or
1123 // in construction vtables, there doesn't seem to be a reason for using
1124 // the thunk in this vtable. Still, we do so to match gcc.
1125 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1126 continue;
1127 }
1128
1129 ThisAdjustment ThisAdjustment =
1130 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1131
1132 if (ThisAdjustment.isEmpty())
1133 continue;
1134
1135 // Add it.
1136 VTableThunks[VTableIndex].This = ThisAdjustment;
1137
1138 if (isa<CXXDestructorDecl>(MD)) {
1139 // Add an adjustment for the deleting destructor as well.
1140 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1141 }
1142 }
1143
1144 /// Clear the method info map.
1145 MethodInfoMap.clear();
1146
1147 if (isBuildingConstructorVTable()) {
1148 // We don't need to store thunk information for construction vtables.
1149 return;
1150 }
1151
1152 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1153 E = VTableThunks.end(); I != E; ++I) {
1154 const VTableComponent &Component = Components[I->first];
1155 const ThunkInfo &Thunk = I->second;
1156 const CXXMethodDecl *MD;
1157
1158 switch (Component.getKind()) {
1159 default:
1160 llvm_unreachable("Unexpected vtable component kind!");
1161 case VTableComponent::CK_FunctionPointer:
1162 MD = Component.getFunctionDecl();
1163 break;
1164 case VTableComponent::CK_CompleteDtorPointer:
1165 MD = Component.getDestructorDecl();
1166 break;
1167 case VTableComponent::CK_DeletingDtorPointer:
1168 // We've already added the thunk when we saw the complete dtor pointer.
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001169 // FIXME: check how this works in the Microsoft ABI
1170 // while working on the multiple inheritance patch.
Peter Collingbourne24018462011-09-26 01:57:12 +00001171 continue;
1172 }
1173
1174 if (MD->getParent() == MostDerivedClass)
1175 AddThunk(MD, Thunk);
1176 }
1177}
1178
1179ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1180 ReturnAdjustment Adjustment;
1181
1182 if (!Offset.isEmpty()) {
1183 if (Offset.VirtualBase) {
1184 // Get the virtual base offset offset.
1185 if (Offset.DerivedClass == MostDerivedClass) {
1186 // We can get the offset offset directly from our map.
1187 Adjustment.VBaseOffsetOffset =
1188 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1189 } else {
1190 Adjustment.VBaseOffsetOffset =
1191 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1192 Offset.VirtualBase).getQuantity();
1193 }
1194 }
1195
1196 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1197 }
1198
1199 return Adjustment;
1200}
1201
1202BaseOffset
1203VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1204 BaseSubobject Derived) const {
1205 const CXXRecordDecl *BaseRD = Base.getBase();
1206 const CXXRecordDecl *DerivedRD = Derived.getBase();
1207
1208 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1209 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1210
Benjamin Kramer922cec22013-02-03 18:55:34 +00001211 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +00001212 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +00001213
1214 // We have to go through all the paths, and see which one leads us to the
1215 // right base subobject.
1216 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1217 I != E; ++I) {
1218 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1219
1220 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1221
1222 if (Offset.VirtualBase) {
1223 // If we have a virtual base class, the non-virtual offset is relative
1224 // to the virtual base class offset.
1225 const ASTRecordLayout &LayoutClassLayout =
1226 Context.getASTRecordLayout(LayoutClass);
1227
1228 /// Get the virtual base offset, relative to the most derived class
1229 /// layout.
1230 OffsetToBaseSubobject +=
1231 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1232 } else {
1233 // Otherwise, the non-virtual offset is relative to the derived class
1234 // offset.
1235 OffsetToBaseSubobject += Derived.getBaseOffset();
1236 }
1237
1238 // Check if this path gives us the right base subobject.
1239 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1240 // Since we're going from the base class _to_ the derived class, we'll
1241 // invert the non-virtual offset here.
1242 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1243 return Offset;
1244 }
1245 }
1246
1247 return BaseOffset();
1248}
1249
1250ThisAdjustment
1251VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1252 CharUnits BaseOffsetInLayoutClass,
1253 FinalOverriders::OverriderInfo Overrider) {
1254 // Ignore adjustments for pure virtual member functions.
1255 if (Overrider.Method->isPure())
1256 return ThisAdjustment();
1257
1258 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1259 BaseOffsetInLayoutClass);
1260
1261 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1262 Overrider.Offset);
1263
1264 // Compute the adjustment offset.
1265 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1266 OverriderBaseSubobject);
1267 if (Offset.isEmpty())
1268 return ThisAdjustment();
1269
1270 ThisAdjustment Adjustment;
1271
1272 if (Offset.VirtualBase) {
1273 // Get the vcall offset map for this virtual base.
1274 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1275
1276 if (VCallOffsets.empty()) {
1277 // We don't have vcall offsets for this virtual base, go ahead and
1278 // build them.
1279 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1280 /*FinalOverriders=*/0,
1281 BaseSubobject(Offset.VirtualBase,
1282 CharUnits::Zero()),
1283 /*BaseIsVirtual=*/true,
1284 /*OffsetInLayoutClass=*/
1285 CharUnits::Zero());
1286
1287 VCallOffsets = Builder.getVCallOffsets();
1288 }
1289
1290 Adjustment.VCallOffsetOffset =
1291 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1292 }
1293
1294 // Set the non-virtual part of the adjustment.
1295 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1296
1297 return Adjustment;
1298}
1299
1300void
1301VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1302 ReturnAdjustment ReturnAdjustment) {
1303 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1304 assert(ReturnAdjustment.isEmpty() &&
1305 "Destructor can't have return adjustment!");
1306
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001307 // FIXME: Should probably add a layer of abstraction for vtable generation.
1308 if (!isMicrosoftABI()) {
1309 // Add both the complete destructor and the deleting destructor.
1310 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1311 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1312 } else {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001313 // Add the scalar deleting destructor.
1314 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001315 }
Peter Collingbourne24018462011-09-26 01:57:12 +00001316 } else {
1317 // Add the return adjustment if necessary.
1318 if (!ReturnAdjustment.isEmpty())
1319 VTableThunks[Components.size()].Return = ReturnAdjustment;
1320
1321 // Add the function.
1322 Components.push_back(VTableComponent::MakeFunction(MD));
1323 }
1324}
1325
1326/// OverridesIndirectMethodInBase - Return whether the given member function
1327/// overrides any methods in the set of given bases.
1328/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1329/// For example, if we have:
1330///
1331/// struct A { virtual void f(); }
1332/// struct B : A { virtual void f(); }
1333/// struct C : B { virtual void f(); }
1334///
1335/// OverridesIndirectMethodInBase will return true if given C::f as the method
1336/// and { A } as the set of bases.
1337static bool
1338OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1339 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1340 if (Bases.count(MD->getParent()))
1341 return true;
1342
1343 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1344 E = MD->end_overridden_methods(); I != E; ++I) {
1345 const CXXMethodDecl *OverriddenMD = *I;
1346
1347 // Check "indirect overriders".
1348 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1349 return true;
1350 }
1351
1352 return false;
1353}
1354
1355bool
1356VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1357 CharUnits BaseOffsetInLayoutClass,
1358 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1359 CharUnits FirstBaseOffsetInLayoutClass) const {
1360 // If the base and the first base in the primary base chain have the same
1361 // offsets, then this overrider will be used.
1362 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1363 return true;
1364
1365 // We know now that Base (or a direct or indirect base of it) is a primary
1366 // base in part of the class hierarchy, but not a primary base in the most
1367 // derived class.
1368
1369 // If the overrider is the first base in the primary base chain, we know
1370 // that the overrider will be used.
1371 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1372 return true;
1373
1374 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1375
1376 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1377 PrimaryBases.insert(RD);
1378
1379 // Now traverse the base chain, starting with the first base, until we find
1380 // the base that is no longer a primary base.
1381 while (true) {
1382 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1383 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1384
1385 if (!PrimaryBase)
1386 break;
1387
1388 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001389 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001390 "Primary base should always be at offset 0!");
1391
1392 const ASTRecordLayout &LayoutClassLayout =
1393 Context.getASTRecordLayout(LayoutClass);
1394
1395 // Now check if this is the primary base that is not a primary base in the
1396 // most derived class.
1397 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1398 FirstBaseOffsetInLayoutClass) {
1399 // We found it, stop walking the chain.
1400 break;
1401 }
1402 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001403 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001404 "Primary base should always be at offset 0!");
1405 }
1406
1407 if (!PrimaryBases.insert(PrimaryBase))
1408 llvm_unreachable("Found a duplicate primary base!");
1409
1410 RD = PrimaryBase;
1411 }
1412
1413 // If the final overrider is an override of one of the primary bases,
1414 // then we know that it will be used.
1415 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1416}
1417
1418/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1419/// from the nearest base. Returns null if no method was found.
1420static const CXXMethodDecl *
1421FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1422 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1423 OverriddenMethodsSetTy OverriddenMethods;
1424 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1425
1426 for (int I = Bases.size(), E = 0; I != E; --I) {
1427 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1428
1429 // Now check the overriden methods.
1430 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1431 E = OverriddenMethods.end(); I != E; ++I) {
1432 const CXXMethodDecl *OverriddenMD = *I;
1433
1434 // We found our overridden method.
1435 if (OverriddenMD->getParent() == PrimaryBase)
1436 return OverriddenMD;
1437 }
1438 }
1439
1440 return 0;
1441}
1442
1443void
1444VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1445 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1446 CharUnits FirstBaseOffsetInLayoutClass,
1447 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001448 // Itanium C++ ABI 2.5.2:
1449 // The order of the virtual function pointers in a virtual table is the
1450 // order of declaration of the corresponding member functions in the class.
1451 //
1452 // There is an entry for any virtual function declared in a class,
1453 // whether it is a new function or overrides a base class function,
1454 // unless it overrides a function from the primary base, and conversion
1455 // between their return types does not require an adjustment.
1456
Peter Collingbourne24018462011-09-26 01:57:12 +00001457 const CXXRecordDecl *RD = Base.getBase();
1458 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1459
1460 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1461 CharUnits PrimaryBaseOffset;
1462 CharUnits PrimaryBaseOffsetInLayoutClass;
1463 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001464 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001465 "Primary vbase should have a zero offset!");
1466
1467 const ASTRecordLayout &MostDerivedClassLayout =
1468 Context.getASTRecordLayout(MostDerivedClass);
1469
1470 PrimaryBaseOffset =
1471 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1472
1473 const ASTRecordLayout &LayoutClassLayout =
1474 Context.getASTRecordLayout(LayoutClass);
1475
1476 PrimaryBaseOffsetInLayoutClass =
1477 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1478 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001479 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001480 "Primary base should have a zero offset!");
1481
1482 PrimaryBaseOffset = Base.getBaseOffset();
1483 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1484 }
1485
1486 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1487 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1488 FirstBaseOffsetInLayoutClass, PrimaryBases);
1489
1490 if (!PrimaryBases.insert(PrimaryBase))
1491 llvm_unreachable("Found a duplicate primary base!");
1492 }
1493
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001494 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1495
1496 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1497 NewVirtualFunctionsTy NewVirtualFunctions;
1498
Peter Collingbourne24018462011-09-26 01:57:12 +00001499 // Now go through all virtual member functions and add them.
1500 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1501 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001502 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001503
1504 if (!MD->isVirtual())
1505 continue;
1506
1507 // Get the final overrider.
1508 FinalOverriders::OverriderInfo Overrider =
1509 Overriders.getOverrider(MD, Base.getBaseOffset());
1510
1511 // Check if this virtual member function overrides a method in a primary
1512 // base. If this is the case, and the return type doesn't require adjustment
1513 // then we can just use the member function from the primary base.
1514 if (const CXXMethodDecl *OverriddenMD =
1515 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1516 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1517 OverriddenMD).isEmpty()) {
1518 // Replace the method info of the overridden method with our own
1519 // method.
1520 assert(MethodInfoMap.count(OverriddenMD) &&
1521 "Did not find the overridden method!");
1522 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1523
1524 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1525 OverriddenMethodInfo.VTableIndex);
1526
1527 assert(!MethodInfoMap.count(MD) &&
1528 "Should not have method info for this method yet!");
1529
1530 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1531 MethodInfoMap.erase(OverriddenMD);
1532
1533 // If the overridden method exists in a virtual base class or a direct
1534 // or indirect base class of a virtual base class, we need to emit a
1535 // thunk if we ever have a class hierarchy where the base class is not
1536 // a primary base in the complete object.
1537 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1538 // Compute the this adjustment.
1539 ThisAdjustment ThisAdjustment =
1540 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1541 Overrider);
1542
1543 if (ThisAdjustment.VCallOffsetOffset &&
1544 Overrider.Method->getParent() == MostDerivedClass) {
1545
1546 // There's no return adjustment from OverriddenMD and MD,
1547 // but that doesn't mean there isn't one between MD and
1548 // the final overrider.
1549 BaseOffset ReturnAdjustmentOffset =
1550 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1551 ReturnAdjustment ReturnAdjustment =
1552 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1553
1554 // This is a virtual thunk for the most derived class, add it.
1555 AddThunk(Overrider.Method,
1556 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1557 }
1558 }
1559
1560 continue;
1561 }
1562 }
1563
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001564 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1565 if (MD->isImplicit()) {
1566 // Itanium C++ ABI 2.5.2:
1567 // If a class has an implicitly-defined virtual destructor,
1568 // its entries come after the declared virtual function pointers.
1569
1570 assert(!ImplicitVirtualDtor &&
1571 "Did already see an implicit virtual dtor!");
1572 ImplicitVirtualDtor = DD;
1573 continue;
1574 }
1575 }
1576
1577 NewVirtualFunctions.push_back(MD);
1578 }
1579
1580 if (ImplicitVirtualDtor)
1581 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1582
1583 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1584 E = NewVirtualFunctions.end(); I != E; ++I) {
1585 const CXXMethodDecl *MD = *I;
1586
1587 // Get the final overrider.
1588 FinalOverriders::OverriderInfo Overrider =
1589 Overriders.getOverrider(MD, Base.getBaseOffset());
1590
Peter Collingbourne24018462011-09-26 01:57:12 +00001591 // Insert the method info for this method.
1592 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1593 Components.size());
1594
1595 assert(!MethodInfoMap.count(MD) &&
1596 "Should not have method info for this method yet!");
1597 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1598
1599 // Check if this overrider is going to be used.
1600 const CXXMethodDecl *OverriderMD = Overrider.Method;
1601 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1602 FirstBaseInPrimaryBaseChain,
1603 FirstBaseOffsetInLayoutClass)) {
1604 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1605 continue;
1606 }
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001607
Peter Collingbourne24018462011-09-26 01:57:12 +00001608 // Check if this overrider needs a return adjustment.
1609 // We don't want to do this for pure virtual member functions.
1610 BaseOffset ReturnAdjustmentOffset;
1611 if (!OverriderMD->isPure()) {
1612 ReturnAdjustmentOffset =
1613 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1614 }
1615
1616 ReturnAdjustment ReturnAdjustment =
1617 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1618
1619 AddMethod(Overrider.Method, ReturnAdjustment);
1620 }
1621}
1622
1623void VTableBuilder::LayoutVTable() {
1624 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1625 CharUnits::Zero()),
1626 /*BaseIsMorallyVirtual=*/false,
1627 MostDerivedClassIsVirtual,
1628 MostDerivedClassOffset);
1629
1630 VisitedVirtualBasesSetTy VBases;
1631
1632 // Determine the primary virtual bases.
1633 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1634 VBases);
1635 VBases.clear();
1636
1637 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1638
1639 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001640 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001641 if (IsAppleKext)
1642 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1643}
1644
1645void
1646VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1647 bool BaseIsMorallyVirtual,
1648 bool BaseIsVirtualInLayoutClass,
1649 CharUnits OffsetInLayoutClass) {
1650 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1651
1652 // Add vcall and vbase offsets for this vtable.
1653 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1654 Base, BaseIsVirtualInLayoutClass,
1655 OffsetInLayoutClass);
1656 Components.append(Builder.components_begin(), Builder.components_end());
1657
1658 // Check if we need to add these vcall offsets.
1659 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1660 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1661
1662 if (VCallOffsets.empty())
1663 VCallOffsets = Builder.getVCallOffsets();
1664 }
1665
1666 // If we're laying out the most derived class we want to keep track of the
1667 // virtual base class offset offsets.
1668 if (Base.getBase() == MostDerivedClass)
1669 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1670
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001671 // FIXME: Should probably add a layer of abstraction for vtable generation.
1672 if (!isMicrosoftABI()) {
1673 // Add the offset to top.
1674 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1675 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1676
1677 // Next, add the RTTI.
1678 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1679 } else {
1680 // FIXME: unclear what to do with RTTI in MS ABI as emitting it anywhere
1681 // breaks the vftable layout. Just skip RTTI for now, can't mangle anyway.
1682 }
1683
Peter Collingbourne24018462011-09-26 01:57:12 +00001684 uint64_t AddressPoint = Components.size();
1685
1686 // Now go through all virtual member functions and add them.
1687 PrimaryBasesSetVectorTy PrimaryBases;
1688 AddMethods(Base, OffsetInLayoutClass,
1689 Base.getBase(), OffsetInLayoutClass,
1690 PrimaryBases);
1691
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001692 const CXXRecordDecl *RD = Base.getBase();
1693 if (RD == MostDerivedClass) {
1694 assert(MethodVTableIndices.empty());
1695 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1696 E = MethodInfoMap.end(); I != E; ++I) {
1697 const CXXMethodDecl *MD = I->first;
1698 const MethodInfo &MI = I->second;
1699 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1700 // FIXME: Should probably add a layer of abstraction for vtable generation.
1701 if (!isMicrosoftABI()) {
1702 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1703 = MI.VTableIndex - AddressPoint;
1704 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1705 = MI.VTableIndex + 1 - AddressPoint;
1706 } else {
1707 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1708 = MI.VTableIndex - AddressPoint;
1709 }
1710 } else {
1711 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1712 }
1713 }
1714 }
1715
Peter Collingbourne24018462011-09-26 01:57:12 +00001716 // Compute 'this' pointer adjustments.
1717 ComputeThisAdjustments();
1718
1719 // Add all address points.
Peter Collingbourne24018462011-09-26 01:57:12 +00001720 while (true) {
1721 AddressPoints.insert(std::make_pair(
1722 BaseSubobject(RD, OffsetInLayoutClass),
1723 AddressPoint));
1724
1725 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1726 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1727
1728 if (!PrimaryBase)
1729 break;
1730
1731 if (Layout.isPrimaryBaseVirtual()) {
1732 // Check if this virtual primary base is a primary base in the layout
1733 // class. If it's not, we don't want to add it.
1734 const ASTRecordLayout &LayoutClassLayout =
1735 Context.getASTRecordLayout(LayoutClass);
1736
1737 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1738 OffsetInLayoutClass) {
1739 // We don't want to add this class (or any of its primary bases).
1740 break;
1741 }
1742 }
1743
1744 RD = PrimaryBase;
1745 }
1746
1747 // Layout secondary vtables.
1748 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1749}
1750
1751void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1752 bool BaseIsMorallyVirtual,
1753 CharUnits OffsetInLayoutClass) {
1754 // Itanium C++ ABI 2.5.2:
1755 // Following the primary virtual table of a derived class are secondary
1756 // virtual tables for each of its proper base classes, except any primary
1757 // base(s) with which it shares its primary virtual table.
1758
1759 const CXXRecordDecl *RD = Base.getBase();
1760 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1761 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1762
1763 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1764 E = RD->bases_end(); I != E; ++I) {
1765 // Ignore virtual bases, we'll emit them later.
1766 if (I->isVirtual())
1767 continue;
1768
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001769 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001770
1771 // Ignore bases that don't have a vtable.
1772 if (!BaseDecl->isDynamicClass())
1773 continue;
1774
1775 if (isBuildingConstructorVTable()) {
1776 // Itanium C++ ABI 2.6.4:
1777 // Some of the base class subobjects may not need construction virtual
1778 // tables, which will therefore not be present in the construction
1779 // virtual table group, even though the subobject virtual tables are
1780 // present in the main virtual table group for the complete object.
1781 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1782 continue;
1783 }
1784
1785 // Get the base offset of this base.
1786 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1787 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1788
1789 CharUnits BaseOffsetInLayoutClass =
1790 OffsetInLayoutClass + RelativeBaseOffset;
1791
1792 // Don't emit a secondary vtable for a primary base. We might however want
1793 // to emit secondary vtables for other bases of this base.
1794 if (BaseDecl == PrimaryBase) {
1795 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1796 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1797 continue;
1798 }
1799
1800 // Layout the primary vtable (and any secondary vtables) for this base.
1801 LayoutPrimaryAndSecondaryVTables(
1802 BaseSubobject(BaseDecl, BaseOffset),
1803 BaseIsMorallyVirtual,
1804 /*BaseIsVirtualInLayoutClass=*/false,
1805 BaseOffsetInLayoutClass);
1806 }
1807}
1808
1809void
1810VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1811 CharUnits OffsetInLayoutClass,
1812 VisitedVirtualBasesSetTy &VBases) {
1813 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1814
1815 // Check if this base has a primary base.
1816 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1817
1818 // Check if it's virtual.
1819 if (Layout.isPrimaryBaseVirtual()) {
1820 bool IsPrimaryVirtualBase = true;
1821
1822 if (isBuildingConstructorVTable()) {
1823 // Check if the base is actually a primary base in the class we use for
1824 // layout.
1825 const ASTRecordLayout &LayoutClassLayout =
1826 Context.getASTRecordLayout(LayoutClass);
1827
1828 CharUnits PrimaryBaseOffsetInLayoutClass =
1829 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1830
1831 // We know that the base is not a primary base in the layout class if
1832 // the base offsets are different.
1833 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1834 IsPrimaryVirtualBase = false;
1835 }
1836
1837 if (IsPrimaryVirtualBase)
1838 PrimaryVirtualBases.insert(PrimaryBase);
1839 }
1840 }
1841
1842 // Traverse bases, looking for more primary virtual bases.
1843 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1844 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001845 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001846
1847 CharUnits BaseOffsetInLayoutClass;
1848
1849 if (I->isVirtual()) {
1850 if (!VBases.insert(BaseDecl))
1851 continue;
1852
1853 const ASTRecordLayout &LayoutClassLayout =
1854 Context.getASTRecordLayout(LayoutClass);
1855
1856 BaseOffsetInLayoutClass =
1857 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1858 } else {
1859 BaseOffsetInLayoutClass =
1860 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1861 }
1862
1863 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1864 }
1865}
1866
1867void
1868VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1869 VisitedVirtualBasesSetTy &VBases) {
1870 // Itanium C++ ABI 2.5.2:
1871 // Then come the virtual base virtual tables, also in inheritance graph
1872 // order, and again excluding primary bases (which share virtual tables with
1873 // the classes for which they are primary).
1874 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1875 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001876 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001877
1878 // Check if this base needs a vtable. (If it's virtual, not a primary base
1879 // of some other class, and we haven't visited it before).
1880 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1881 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1882 const ASTRecordLayout &MostDerivedClassLayout =
1883 Context.getASTRecordLayout(MostDerivedClass);
1884 CharUnits BaseOffset =
1885 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1886
1887 const ASTRecordLayout &LayoutClassLayout =
1888 Context.getASTRecordLayout(LayoutClass);
1889 CharUnits BaseOffsetInLayoutClass =
1890 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1891
1892 LayoutPrimaryAndSecondaryVTables(
1893 BaseSubobject(BaseDecl, BaseOffset),
1894 /*BaseIsMorallyVirtual=*/true,
1895 /*BaseIsVirtualInLayoutClass=*/true,
1896 BaseOffsetInLayoutClass);
1897 }
1898
1899 // We only need to check the base for virtual base vtables if it actually
1900 // has virtual bases.
1901 if (BaseDecl->getNumVBases())
1902 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1903 }
1904}
1905
1906/// dumpLayout - Dump the vtable layout.
1907void VTableBuilder::dumpLayout(raw_ostream& Out) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00001908 // FIXME: write more tests that actually use the dumpLayout output to prevent
1909 // VTableBuilder regressions.
Peter Collingbourne24018462011-09-26 01:57:12 +00001910
1911 if (isBuildingConstructorVTable()) {
1912 Out << "Construction vtable for ('";
1913 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1914 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1915 Out << LayoutClass->getQualifiedNameAsString();
1916 } else {
1917 Out << "Vtable for '";
1918 Out << MostDerivedClass->getQualifiedNameAsString();
1919 }
1920 Out << "' (" << Components.size() << " entries).\n";
1921
1922 // Iterate through the address points and insert them into a new map where
1923 // they are keyed by the index and not the base object.
1924 // Since an address point can be shared by multiple subobjects, we use an
1925 // STL multimap.
1926 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1927 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1928 E = AddressPoints.end(); I != E; ++I) {
1929 const BaseSubobject& Base = I->first;
1930 uint64_t Index = I->second;
1931
1932 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1933 }
1934
1935 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1936 uint64_t Index = I;
1937
1938 Out << llvm::format("%4d | ", I);
1939
1940 const VTableComponent &Component = Components[I];
1941
1942 // Dump the component.
1943 switch (Component.getKind()) {
1944
1945 case VTableComponent::CK_VCallOffset:
1946 Out << "vcall_offset ("
1947 << Component.getVCallOffset().getQuantity()
1948 << ")";
1949 break;
1950
1951 case VTableComponent::CK_VBaseOffset:
1952 Out << "vbase_offset ("
1953 << Component.getVBaseOffset().getQuantity()
1954 << ")";
1955 break;
1956
1957 case VTableComponent::CK_OffsetToTop:
1958 Out << "offset_to_top ("
1959 << Component.getOffsetToTop().getQuantity()
1960 << ")";
1961 break;
1962
1963 case VTableComponent::CK_RTTI:
1964 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1965 break;
1966
1967 case VTableComponent::CK_FunctionPointer: {
1968 const CXXMethodDecl *MD = Component.getFunctionDecl();
1969
1970 std::string Str =
1971 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1972 MD);
1973 Out << Str;
1974 if (MD->isPure())
1975 Out << " [pure]";
1976
David Blaikied954ab42012-10-16 20:25:33 +00001977 if (MD->isDeleted())
1978 Out << " [deleted]";
1979
Peter Collingbourne24018462011-09-26 01:57:12 +00001980 ThunkInfo Thunk = VTableThunks.lookup(I);
1981 if (!Thunk.isEmpty()) {
1982 // If this function pointer has a return adjustment, dump it.
1983 if (!Thunk.Return.isEmpty()) {
1984 Out << "\n [return adjustment: ";
1985 Out << Thunk.Return.NonVirtual << " non-virtual";
1986
1987 if (Thunk.Return.VBaseOffsetOffset) {
1988 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1989 Out << " vbase offset offset";
1990 }
1991
1992 Out << ']';
1993 }
1994
1995 // If this function pointer has a 'this' pointer adjustment, dump it.
1996 if (!Thunk.This.isEmpty()) {
1997 Out << "\n [this adjustment: ";
1998 Out << Thunk.This.NonVirtual << " non-virtual";
1999
2000 if (Thunk.This.VCallOffsetOffset) {
2001 Out << ", " << Thunk.This.VCallOffsetOffset;
2002 Out << " vcall offset offset";
2003 }
2004
2005 Out << ']';
2006 }
2007 }
2008
2009 break;
2010 }
2011
2012 case VTableComponent::CK_CompleteDtorPointer:
2013 case VTableComponent::CK_DeletingDtorPointer: {
2014 bool IsComplete =
2015 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2016
2017 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2018
2019 Out << DD->getQualifiedNameAsString();
2020 if (IsComplete)
2021 Out << "() [complete]";
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00002022 else if (isMicrosoftABI())
2023 Out << "() [scalar deleting]";
Peter Collingbourne24018462011-09-26 01:57:12 +00002024 else
2025 Out << "() [deleting]";
2026
2027 if (DD->isPure())
2028 Out << " [pure]";
2029
2030 ThunkInfo Thunk = VTableThunks.lookup(I);
2031 if (!Thunk.isEmpty()) {
2032 // If this destructor has a 'this' pointer adjustment, dump it.
2033 if (!Thunk.This.isEmpty()) {
2034 Out << "\n [this adjustment: ";
2035 Out << Thunk.This.NonVirtual << " non-virtual";
2036
2037 if (Thunk.This.VCallOffsetOffset) {
2038 Out << ", " << Thunk.This.VCallOffsetOffset;
2039 Out << " vcall offset offset";
2040 }
2041
2042 Out << ']';
2043 }
2044 }
2045
2046 break;
2047 }
2048
2049 case VTableComponent::CK_UnusedFunctionPointer: {
2050 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2051
2052 std::string Str =
2053 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2054 MD);
2055 Out << "[unused] " << Str;
2056 if (MD->isPure())
2057 Out << " [pure]";
2058 }
2059
2060 }
2061
2062 Out << '\n';
2063
2064 // Dump the next address point.
2065 uint64_t NextIndex = Index + 1;
2066 if (AddressPointsByIndex.count(NextIndex)) {
2067 if (AddressPointsByIndex.count(NextIndex) == 1) {
2068 const BaseSubobject &Base =
2069 AddressPointsByIndex.find(NextIndex)->second;
2070
2071 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2072 Out << ", " << Base.getBaseOffset().getQuantity();
2073 Out << ") vtable address --\n";
2074 } else {
2075 CharUnits BaseOffset =
2076 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2077
2078 // We store the class names in a set to get a stable order.
2079 std::set<std::string> ClassNames;
2080 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2081 AddressPointsByIndex.lower_bound(NextIndex), E =
2082 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2083 assert(I->second.getBaseOffset() == BaseOffset &&
2084 "Invalid base offset!");
2085 const CXXRecordDecl *RD = I->second.getBase();
2086 ClassNames.insert(RD->getQualifiedNameAsString());
2087 }
2088
2089 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2090 E = ClassNames.end(); I != E; ++I) {
2091 Out << " -- (" << *I;
2092 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2093 }
2094 }
2095 }
2096 }
2097
2098 Out << '\n';
2099
2100 if (isBuildingConstructorVTable())
2101 return;
2102
2103 if (MostDerivedClass->getNumVBases()) {
2104 // We store the virtual base class names and their offsets in a map to get
2105 // a stable order.
2106
2107 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2108 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2109 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2110 std::string ClassName = I->first->getQualifiedNameAsString();
2111 CharUnits OffsetOffset = I->second;
2112 ClassNamesAndOffsets.insert(
2113 std::make_pair(ClassName, OffsetOffset));
2114 }
2115
2116 Out << "Virtual base offset offsets for '";
2117 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2118 Out << ClassNamesAndOffsets.size();
2119 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2120
2121 for (std::map<std::string, CharUnits>::const_iterator I =
2122 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2123 I != E; ++I)
2124 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2125
2126 Out << "\n";
2127 }
2128
2129 if (!Thunks.empty()) {
2130 // We store the method names in a map to get a stable order.
2131 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2132
2133 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2134 I != E; ++I) {
2135 const CXXMethodDecl *MD = I->first;
2136 std::string MethodName =
2137 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2138 MD);
2139
2140 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2141 }
2142
2143 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2144 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2145 I != E; ++I) {
2146 const std::string &MethodName = I->first;
2147 const CXXMethodDecl *MD = I->second;
2148
2149 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2150 std::sort(ThunksVector.begin(), ThunksVector.end());
2151
2152 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2153 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2154
2155 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2156 const ThunkInfo &Thunk = ThunksVector[I];
2157
2158 Out << llvm::format("%4d | ", I);
2159
2160 // If this function pointer has a return pointer adjustment, dump it.
2161 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00002162 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbourne24018462011-09-26 01:57:12 +00002163 Out << " non-virtual";
2164 if (Thunk.Return.VBaseOffsetOffset) {
2165 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2166 Out << " vbase offset offset";
2167 }
2168
2169 if (!Thunk.This.isEmpty())
2170 Out << "\n ";
2171 }
2172
2173 // If this function pointer has a 'this' pointer adjustment, dump it.
2174 if (!Thunk.This.isEmpty()) {
2175 Out << "this adjustment: ";
2176 Out << Thunk.This.NonVirtual << " non-virtual";
2177
2178 if (Thunk.This.VCallOffsetOffset) {
2179 Out << ", " << Thunk.This.VCallOffsetOffset;
2180 Out << " vcall offset offset";
2181 }
2182 }
2183
2184 Out << '\n';
2185 }
2186
2187 Out << '\n';
2188 }
2189 }
2190
2191 // Compute the vtable indices for all the member functions.
2192 // Store them in a map keyed by the index so we'll get a sorted table.
2193 std::map<uint64_t, std::string> IndicesMap;
2194
2195 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2196 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002197 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002198
2199 // We only want virtual member functions.
2200 if (!MD->isVirtual())
2201 continue;
2202
2203 std::string MethodName =
2204 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2205 MD);
2206
2207 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002208 // FIXME: Should add a layer of abstraction for vtable generation.
2209 if (!isMicrosoftABI()) {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002210 GlobalDecl GD(DD, Dtor_Complete);
2211 assert(MethodVTableIndices.count(GD));
2212 uint64_t VTableIndex = MethodVTableIndices[GD];
2213 IndicesMap[VTableIndex] = MethodName + " [complete]";
2214 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002215 } else {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002216 GlobalDecl GD(DD, Dtor_Deleting);
2217 assert(MethodVTableIndices.count(GD));
2218 IndicesMap[MethodVTableIndices[GD]] = MethodName + " [scalar deleting]";
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002219 }
Peter Collingbourne24018462011-09-26 01:57:12 +00002220 } else {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002221 assert(MethodVTableIndices.count(MD));
2222 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbourne24018462011-09-26 01:57:12 +00002223 }
2224 }
2225
2226 // Print the vtable indices for all the member functions.
2227 if (!IndicesMap.empty()) {
2228 Out << "VTable indices for '";
2229 Out << MostDerivedClass->getQualifiedNameAsString();
2230 Out << "' (" << IndicesMap.size() << " entries).\n";
2231
2232 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2233 E = IndicesMap.end(); I != E; ++I) {
2234 uint64_t VTableIndex = I->first;
2235 const std::string &MethodName = I->second;
2236
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002237 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer79a55012012-03-10 02:06:27 +00002238 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002239 }
2240 }
2241
2242 Out << '\n';
2243}
2244
2245}
2246
2247VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2248 const VTableComponent *VTableComponents,
2249 uint64_t NumVTableThunks,
2250 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002251 const AddressPointsMapTy &AddressPoints,
2252 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002253 : NumVTableComponents(NumVTableComponents),
2254 VTableComponents(new VTableComponent[NumVTableComponents]),
2255 NumVTableThunks(NumVTableThunks),
2256 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002257 AddressPoints(AddressPoints),
2258 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002259 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002260 this->VTableComponents.get());
2261 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2262 this->VTableThunks.get());
Peter Collingbourne24018462011-09-26 01:57:12 +00002263}
2264
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002265VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002266
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002267VTableContext::VTableContext(ASTContext &Context)
Eli Friedman0a598fd2013-06-27 20:48:08 +00002268 : IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
John McCallb8b2c9d2013-01-25 22:30:49 +00002269}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002270
Peter Collingbourne24018462011-09-26 01:57:12 +00002271VTableContext::~VTableContext() {
2272 llvm::DeleteContainerSeconds(VTableLayouts);
2273}
2274
Peter Collingbourne24018462011-09-26 01:57:12 +00002275uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2276 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2277 if (I != MethodVTableIndices.end())
2278 return I->second;
2279
2280 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2281
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002282 ComputeVTableRelatedInformation(RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002283
2284 I = MethodVTableIndices.find(GD);
2285 assert(I != MethodVTableIndices.end() && "Did not find index!");
2286 return I->second;
2287}
2288
2289CharUnits
2290VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2291 const CXXRecordDecl *VBase) {
2292 ClassPairTy ClassPair(RD, VBase);
2293
2294 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2295 VirtualBaseClassOffsetOffsets.find(ClassPair);
2296 if (I != VirtualBaseClassOffsetOffsets.end())
2297 return I->second;
2298
2299 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2300 BaseSubobject(RD, CharUnits::Zero()),
2301 /*BaseIsVirtual=*/false,
2302 /*OffsetInLayoutClass=*/CharUnits::Zero());
2303
2304 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2305 Builder.getVBaseOffsetOffsets().begin(),
2306 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2307 // Insert all types.
2308 ClassPairTy ClassPair(RD, I->first);
2309
2310 VirtualBaseClassOffsetOffsets.insert(
2311 std::make_pair(ClassPair, I->second));
2312 }
2313
2314 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2315 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2316
2317 return I->second;
2318}
2319
2320static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2321 SmallVector<VTableLayout::VTableThunkTy, 1>
2322 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2323 std::sort(VTableThunks.begin(), VTableThunks.end());
2324
2325 return new VTableLayout(Builder.getNumVTableComponents(),
2326 Builder.vtable_component_begin(),
2327 VTableThunks.size(),
2328 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002329 Builder.getAddressPoints(),
2330 Builder.isMicrosoftABI());
Peter Collingbourne24018462011-09-26 01:57:12 +00002331}
2332
2333void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2334 const VTableLayout *&Entry = VTableLayouts[RD];
2335
2336 // Check if we've computed this information before.
2337 if (Entry)
2338 return;
2339
2340 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2341 /*MostDerivedClassIsVirtual=*/0, RD);
2342 Entry = CreateVTableLayout(Builder);
2343
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002344 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2345 Builder.vtable_indices_end());
2346
Peter Collingbourne24018462011-09-26 01:57:12 +00002347 // Add the known thunks.
2348 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2349
2350 // If we don't have the vbase information for this class, insert it.
2351 // getVirtualBaseOffsetOffset will compute it separately without computing
2352 // the rest of the vtable related information.
2353 if (!RD->getNumVBases())
2354 return;
2355
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00002356 const CXXRecordDecl *VBase =
2357 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00002358
2359 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2360 return;
2361
2362 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2363 Builder.getVBaseOffsetOffsets().begin(),
2364 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2365 // Insert all types.
2366 ClassPairTy ClassPair(RD, I->first);
2367
2368 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2369 }
2370}
2371
Peter Collingbourne24018462011-09-26 01:57:12 +00002372VTableLayout *VTableContext::createConstructionVTableLayout(
2373 const CXXRecordDecl *MostDerivedClass,
2374 CharUnits MostDerivedClassOffset,
2375 bool MostDerivedClassIsVirtual,
2376 const CXXRecordDecl *LayoutClass) {
2377 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2378 MostDerivedClassIsVirtual, LayoutClass);
2379 return CreateVTableLayout(Builder);
2380}