blob: 1ab2b990ea2b49d3fd7f825a7bd0233bc37b5c7c [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
37 /// involves a virtual base class, this holds its declaration.
38 const CXXRecordDecl *VirtualBase;
39
40 /// NonVirtualOffset - The offset from the derived class to the base class.
41 /// (Or the offset from the virtual base class to the base class, if the
42 /// path from the derived class to the base class involves a virtual base
43 /// class.
44 CharUnits NonVirtualOffset;
45
46 BaseOffset() : DerivedClass(0), VirtualBase(0),
47 NonVirtualOffset(CharUnits::Zero()) { }
48 BaseOffset(const CXXRecordDecl *DerivedClass,
49 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
50 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
51 NonVirtualOffset(NonVirtualOffset) { }
52
53 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
54};
55
56/// FinalOverriders - Contains the final overrider member functions for all
57/// member functions in the base subobjects of a class.
58class FinalOverriders {
59public:
60 /// OverriderInfo - Information about a final overrider.
61 struct OverriderInfo {
62 /// Method - The method decl of the overrider.
63 const CXXMethodDecl *Method;
64
65 /// Offset - the base offset of the overrider in the layout class.
66 CharUnits Offset;
67
68 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
69 };
70
71private:
72 /// MostDerivedClass - The most derived class for which the final overriders
73 /// are stored.
74 const CXXRecordDecl *MostDerivedClass;
75
76 /// MostDerivedClassOffset - If we're building final overriders for a
77 /// construction vtable, this holds the offset from the layout class to the
78 /// most derived class.
79 const CharUnits MostDerivedClassOffset;
80
81 /// LayoutClass - The class we're using for layout information. Will be
82 /// different than the most derived class if the final overriders are for a
83 /// construction vtable.
84 const CXXRecordDecl *LayoutClass;
85
86 ASTContext &Context;
87
88 /// MostDerivedClassLayout - the AST record layout of the most derived class.
89 const ASTRecordLayout &MostDerivedClassLayout;
90
91 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
92 /// in a base subobject.
93 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
94
95 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
96 OverriderInfo> OverridersMapTy;
97
98 /// OverridersMap - The final overriders for all virtual member functions of
99 /// all the base subobjects of the most derived class.
100 OverridersMapTy OverridersMap;
101
102 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
103 /// as a record decl and a subobject number) and its offsets in the most
104 /// derived class as well as the layout class.
105 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
106 CharUnits> SubobjectOffsetMapTy;
107
108 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
109
110 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
111 /// given base.
112 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
113 CharUnits OffsetInLayoutClass,
114 SubobjectOffsetMapTy &SubobjectOffsets,
115 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
116 SubobjectCountMapTy &SubobjectCounts);
117
118 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
119
120 /// dump - dump the final overriders for a base subobject, and all its direct
121 /// and indirect base subobjects.
122 void dump(raw_ostream &Out, BaseSubobject Base,
123 VisitedVirtualBasesSetTy& VisitedVirtualBases);
124
125public:
126 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
127 CharUnits MostDerivedClassOffset,
128 const CXXRecordDecl *LayoutClass);
129
130 /// getOverrider - Get the final overrider for the given method declaration in
131 /// the subobject with the given base offset.
132 OverriderInfo getOverrider(const CXXMethodDecl *MD,
133 CharUnits BaseOffset) const {
134 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
135 "Did not find overrider!");
136
137 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
138 }
139
140 /// dump - dump the final overriders.
141 void dump() {
142 VisitedVirtualBasesSetTy VisitedVirtualBases;
143 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
144 VisitedVirtualBases);
145 }
146
147};
148
149#define DUMP_OVERRIDERS 0
150
151FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
152 CharUnits MostDerivedClassOffset,
153 const CXXRecordDecl *LayoutClass)
154 : MostDerivedClass(MostDerivedClass),
155 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
156 Context(MostDerivedClass->getASTContext()),
157 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
158
159 // Compute base offsets.
160 SubobjectOffsetMapTy SubobjectOffsets;
161 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
162 SubobjectCountMapTy SubobjectCounts;
163 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
164 /*IsVirtual=*/false,
165 MostDerivedClassOffset,
166 SubobjectOffsets, SubobjectLayoutClassOffsets,
167 SubobjectCounts);
168
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000169 // Get the final overriders.
Peter Collingbourne24018462011-09-26 01:57:12 +0000170 CXXFinalOverriderMap FinalOverriders;
171 MostDerivedClass->getFinalOverriders(FinalOverriders);
172
173 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
174 E = FinalOverriders.end(); I != E; ++I) {
175 const CXXMethodDecl *MD = I->first;
176 const OverridingMethods& Methods = I->second;
177
178 for (OverridingMethods::const_iterator I = Methods.begin(),
179 E = Methods.end(); I != E; ++I) {
180 unsigned SubobjectNumber = I->first;
181 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
182 SubobjectNumber)) &&
183 "Did not find subobject offset!");
184
185 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
186 SubobjectNumber)];
187
188 assert(I->second.size() == 1 && "Final overrider is not unique!");
189 const UniqueVirtualMethod &Method = I->second.front();
190
191 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
192 assert(SubobjectLayoutClassOffsets.count(
193 std::make_pair(OverriderRD, Method.Subobject))
194 && "Did not find subobject offset!");
195 CharUnits OverriderOffset =
196 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
197 Method.Subobject)];
198
199 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
200 assert(!Overrider.Method && "Overrider should not exist yet!");
201
202 Overrider.Offset = OverriderOffset;
203 Overrider.Method = Method.Method;
204 }
205 }
206
207#if DUMP_OVERRIDERS
208 // And dump them (for now).
209 dump();
210#endif
211}
212
213static BaseOffset ComputeBaseOffset(ASTContext &Context,
214 const CXXRecordDecl *DerivedRD,
215 const CXXBasePath &Path) {
216 CharUnits NonVirtualOffset = CharUnits::Zero();
217
218 unsigned NonVirtualStart = 0;
219 const CXXRecordDecl *VirtualBase = 0;
220
221 // First, look for the virtual base class.
222 for (unsigned I = 0, E = Path.size(); I != E; ++I) {
223 const CXXBasePathElement &Element = Path[I];
224
225 if (Element.Base->isVirtual()) {
226 // FIXME: Can we break when we find the first virtual base?
227 // (If we can't, can't we just iterate over the path in reverse order?)
228 NonVirtualStart = I + 1;
229 QualType VBaseType = Element.Base->getType();
230 VirtualBase =
231 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
232 }
233 }
234
235 // Now compute the non-virtual offset.
236 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
237 const CXXBasePathElement &Element = Path[I];
238
239 // Check the base class offset.
240 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
241
242 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
243 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
244
245 NonVirtualOffset += Layout.getBaseClassOffset(Base);
246 }
247
248 // FIXME: This should probably use CharUnits or something. Maybe we should
249 // even change the base offsets in ASTRecordLayout to be specified in
250 // CharUnits.
251 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
252
253}
254
255static BaseOffset ComputeBaseOffset(ASTContext &Context,
256 const CXXRecordDecl *BaseRD,
257 const CXXRecordDecl *DerivedRD) {
258 CXXBasePaths Paths(/*FindAmbiguities=*/false,
259 /*RecordPaths=*/true, /*DetectVirtual=*/false);
260
261 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
262 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
263 llvm_unreachable("Class must be derived from the passed in base class!");
264 }
265
266 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
267}
268
269static BaseOffset
270ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
271 const CXXMethodDecl *DerivedMD,
272 const CXXMethodDecl *BaseMD) {
273 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
274 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
275
276 // Canonicalize the return types.
277 CanQualType CanDerivedReturnType =
278 Context.getCanonicalType(DerivedFT->getResultType());
279 CanQualType CanBaseReturnType =
280 Context.getCanonicalType(BaseFT->getResultType());
281
282 assert(CanDerivedReturnType->getTypeClass() ==
283 CanBaseReturnType->getTypeClass() &&
284 "Types must have same type class!");
285
286 if (CanDerivedReturnType == CanBaseReturnType) {
287 // No adjustment needed.
288 return BaseOffset();
289 }
290
291 if (isa<ReferenceType>(CanDerivedReturnType)) {
292 CanDerivedReturnType =
293 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
294 CanBaseReturnType =
295 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
296 } else if (isa<PointerType>(CanDerivedReturnType)) {
297 CanDerivedReturnType =
298 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
299 CanBaseReturnType =
300 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
301 } else {
302 llvm_unreachable("Unexpected return type!");
303 }
304
305 // We need to compare unqualified types here; consider
306 // const T *Base::foo();
307 // T *Derived::foo();
308 if (CanDerivedReturnType.getUnqualifiedType() ==
309 CanBaseReturnType.getUnqualifiedType()) {
310 // No adjustment needed.
311 return BaseOffset();
312 }
313
314 const CXXRecordDecl *DerivedRD =
315 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
316
317 const CXXRecordDecl *BaseRD =
318 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
319
320 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
321}
322
323void
324FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
325 CharUnits OffsetInLayoutClass,
326 SubobjectOffsetMapTy &SubobjectOffsets,
327 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
328 SubobjectCountMapTy &SubobjectCounts) {
329 const CXXRecordDecl *RD = Base.getBase();
330
331 unsigned SubobjectNumber = 0;
332 if (!IsVirtual)
333 SubobjectNumber = ++SubobjectCounts[RD];
334
335 // Set up the subobject to offset mapping.
336 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
337 && "Subobject offset already exists!");
338 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
339 && "Subobject offset already exists!");
340
341 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
342 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
343 OffsetInLayoutClass;
344
345 // Traverse our bases.
346 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
347 E = RD->bases_end(); I != E; ++I) {
348 const CXXRecordDecl *BaseDecl =
349 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
350
351 CharUnits BaseOffset;
352 CharUnits BaseOffsetInLayoutClass;
353 if (I->isVirtual()) {
354 // Check if we've visited this virtual base before.
355 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
356 continue;
357
358 const ASTRecordLayout &LayoutClassLayout =
359 Context.getASTRecordLayout(LayoutClass);
360
361 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
362 BaseOffsetInLayoutClass =
363 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
364 } else {
365 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
366 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
367
368 BaseOffset = Base.getBaseOffset() + Offset;
369 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
370 }
371
372 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
373 I->isVirtual(), BaseOffsetInLayoutClass,
374 SubobjectOffsets, SubobjectLayoutClassOffsets,
375 SubobjectCounts);
376 }
377}
378
379void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
380 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
381 const CXXRecordDecl *RD = Base.getBase();
382 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
383
384 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
385 E = RD->bases_end(); I != E; ++I) {
386 const CXXRecordDecl *BaseDecl =
387 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
388
389 // Ignore bases that don't have any virtual member functions.
390 if (!BaseDecl->isPolymorphic())
391 continue;
392
393 CharUnits BaseOffset;
394 if (I->isVirtual()) {
395 if (!VisitedVirtualBases.insert(BaseDecl)) {
396 // We've visited this base before.
397 continue;
398 }
399
400 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
401 } else {
402 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
403 }
404
405 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
406 }
407
408 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
409 Out << Base.getBaseOffset().getQuantity() << ")\n";
410
411 // Now dump the overriders for this base subobject.
412 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
413 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000414 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000415
416 if (!MD->isVirtual())
417 continue;
418
419 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
420
421 Out << " " << MD->getQualifiedNameAsString() << " - (";
422 Out << Overrider.Method->getQualifiedNameAsString();
423 Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
424
425 BaseOffset Offset;
426 if (!Overrider.Method->isPure())
427 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
428
429 if (!Offset.isEmpty()) {
430 Out << " [ret-adj: ";
431 if (Offset.VirtualBase)
432 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
433
434 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
435 }
436
437 Out << "\n";
438 }
439}
440
441/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
442struct VCallOffsetMap {
443
444 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
445
446 /// Offsets - Keeps track of methods and their offsets.
447 // FIXME: This should be a real map and not a vector.
448 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
449
450 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
451 /// can share the same vcall offset.
452 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
453 const CXXMethodDecl *RHS);
454
455public:
456 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
457 /// add was successful, or false if there was already a member function with
458 /// the same signature in the map.
459 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
460
461 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
462 /// vtable address point) for the given virtual member function.
463 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
464
465 // empty - Return whether the offset map is empty or not.
466 bool empty() const { return Offsets.empty(); }
467};
468
469static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
470 const CXXMethodDecl *RHS) {
John McCall260a3e42012-03-21 06:57:19 +0000471 const FunctionProtoType *LT =
472 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
473 const FunctionProtoType *RT =
474 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbourne24018462011-09-26 01:57:12 +0000475
476 // Fast-path matches in the canonical types.
477 if (LT == RT) return true;
478
479 // Force the signatures to match. We can't rely on the overrides
480 // list here because there isn't necessarily an inheritance
481 // relationship between the two methods.
John McCall260a3e42012-03-21 06:57:19 +0000482 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Peter Collingbourne24018462011-09-26 01:57:12 +0000483 LT->getNumArgs() != RT->getNumArgs())
484 return false;
485 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
486 if (LT->getArgType(I) != RT->getArgType(I))
487 return false;
488 return true;
489}
490
491bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
492 const CXXMethodDecl *RHS) {
493 assert(LHS->isVirtual() && "LHS must be virtual!");
494 assert(RHS->isVirtual() && "LHS must be virtual!");
495
496 // A destructor can share a vcall offset with another destructor.
497 if (isa<CXXDestructorDecl>(LHS))
498 return isa<CXXDestructorDecl>(RHS);
499
500 // FIXME: We need to check more things here.
501
502 // The methods must have the same name.
503 DeclarationName LHSName = LHS->getDeclName();
504 DeclarationName RHSName = RHS->getDeclName();
505 if (LHSName != RHSName)
506 return false;
507
508 // And the same signatures.
509 return HasSameVirtualSignature(LHS, RHS);
510}
511
512bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
513 CharUnits OffsetOffset) {
514 // Check if we can reuse an offset.
515 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
516 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
517 return false;
518 }
519
520 // Add the offset.
521 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
522 return true;
523}
524
525CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
526 // Look for an offset.
527 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
528 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
529 return Offsets[I].second;
530 }
531
532 llvm_unreachable("Should always find a vcall offset offset!");
533}
534
535/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
536class VCallAndVBaseOffsetBuilder {
537public:
538 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
539 VBaseOffsetOffsetsMapTy;
540
541private:
542 /// MostDerivedClass - The most derived class for which we're building vcall
543 /// and vbase offsets.
544 const CXXRecordDecl *MostDerivedClass;
545
546 /// LayoutClass - The class we're using for layout information. Will be
547 /// different than the most derived class if we're building a construction
548 /// vtable.
549 const CXXRecordDecl *LayoutClass;
550
551 /// Context - The ASTContext which we will use for layout information.
552 ASTContext &Context;
553
554 /// Components - vcall and vbase offset components
555 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
556 VTableComponentVectorTy Components;
557
558 /// VisitedVirtualBases - Visited virtual bases.
559 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
560
561 /// VCallOffsets - Keeps track of vcall offsets.
562 VCallOffsetMap VCallOffsets;
563
564
565 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
566 /// relative to the address point.
567 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
568
569 /// FinalOverriders - The final overriders of the most derived class.
570 /// (Can be null when we're not building a vtable of the most derived class).
571 const FinalOverriders *Overriders;
572
573 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
574 /// given base subobject.
575 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
576 CharUnits RealBaseOffset);
577
578 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
579 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
580
581 /// AddVBaseOffsets - Add vbase offsets for the given class.
582 void AddVBaseOffsets(const CXXRecordDecl *Base,
583 CharUnits OffsetInLayoutClass);
584
585 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
586 /// chars, relative to the vtable address point.
587 CharUnits getCurrentOffsetOffset() const;
588
589public:
590 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
591 const CXXRecordDecl *LayoutClass,
592 const FinalOverriders *Overriders,
593 BaseSubobject Base, bool BaseIsVirtual,
594 CharUnits OffsetInLayoutClass)
595 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
596 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
597
598 // Add vcall and vbase offsets.
599 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
600 }
601
602 /// Methods for iterating over the components.
603 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
604 const_iterator components_begin() const { return Components.rbegin(); }
605 const_iterator components_end() const { return Components.rend(); }
606
607 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
608 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
609 return VBaseOffsetOffsets;
610 }
611};
612
613void
614VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
615 bool BaseIsVirtual,
616 CharUnits RealBaseOffset) {
617 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
618
619 // Itanium C++ ABI 2.5.2:
620 // ..in classes sharing a virtual table with a primary base class, the vcall
621 // and vbase offsets added by the derived class all come before the vcall
622 // and vbase offsets required by the base class, so that the latter may be
623 // laid out as required by the base class without regard to additions from
624 // the derived class(es).
625
626 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
627 // emit them for the primary base first).
628 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
629 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
630
631 CharUnits PrimaryBaseOffset;
632
633 // Get the base offset of the primary base.
634 if (PrimaryBaseIsVirtual) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000635 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000636 "Primary vbase should have a zero offset!");
637
638 const ASTRecordLayout &MostDerivedClassLayout =
639 Context.getASTRecordLayout(MostDerivedClass);
640
641 PrimaryBaseOffset =
642 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
643 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000644 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000645 "Primary base should have a zero offset!");
646
647 PrimaryBaseOffset = Base.getBaseOffset();
648 }
649
650 AddVCallAndVBaseOffsets(
651 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
652 PrimaryBaseIsVirtual, RealBaseOffset);
653 }
654
655 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
656
657 // We only want to add vcall offsets for virtual bases.
658 if (BaseIsVirtual)
659 AddVCallOffsets(Base, RealBaseOffset);
660}
661
662CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
663 // OffsetIndex is the index of this vcall or vbase offset, relative to the
664 // vtable address point. (We subtract 3 to account for the information just
665 // above the address point, the RTTI info, the offset to top, and the
666 // vcall offset itself).
667 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
668
669 CharUnits PointerWidth =
670 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
671 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
672 return OffsetOffset;
673}
674
675void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
676 CharUnits VBaseOffset) {
677 const CXXRecordDecl *RD = Base.getBase();
678 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
679
680 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
681
682 // Handle the primary base first.
683 // We only want to add vcall offsets if the base is non-virtual; a virtual
684 // primary base will have its vcall and vbase offsets emitted already.
685 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
686 // Get the base offset of the primary base.
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000687 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000688 "Primary base should have a zero offset!");
689
690 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
691 VBaseOffset);
692 }
693
694 // Add the vcall offsets.
695 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
696 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000697 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000698
699 if (!MD->isVirtual())
700 continue;
701
702 CharUnits OffsetOffset = getCurrentOffsetOffset();
703
704 // Don't add a vcall offset if we already have one for this member function
705 // signature.
706 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
707 continue;
708
709 CharUnits Offset = CharUnits::Zero();
710
711 if (Overriders) {
712 // Get the final overrider.
713 FinalOverriders::OverriderInfo Overrider =
714 Overriders->getOverrider(MD, Base.getBaseOffset());
715
716 /// The vcall offset is the offset from the virtual base to the object
717 /// where the function was overridden.
718 Offset = Overrider.Offset - VBaseOffset;
719 }
720
721 Components.push_back(
722 VTableComponent::MakeVCallOffset(Offset));
723 }
724
725 // And iterate over all non-virtual bases (ignoring the primary base).
726 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
727 E = RD->bases_end(); I != E; ++I) {
728
729 if (I->isVirtual())
730 continue;
731
732 const CXXRecordDecl *BaseDecl =
733 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
734 if (BaseDecl == PrimaryBase)
735 continue;
736
737 // Get the base offset of this base.
738 CharUnits BaseOffset = Base.getBaseOffset() +
739 Layout.getBaseClassOffset(BaseDecl);
740
741 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
742 VBaseOffset);
743 }
744}
745
746void
747VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
748 CharUnits OffsetInLayoutClass) {
749 const ASTRecordLayout &LayoutClassLayout =
750 Context.getASTRecordLayout(LayoutClass);
751
752 // Add vbase offsets.
753 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
754 E = RD->bases_end(); I != E; ++I) {
755 const CXXRecordDecl *BaseDecl =
756 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
757
758 // Check if this is a virtual base that we haven't visited before.
759 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
760 CharUnits Offset =
761 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
762
763 // Add the vbase offset offset.
764 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
765 "vbase offset offset already exists!");
766
767 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
768 VBaseOffsetOffsets.insert(
769 std::make_pair(BaseDecl, VBaseOffsetOffset));
770
771 Components.push_back(
772 VTableComponent::MakeVBaseOffset(Offset));
773 }
774
775 // Check the base class looking for more vbase offsets.
776 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
777 }
778}
779
780/// VTableBuilder - Class for building vtable layout information.
781class VTableBuilder {
782public:
783 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
784 /// primary bases.
785 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
786 PrimaryBasesSetVectorTy;
787
788 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
789 VBaseOffsetOffsetsMapTy;
790
791 typedef llvm::DenseMap<BaseSubobject, uint64_t>
792 AddressPointsMapTy;
793
794private:
795 /// VTables - Global vtable information.
796 VTableContext &VTables;
797
798 /// MostDerivedClass - The most derived class for which we're building this
799 /// vtable.
800 const CXXRecordDecl *MostDerivedClass;
801
802 /// MostDerivedClassOffset - If we're building a construction vtable, this
803 /// holds the offset from the layout class to the most derived class.
804 const CharUnits MostDerivedClassOffset;
805
806 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
807 /// base. (This only makes sense when building a construction vtable).
808 bool MostDerivedClassIsVirtual;
809
810 /// LayoutClass - The class we're using for layout information. Will be
811 /// different than the most derived class if we're building a construction
812 /// vtable.
813 const CXXRecordDecl *LayoutClass;
814
815 /// Context - The ASTContext which we will use for layout information.
816 ASTContext &Context;
817
818 /// FinalOverriders - The final overriders of the most derived class.
819 const FinalOverriders Overriders;
820
821 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
822 /// bases in this vtable.
823 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
824
825 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
826 /// the most derived class.
827 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
828
829 /// Components - The components of the vtable being built.
830 SmallVector<VTableComponent, 64> Components;
831
832 /// AddressPoints - Address points for the vtable being built.
833 AddressPointsMapTy AddressPoints;
834
835 /// MethodInfo - Contains information about a method in a vtable.
836 /// (Used for computing 'this' pointer adjustment thunks.
837 struct MethodInfo {
838 /// BaseOffset - The base offset of this method.
839 const CharUnits BaseOffset;
840
841 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
842 /// method.
843 const CharUnits BaseOffsetInLayoutClass;
844
845 /// VTableIndex - The index in the vtable that this method has.
846 /// (For destructors, this is the index of the complete destructor).
847 const uint64_t VTableIndex;
848
849 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
850 uint64_t VTableIndex)
851 : BaseOffset(BaseOffset),
852 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
853 VTableIndex(VTableIndex) { }
854
855 MethodInfo()
856 : BaseOffset(CharUnits::Zero()),
857 BaseOffsetInLayoutClass(CharUnits::Zero()),
858 VTableIndex(0) { }
859 };
860
861 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
862
863 /// MethodInfoMap - The information for all methods in the vtable we're
864 /// currently building.
865 MethodInfoMapTy MethodInfoMap;
866
867 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
868
869 /// VTableThunks - The thunks by vtable index in the vtable currently being
870 /// built.
871 VTableThunksMapTy VTableThunks;
872
873 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
874 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
875
876 /// Thunks - A map that contains all the thunks needed for all methods in the
877 /// most derived class for which the vtable is currently being built.
878 ThunksMapTy Thunks;
879
880 /// AddThunk - Add a thunk for the given method.
881 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
882
883 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
884 /// part of the vtable we're currently building.
885 void ComputeThisAdjustments();
886
887 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
888
889 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
890 /// some other base.
891 VisitedVirtualBasesSetTy PrimaryVirtualBases;
892
893 /// ComputeReturnAdjustment - Compute the return adjustment given a return
894 /// adjustment base offset.
895 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
896
897 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
898 /// the 'this' pointer from the base subobject to the derived subobject.
899 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
900 BaseSubobject Derived) const;
901
902 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
903 /// given virtual member function, its offset in the layout class and its
904 /// final overrider.
905 ThisAdjustment
906 ComputeThisAdjustment(const CXXMethodDecl *MD,
907 CharUnits BaseOffsetInLayoutClass,
908 FinalOverriders::OverriderInfo Overrider);
909
910 /// AddMethod - Add a single virtual member function to the vtable
911 /// components vector.
912 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
913
914 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
915 /// part of the vtable.
916 ///
917 /// Itanium C++ ABI 2.5.2:
918 ///
919 /// struct A { virtual void f(); };
920 /// struct B : virtual public A { int i; };
921 /// struct C : virtual public A { int j; };
922 /// struct D : public B, public C {};
923 ///
924 /// When B and C are declared, A is a primary base in each case, so although
925 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
926 /// adjustment is required and no thunk is generated. However, inside D
927 /// objects, A is no longer a primary base of C, so if we allowed calls to
928 /// C::f() to use the copy of A's vtable in the C subobject, we would need
929 /// to adjust this from C* to B::A*, which would require a third-party
930 /// thunk. Since we require that a call to C::f() first convert to A*,
931 /// C-in-D's copy of A's vtable is never referenced, so this is not
932 /// necessary.
933 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
934 CharUnits BaseOffsetInLayoutClass,
935 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
936 CharUnits FirstBaseOffsetInLayoutClass) const;
937
938
939 /// AddMethods - Add the methods of this base subobject and all its
940 /// primary bases to the vtable components vector.
941 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
942 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
943 CharUnits FirstBaseOffsetInLayoutClass,
944 PrimaryBasesSetVectorTy &PrimaryBases);
945
946 // LayoutVTable - Layout the vtable for the given base class, including its
947 // secondary vtables and any vtables for virtual bases.
948 void LayoutVTable();
949
950 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
951 /// given base subobject, as well as all its secondary vtables.
952 ///
953 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
954 /// or a direct or indirect base of a virtual base.
955 ///
956 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
957 /// in the layout class.
958 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
959 bool BaseIsMorallyVirtual,
960 bool BaseIsVirtualInLayoutClass,
961 CharUnits OffsetInLayoutClass);
962
963 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
964 /// subobject.
965 ///
966 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
967 /// or a direct or indirect base of a virtual base.
968 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
969 CharUnits OffsetInLayoutClass);
970
971 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
972 /// class hierarchy.
973 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
974 CharUnits OffsetInLayoutClass,
975 VisitedVirtualBasesSetTy &VBases);
976
977 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
978 /// given base (excluding any primary bases).
979 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
980 VisitedVirtualBasesSetTy &VBases);
981
982 /// isBuildingConstructionVTable - Return whether this vtable builder is
983 /// building a construction vtable.
984 bool isBuildingConstructorVTable() const {
985 return MostDerivedClass != LayoutClass;
986 }
987
988public:
989 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
990 CharUnits MostDerivedClassOffset,
991 bool MostDerivedClassIsVirtual, const
992 CXXRecordDecl *LayoutClass)
993 : VTables(VTables), MostDerivedClass(MostDerivedClass),
994 MostDerivedClassOffset(MostDerivedClassOffset),
995 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
996 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
997 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
998
999 LayoutVTable();
1000
David Blaikie4e4d0842012-03-11 07:00:24 +00001001 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +00001002 dumpLayout(llvm::errs());
1003 }
1004
1005 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
1025 /// getNumVTableComponents - Return the number of components in the vtable
1026 /// currently built.
1027 uint64_t getNumVTableComponents() const {
1028 return Components.size();
1029 }
1030
1031 const VTableComponent *vtable_component_begin() const {
1032 return Components.begin();
1033 }
1034
1035 const VTableComponent *vtable_component_end() const {
1036 return Components.end();
1037 }
1038
1039 AddressPointsMapTy::const_iterator address_points_begin() const {
1040 return AddressPoints.begin();
1041 }
1042
1043 AddressPointsMapTy::const_iterator address_points_end() const {
1044 return AddressPoints.end();
1045 }
1046
1047 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1048 return VTableThunks.begin();
1049 }
1050
1051 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1052 return VTableThunks.end();
1053 }
1054
1055 /// dumpLayout - Dump the vtable layout.
1056 void dumpLayout(raw_ostream&);
1057};
1058
1059void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1060 assert(!isBuildingConstructorVTable() &&
1061 "Can't add thunks for construction vtable");
1062
1063 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1064
1065 // Check if we have this thunk already.
1066 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1067 ThunksVector.end())
1068 return;
1069
1070 ThunksVector.push_back(Thunk);
1071}
1072
1073typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1074
1075/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1076/// the overridden methods that the function decl overrides.
1077static void
1078ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1079 OverriddenMethodsSetTy& OverriddenMethods) {
1080 assert(MD->isVirtual() && "Method is not virtual!");
1081
1082 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1083 E = MD->end_overridden_methods(); I != E; ++I) {
1084 const CXXMethodDecl *OverriddenMD = *I;
1085
1086 OverriddenMethods.insert(OverriddenMD);
1087
1088 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1089 }
1090}
1091
1092void VTableBuilder::ComputeThisAdjustments() {
1093 // Now go through the method info map and see if any of the methods need
1094 // 'this' pointer adjustments.
1095 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1096 E = MethodInfoMap.end(); I != E; ++I) {
1097 const CXXMethodDecl *MD = I->first;
1098 const MethodInfo &MethodInfo = I->second;
1099
1100 // Ignore adjustments for unused function pointers.
1101 uint64_t VTableIndex = MethodInfo.VTableIndex;
1102 if (Components[VTableIndex].getKind() ==
1103 VTableComponent::CK_UnusedFunctionPointer)
1104 continue;
1105
1106 // Get the final overrider for this method.
1107 FinalOverriders::OverriderInfo Overrider =
1108 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1109
1110 // Check if we need an adjustment at all.
1111 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1112 // When a return thunk is needed by a derived class that overrides a
1113 // virtual base, gcc uses a virtual 'this' adjustment as well.
1114 // While the thunk itself might be needed by vtables in subclasses or
1115 // in construction vtables, there doesn't seem to be a reason for using
1116 // the thunk in this vtable. Still, we do so to match gcc.
1117 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1118 continue;
1119 }
1120
1121 ThisAdjustment ThisAdjustment =
1122 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1123
1124 if (ThisAdjustment.isEmpty())
1125 continue;
1126
1127 // Add it.
1128 VTableThunks[VTableIndex].This = ThisAdjustment;
1129
1130 if (isa<CXXDestructorDecl>(MD)) {
1131 // Add an adjustment for the deleting destructor as well.
1132 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1133 }
1134 }
1135
1136 /// Clear the method info map.
1137 MethodInfoMap.clear();
1138
1139 if (isBuildingConstructorVTable()) {
1140 // We don't need to store thunk information for construction vtables.
1141 return;
1142 }
1143
1144 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1145 E = VTableThunks.end(); I != E; ++I) {
1146 const VTableComponent &Component = Components[I->first];
1147 const ThunkInfo &Thunk = I->second;
1148 const CXXMethodDecl *MD;
1149
1150 switch (Component.getKind()) {
1151 default:
1152 llvm_unreachable("Unexpected vtable component kind!");
1153 case VTableComponent::CK_FunctionPointer:
1154 MD = Component.getFunctionDecl();
1155 break;
1156 case VTableComponent::CK_CompleteDtorPointer:
1157 MD = Component.getDestructorDecl();
1158 break;
1159 case VTableComponent::CK_DeletingDtorPointer:
1160 // We've already added the thunk when we saw the complete dtor pointer.
1161 continue;
1162 }
1163
1164 if (MD->getParent() == MostDerivedClass)
1165 AddThunk(MD, Thunk);
1166 }
1167}
1168
1169ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1170 ReturnAdjustment Adjustment;
1171
1172 if (!Offset.isEmpty()) {
1173 if (Offset.VirtualBase) {
1174 // Get the virtual base offset offset.
1175 if (Offset.DerivedClass == MostDerivedClass) {
1176 // We can get the offset offset directly from our map.
1177 Adjustment.VBaseOffsetOffset =
1178 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1179 } else {
1180 Adjustment.VBaseOffsetOffset =
1181 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1182 Offset.VirtualBase).getQuantity();
1183 }
1184 }
1185
1186 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1187 }
1188
1189 return Adjustment;
1190}
1191
1192BaseOffset
1193VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1194 BaseSubobject Derived) const {
1195 const CXXRecordDecl *BaseRD = Base.getBase();
1196 const CXXRecordDecl *DerivedRD = Derived.getBase();
1197
1198 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1199 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1200
1201 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1202 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1203 llvm_unreachable("Class must be derived from the passed in base class!");
1204 }
1205
1206 // We have to go through all the paths, and see which one leads us to the
1207 // right base subobject.
1208 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1209 I != E; ++I) {
1210 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1211
1212 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1213
1214 if (Offset.VirtualBase) {
1215 // If we have a virtual base class, the non-virtual offset is relative
1216 // to the virtual base class offset.
1217 const ASTRecordLayout &LayoutClassLayout =
1218 Context.getASTRecordLayout(LayoutClass);
1219
1220 /// Get the virtual base offset, relative to the most derived class
1221 /// layout.
1222 OffsetToBaseSubobject +=
1223 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1224 } else {
1225 // Otherwise, the non-virtual offset is relative to the derived class
1226 // offset.
1227 OffsetToBaseSubobject += Derived.getBaseOffset();
1228 }
1229
1230 // Check if this path gives us the right base subobject.
1231 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1232 // Since we're going from the base class _to_ the derived class, we'll
1233 // invert the non-virtual offset here.
1234 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1235 return Offset;
1236 }
1237 }
1238
1239 return BaseOffset();
1240}
1241
1242ThisAdjustment
1243VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1244 CharUnits BaseOffsetInLayoutClass,
1245 FinalOverriders::OverriderInfo Overrider) {
1246 // Ignore adjustments for pure virtual member functions.
1247 if (Overrider.Method->isPure())
1248 return ThisAdjustment();
1249
1250 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1251 BaseOffsetInLayoutClass);
1252
1253 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1254 Overrider.Offset);
1255
1256 // Compute the adjustment offset.
1257 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1258 OverriderBaseSubobject);
1259 if (Offset.isEmpty())
1260 return ThisAdjustment();
1261
1262 ThisAdjustment Adjustment;
1263
1264 if (Offset.VirtualBase) {
1265 // Get the vcall offset map for this virtual base.
1266 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1267
1268 if (VCallOffsets.empty()) {
1269 // We don't have vcall offsets for this virtual base, go ahead and
1270 // build them.
1271 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1272 /*FinalOverriders=*/0,
1273 BaseSubobject(Offset.VirtualBase,
1274 CharUnits::Zero()),
1275 /*BaseIsVirtual=*/true,
1276 /*OffsetInLayoutClass=*/
1277 CharUnits::Zero());
1278
1279 VCallOffsets = Builder.getVCallOffsets();
1280 }
1281
1282 Adjustment.VCallOffsetOffset =
1283 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1284 }
1285
1286 // Set the non-virtual part of the adjustment.
1287 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1288
1289 return Adjustment;
1290}
1291
1292void
1293VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1294 ReturnAdjustment ReturnAdjustment) {
1295 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1296 assert(ReturnAdjustment.isEmpty() &&
1297 "Destructor can't have return adjustment!");
1298
1299 // Add both the complete destructor and the deleting destructor.
1300 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1301 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1302 } else {
1303 // Add the return adjustment if necessary.
1304 if (!ReturnAdjustment.isEmpty())
1305 VTableThunks[Components.size()].Return = ReturnAdjustment;
1306
1307 // Add the function.
1308 Components.push_back(VTableComponent::MakeFunction(MD));
1309 }
1310}
1311
1312/// OverridesIndirectMethodInBase - Return whether the given member function
1313/// overrides any methods in the set of given bases.
1314/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1315/// For example, if we have:
1316///
1317/// struct A { virtual void f(); }
1318/// struct B : A { virtual void f(); }
1319/// struct C : B { virtual void f(); }
1320///
1321/// OverridesIndirectMethodInBase will return true if given C::f as the method
1322/// and { A } as the set of bases.
1323static bool
1324OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1325 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1326 if (Bases.count(MD->getParent()))
1327 return true;
1328
1329 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1330 E = MD->end_overridden_methods(); I != E; ++I) {
1331 const CXXMethodDecl *OverriddenMD = *I;
1332
1333 // Check "indirect overriders".
1334 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1335 return true;
1336 }
1337
1338 return false;
1339}
1340
1341bool
1342VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1343 CharUnits BaseOffsetInLayoutClass,
1344 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1345 CharUnits FirstBaseOffsetInLayoutClass) const {
1346 // If the base and the first base in the primary base chain have the same
1347 // offsets, then this overrider will be used.
1348 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1349 return true;
1350
1351 // We know now that Base (or a direct or indirect base of it) is a primary
1352 // base in part of the class hierarchy, but not a primary base in the most
1353 // derived class.
1354
1355 // If the overrider is the first base in the primary base chain, we know
1356 // that the overrider will be used.
1357 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1358 return true;
1359
1360 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1361
1362 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1363 PrimaryBases.insert(RD);
1364
1365 // Now traverse the base chain, starting with the first base, until we find
1366 // the base that is no longer a primary base.
1367 while (true) {
1368 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1369 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1370
1371 if (!PrimaryBase)
1372 break;
1373
1374 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001375 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001376 "Primary base should always be at offset 0!");
1377
1378 const ASTRecordLayout &LayoutClassLayout =
1379 Context.getASTRecordLayout(LayoutClass);
1380
1381 // Now check if this is the primary base that is not a primary base in the
1382 // most derived class.
1383 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1384 FirstBaseOffsetInLayoutClass) {
1385 // We found it, stop walking the chain.
1386 break;
1387 }
1388 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001389 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001390 "Primary base should always be at offset 0!");
1391 }
1392
1393 if (!PrimaryBases.insert(PrimaryBase))
1394 llvm_unreachable("Found a duplicate primary base!");
1395
1396 RD = PrimaryBase;
1397 }
1398
1399 // If the final overrider is an override of one of the primary bases,
1400 // then we know that it will be used.
1401 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1402}
1403
1404/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1405/// from the nearest base. Returns null if no method was found.
1406static const CXXMethodDecl *
1407FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1408 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1409 OverriddenMethodsSetTy OverriddenMethods;
1410 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1411
1412 for (int I = Bases.size(), E = 0; I != E; --I) {
1413 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1414
1415 // Now check the overriden methods.
1416 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1417 E = OverriddenMethods.end(); I != E; ++I) {
1418 const CXXMethodDecl *OverriddenMD = *I;
1419
1420 // We found our overridden method.
1421 if (OverriddenMD->getParent() == PrimaryBase)
1422 return OverriddenMD;
1423 }
1424 }
1425
1426 return 0;
1427}
1428
1429void
1430VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1431 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1432 CharUnits FirstBaseOffsetInLayoutClass,
1433 PrimaryBasesSetVectorTy &PrimaryBases) {
1434 const CXXRecordDecl *RD = Base.getBase();
1435 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1436
1437 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1438 CharUnits PrimaryBaseOffset;
1439 CharUnits PrimaryBaseOffsetInLayoutClass;
1440 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001441 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001442 "Primary vbase should have a zero offset!");
1443
1444 const ASTRecordLayout &MostDerivedClassLayout =
1445 Context.getASTRecordLayout(MostDerivedClass);
1446
1447 PrimaryBaseOffset =
1448 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1449
1450 const ASTRecordLayout &LayoutClassLayout =
1451 Context.getASTRecordLayout(LayoutClass);
1452
1453 PrimaryBaseOffsetInLayoutClass =
1454 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1455 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001456 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001457 "Primary base should have a zero offset!");
1458
1459 PrimaryBaseOffset = Base.getBaseOffset();
1460 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1461 }
1462
1463 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1464 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1465 FirstBaseOffsetInLayoutClass, PrimaryBases);
1466
1467 if (!PrimaryBases.insert(PrimaryBase))
1468 llvm_unreachable("Found a duplicate primary base!");
1469 }
1470
1471 // Now go through all virtual member functions and add them.
1472 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1473 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001474 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001475
1476 if (!MD->isVirtual())
1477 continue;
1478
1479 // Get the final overrider.
1480 FinalOverriders::OverriderInfo Overrider =
1481 Overriders.getOverrider(MD, Base.getBaseOffset());
1482
1483 // Check if this virtual member function overrides a method in a primary
1484 // base. If this is the case, and the return type doesn't require adjustment
1485 // then we can just use the member function from the primary base.
1486 if (const CXXMethodDecl *OverriddenMD =
1487 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1488 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1489 OverriddenMD).isEmpty()) {
1490 // Replace the method info of the overridden method with our own
1491 // method.
1492 assert(MethodInfoMap.count(OverriddenMD) &&
1493 "Did not find the overridden method!");
1494 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1495
1496 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1497 OverriddenMethodInfo.VTableIndex);
1498
1499 assert(!MethodInfoMap.count(MD) &&
1500 "Should not have method info for this method yet!");
1501
1502 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1503 MethodInfoMap.erase(OverriddenMD);
1504
1505 // If the overridden method exists in a virtual base class or a direct
1506 // or indirect base class of a virtual base class, we need to emit a
1507 // thunk if we ever have a class hierarchy where the base class is not
1508 // a primary base in the complete object.
1509 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1510 // Compute the this adjustment.
1511 ThisAdjustment ThisAdjustment =
1512 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1513 Overrider);
1514
1515 if (ThisAdjustment.VCallOffsetOffset &&
1516 Overrider.Method->getParent() == MostDerivedClass) {
1517
1518 // There's no return adjustment from OverriddenMD and MD,
1519 // but that doesn't mean there isn't one between MD and
1520 // the final overrider.
1521 BaseOffset ReturnAdjustmentOffset =
1522 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1523 ReturnAdjustment ReturnAdjustment =
1524 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1525
1526 // This is a virtual thunk for the most derived class, add it.
1527 AddThunk(Overrider.Method,
1528 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1529 }
1530 }
1531
1532 continue;
1533 }
1534 }
1535
1536 // Insert the method info for this method.
1537 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1538 Components.size());
1539
1540 assert(!MethodInfoMap.count(MD) &&
1541 "Should not have method info for this method yet!");
1542 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1543
1544 // Check if this overrider is going to be used.
1545 const CXXMethodDecl *OverriderMD = Overrider.Method;
1546 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1547 FirstBaseInPrimaryBaseChain,
1548 FirstBaseOffsetInLayoutClass)) {
1549 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1550 continue;
1551 }
1552
1553 // Check if this overrider needs a return adjustment.
1554 // We don't want to do this for pure virtual member functions.
1555 BaseOffset ReturnAdjustmentOffset;
1556 if (!OverriderMD->isPure()) {
1557 ReturnAdjustmentOffset =
1558 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1559 }
1560
1561 ReturnAdjustment ReturnAdjustment =
1562 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1563
1564 AddMethod(Overrider.Method, ReturnAdjustment);
1565 }
1566}
1567
1568void VTableBuilder::LayoutVTable() {
1569 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1570 CharUnits::Zero()),
1571 /*BaseIsMorallyVirtual=*/false,
1572 MostDerivedClassIsVirtual,
1573 MostDerivedClassOffset);
1574
1575 VisitedVirtualBasesSetTy VBases;
1576
1577 // Determine the primary virtual bases.
1578 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1579 VBases);
1580 VBases.clear();
1581
1582 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1583
1584 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001585 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001586 if (IsAppleKext)
1587 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1588}
1589
1590void
1591VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1592 bool BaseIsMorallyVirtual,
1593 bool BaseIsVirtualInLayoutClass,
1594 CharUnits OffsetInLayoutClass) {
1595 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1596
1597 // Add vcall and vbase offsets for this vtable.
1598 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1599 Base, BaseIsVirtualInLayoutClass,
1600 OffsetInLayoutClass);
1601 Components.append(Builder.components_begin(), Builder.components_end());
1602
1603 // Check if we need to add these vcall offsets.
1604 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1605 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1606
1607 if (VCallOffsets.empty())
1608 VCallOffsets = Builder.getVCallOffsets();
1609 }
1610
1611 // If we're laying out the most derived class we want to keep track of the
1612 // virtual base class offset offsets.
1613 if (Base.getBase() == MostDerivedClass)
1614 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1615
1616 // Add the offset to top.
1617 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1618 Components.push_back(
1619 VTableComponent::MakeOffsetToTop(OffsetToTop));
1620
1621 // Next, add the RTTI.
1622 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1623
1624 uint64_t AddressPoint = Components.size();
1625
1626 // Now go through all virtual member functions and add them.
1627 PrimaryBasesSetVectorTy PrimaryBases;
1628 AddMethods(Base, OffsetInLayoutClass,
1629 Base.getBase(), OffsetInLayoutClass,
1630 PrimaryBases);
1631
1632 // Compute 'this' pointer adjustments.
1633 ComputeThisAdjustments();
1634
1635 // Add all address points.
1636 const CXXRecordDecl *RD = Base.getBase();
1637 while (true) {
1638 AddressPoints.insert(std::make_pair(
1639 BaseSubobject(RD, OffsetInLayoutClass),
1640 AddressPoint));
1641
1642 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1643 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1644
1645 if (!PrimaryBase)
1646 break;
1647
1648 if (Layout.isPrimaryBaseVirtual()) {
1649 // Check if this virtual primary base is a primary base in the layout
1650 // class. If it's not, we don't want to add it.
1651 const ASTRecordLayout &LayoutClassLayout =
1652 Context.getASTRecordLayout(LayoutClass);
1653
1654 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1655 OffsetInLayoutClass) {
1656 // We don't want to add this class (or any of its primary bases).
1657 break;
1658 }
1659 }
1660
1661 RD = PrimaryBase;
1662 }
1663
1664 // Layout secondary vtables.
1665 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1666}
1667
1668void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1669 bool BaseIsMorallyVirtual,
1670 CharUnits OffsetInLayoutClass) {
1671 // Itanium C++ ABI 2.5.2:
1672 // Following the primary virtual table of a derived class are secondary
1673 // virtual tables for each of its proper base classes, except any primary
1674 // base(s) with which it shares its primary virtual table.
1675
1676 const CXXRecordDecl *RD = Base.getBase();
1677 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1678 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1679
1680 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1681 E = RD->bases_end(); I != E; ++I) {
1682 // Ignore virtual bases, we'll emit them later.
1683 if (I->isVirtual())
1684 continue;
1685
1686 const CXXRecordDecl *BaseDecl =
1687 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1688
1689 // Ignore bases that don't have a vtable.
1690 if (!BaseDecl->isDynamicClass())
1691 continue;
1692
1693 if (isBuildingConstructorVTable()) {
1694 // Itanium C++ ABI 2.6.4:
1695 // Some of the base class subobjects may not need construction virtual
1696 // tables, which will therefore not be present in the construction
1697 // virtual table group, even though the subobject virtual tables are
1698 // present in the main virtual table group for the complete object.
1699 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1700 continue;
1701 }
1702
1703 // Get the base offset of this base.
1704 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1705 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1706
1707 CharUnits BaseOffsetInLayoutClass =
1708 OffsetInLayoutClass + RelativeBaseOffset;
1709
1710 // Don't emit a secondary vtable for a primary base. We might however want
1711 // to emit secondary vtables for other bases of this base.
1712 if (BaseDecl == PrimaryBase) {
1713 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1714 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1715 continue;
1716 }
1717
1718 // Layout the primary vtable (and any secondary vtables) for this base.
1719 LayoutPrimaryAndSecondaryVTables(
1720 BaseSubobject(BaseDecl, BaseOffset),
1721 BaseIsMorallyVirtual,
1722 /*BaseIsVirtualInLayoutClass=*/false,
1723 BaseOffsetInLayoutClass);
1724 }
1725}
1726
1727void
1728VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1729 CharUnits OffsetInLayoutClass,
1730 VisitedVirtualBasesSetTy &VBases) {
1731 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1732
1733 // Check if this base has a primary base.
1734 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1735
1736 // Check if it's virtual.
1737 if (Layout.isPrimaryBaseVirtual()) {
1738 bool IsPrimaryVirtualBase = true;
1739
1740 if (isBuildingConstructorVTable()) {
1741 // Check if the base is actually a primary base in the class we use for
1742 // layout.
1743 const ASTRecordLayout &LayoutClassLayout =
1744 Context.getASTRecordLayout(LayoutClass);
1745
1746 CharUnits PrimaryBaseOffsetInLayoutClass =
1747 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1748
1749 // We know that the base is not a primary base in the layout class if
1750 // the base offsets are different.
1751 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1752 IsPrimaryVirtualBase = false;
1753 }
1754
1755 if (IsPrimaryVirtualBase)
1756 PrimaryVirtualBases.insert(PrimaryBase);
1757 }
1758 }
1759
1760 // Traverse bases, looking for more primary virtual bases.
1761 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1762 E = RD->bases_end(); I != E; ++I) {
1763 const CXXRecordDecl *BaseDecl =
1764 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1765
1766 CharUnits BaseOffsetInLayoutClass;
1767
1768 if (I->isVirtual()) {
1769 if (!VBases.insert(BaseDecl))
1770 continue;
1771
1772 const ASTRecordLayout &LayoutClassLayout =
1773 Context.getASTRecordLayout(LayoutClass);
1774
1775 BaseOffsetInLayoutClass =
1776 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1777 } else {
1778 BaseOffsetInLayoutClass =
1779 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1780 }
1781
1782 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1783 }
1784}
1785
1786void
1787VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1788 VisitedVirtualBasesSetTy &VBases) {
1789 // Itanium C++ ABI 2.5.2:
1790 // Then come the virtual base virtual tables, also in inheritance graph
1791 // order, and again excluding primary bases (which share virtual tables with
1792 // the classes for which they are primary).
1793 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1794 E = RD->bases_end(); I != E; ++I) {
1795 const CXXRecordDecl *BaseDecl =
1796 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1797
1798 // Check if this base needs a vtable. (If it's virtual, not a primary base
1799 // of some other class, and we haven't visited it before).
1800 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1801 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1802 const ASTRecordLayout &MostDerivedClassLayout =
1803 Context.getASTRecordLayout(MostDerivedClass);
1804 CharUnits BaseOffset =
1805 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1806
1807 const ASTRecordLayout &LayoutClassLayout =
1808 Context.getASTRecordLayout(LayoutClass);
1809 CharUnits BaseOffsetInLayoutClass =
1810 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1811
1812 LayoutPrimaryAndSecondaryVTables(
1813 BaseSubobject(BaseDecl, BaseOffset),
1814 /*BaseIsMorallyVirtual=*/true,
1815 /*BaseIsVirtualInLayoutClass=*/true,
1816 BaseOffsetInLayoutClass);
1817 }
1818
1819 // We only need to check the base for virtual base vtables if it actually
1820 // has virtual bases.
1821 if (BaseDecl->getNumVBases())
1822 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1823 }
1824}
1825
1826/// dumpLayout - Dump the vtable layout.
1827void VTableBuilder::dumpLayout(raw_ostream& Out) {
1828
1829 if (isBuildingConstructorVTable()) {
1830 Out << "Construction vtable for ('";
1831 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1832 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1833 Out << LayoutClass->getQualifiedNameAsString();
1834 } else {
1835 Out << "Vtable for '";
1836 Out << MostDerivedClass->getQualifiedNameAsString();
1837 }
1838 Out << "' (" << Components.size() << " entries).\n";
1839
1840 // Iterate through the address points and insert them into a new map where
1841 // they are keyed by the index and not the base object.
1842 // Since an address point can be shared by multiple subobjects, we use an
1843 // STL multimap.
1844 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1845 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1846 E = AddressPoints.end(); I != E; ++I) {
1847 const BaseSubobject& Base = I->first;
1848 uint64_t Index = I->second;
1849
1850 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1851 }
1852
1853 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1854 uint64_t Index = I;
1855
1856 Out << llvm::format("%4d | ", I);
1857
1858 const VTableComponent &Component = Components[I];
1859
1860 // Dump the component.
1861 switch (Component.getKind()) {
1862
1863 case VTableComponent::CK_VCallOffset:
1864 Out << "vcall_offset ("
1865 << Component.getVCallOffset().getQuantity()
1866 << ")";
1867 break;
1868
1869 case VTableComponent::CK_VBaseOffset:
1870 Out << "vbase_offset ("
1871 << Component.getVBaseOffset().getQuantity()
1872 << ")";
1873 break;
1874
1875 case VTableComponent::CK_OffsetToTop:
1876 Out << "offset_to_top ("
1877 << Component.getOffsetToTop().getQuantity()
1878 << ")";
1879 break;
1880
1881 case VTableComponent::CK_RTTI:
1882 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1883 break;
1884
1885 case VTableComponent::CK_FunctionPointer: {
1886 const CXXMethodDecl *MD = Component.getFunctionDecl();
1887
1888 std::string Str =
1889 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1890 MD);
1891 Out << Str;
1892 if (MD->isPure())
1893 Out << " [pure]";
1894
David Blaikied954ab42012-10-16 20:25:33 +00001895 if (MD->isDeleted())
1896 Out << " [deleted]";
1897
Peter Collingbourne24018462011-09-26 01:57:12 +00001898 ThunkInfo Thunk = VTableThunks.lookup(I);
1899 if (!Thunk.isEmpty()) {
1900 // If this function pointer has a return adjustment, dump it.
1901 if (!Thunk.Return.isEmpty()) {
1902 Out << "\n [return adjustment: ";
1903 Out << Thunk.Return.NonVirtual << " non-virtual";
1904
1905 if (Thunk.Return.VBaseOffsetOffset) {
1906 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1907 Out << " vbase offset offset";
1908 }
1909
1910 Out << ']';
1911 }
1912
1913 // If this function pointer has a 'this' pointer adjustment, dump it.
1914 if (!Thunk.This.isEmpty()) {
1915 Out << "\n [this adjustment: ";
1916 Out << Thunk.This.NonVirtual << " non-virtual";
1917
1918 if (Thunk.This.VCallOffsetOffset) {
1919 Out << ", " << Thunk.This.VCallOffsetOffset;
1920 Out << " vcall offset offset";
1921 }
1922
1923 Out << ']';
1924 }
1925 }
1926
1927 break;
1928 }
1929
1930 case VTableComponent::CK_CompleteDtorPointer:
1931 case VTableComponent::CK_DeletingDtorPointer: {
1932 bool IsComplete =
1933 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1934
1935 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1936
1937 Out << DD->getQualifiedNameAsString();
1938 if (IsComplete)
1939 Out << "() [complete]";
1940 else
1941 Out << "() [deleting]";
1942
1943 if (DD->isPure())
1944 Out << " [pure]";
1945
1946 ThunkInfo Thunk = VTableThunks.lookup(I);
1947 if (!Thunk.isEmpty()) {
1948 // If this destructor has a 'this' pointer adjustment, dump it.
1949 if (!Thunk.This.isEmpty()) {
1950 Out << "\n [this adjustment: ";
1951 Out << Thunk.This.NonVirtual << " non-virtual";
1952
1953 if (Thunk.This.VCallOffsetOffset) {
1954 Out << ", " << Thunk.This.VCallOffsetOffset;
1955 Out << " vcall offset offset";
1956 }
1957
1958 Out << ']';
1959 }
1960 }
1961
1962 break;
1963 }
1964
1965 case VTableComponent::CK_UnusedFunctionPointer: {
1966 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1967
1968 std::string Str =
1969 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1970 MD);
1971 Out << "[unused] " << Str;
1972 if (MD->isPure())
1973 Out << " [pure]";
1974 }
1975
1976 }
1977
1978 Out << '\n';
1979
1980 // Dump the next address point.
1981 uint64_t NextIndex = Index + 1;
1982 if (AddressPointsByIndex.count(NextIndex)) {
1983 if (AddressPointsByIndex.count(NextIndex) == 1) {
1984 const BaseSubobject &Base =
1985 AddressPointsByIndex.find(NextIndex)->second;
1986
1987 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
1988 Out << ", " << Base.getBaseOffset().getQuantity();
1989 Out << ") vtable address --\n";
1990 } else {
1991 CharUnits BaseOffset =
1992 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
1993
1994 // We store the class names in a set to get a stable order.
1995 std::set<std::string> ClassNames;
1996 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
1997 AddressPointsByIndex.lower_bound(NextIndex), E =
1998 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
1999 assert(I->second.getBaseOffset() == BaseOffset &&
2000 "Invalid base offset!");
2001 const CXXRecordDecl *RD = I->second.getBase();
2002 ClassNames.insert(RD->getQualifiedNameAsString());
2003 }
2004
2005 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2006 E = ClassNames.end(); I != E; ++I) {
2007 Out << " -- (" << *I;
2008 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2009 }
2010 }
2011 }
2012 }
2013
2014 Out << '\n';
2015
2016 if (isBuildingConstructorVTable())
2017 return;
2018
2019 if (MostDerivedClass->getNumVBases()) {
2020 // We store the virtual base class names and their offsets in a map to get
2021 // a stable order.
2022
2023 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2024 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2025 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2026 std::string ClassName = I->first->getQualifiedNameAsString();
2027 CharUnits OffsetOffset = I->second;
2028 ClassNamesAndOffsets.insert(
2029 std::make_pair(ClassName, OffsetOffset));
2030 }
2031
2032 Out << "Virtual base offset offsets for '";
2033 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2034 Out << ClassNamesAndOffsets.size();
2035 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2036
2037 for (std::map<std::string, CharUnits>::const_iterator I =
2038 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2039 I != E; ++I)
2040 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2041
2042 Out << "\n";
2043 }
2044
2045 if (!Thunks.empty()) {
2046 // We store the method names in a map to get a stable order.
2047 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2048
2049 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2050 I != E; ++I) {
2051 const CXXMethodDecl *MD = I->first;
2052 std::string MethodName =
2053 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2054 MD);
2055
2056 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2057 }
2058
2059 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2060 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2061 I != E; ++I) {
2062 const std::string &MethodName = I->first;
2063 const CXXMethodDecl *MD = I->second;
2064
2065 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2066 std::sort(ThunksVector.begin(), ThunksVector.end());
2067
2068 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2069 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2070
2071 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2072 const ThunkInfo &Thunk = ThunksVector[I];
2073
2074 Out << llvm::format("%4d | ", I);
2075
2076 // If this function pointer has a return pointer adjustment, dump it.
2077 if (!Thunk.Return.isEmpty()) {
2078 Out << "return adjustment: " << Thunk.This.NonVirtual;
2079 Out << " non-virtual";
2080 if (Thunk.Return.VBaseOffsetOffset) {
2081 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2082 Out << " vbase offset offset";
2083 }
2084
2085 if (!Thunk.This.isEmpty())
2086 Out << "\n ";
2087 }
2088
2089 // If this function pointer has a 'this' pointer adjustment, dump it.
2090 if (!Thunk.This.isEmpty()) {
2091 Out << "this adjustment: ";
2092 Out << Thunk.This.NonVirtual << " non-virtual";
2093
2094 if (Thunk.This.VCallOffsetOffset) {
2095 Out << ", " << Thunk.This.VCallOffsetOffset;
2096 Out << " vcall offset offset";
2097 }
2098 }
2099
2100 Out << '\n';
2101 }
2102
2103 Out << '\n';
2104 }
2105 }
2106
2107 // Compute the vtable indices for all the member functions.
2108 // Store them in a map keyed by the index so we'll get a sorted table.
2109 std::map<uint64_t, std::string> IndicesMap;
2110
2111 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2112 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002113 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002114
2115 // We only want virtual member functions.
2116 if (!MD->isVirtual())
2117 continue;
2118
2119 std::string MethodName =
2120 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2121 MD);
2122
2123 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2124 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))] =
2125 MethodName + " [complete]";
2126 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))] =
2127 MethodName + " [deleting]";
2128 } else {
2129 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2130 }
2131 }
2132
2133 // Print the vtable indices for all the member functions.
2134 if (!IndicesMap.empty()) {
2135 Out << "VTable indices for '";
2136 Out << MostDerivedClass->getQualifiedNameAsString();
2137 Out << "' (" << IndicesMap.size() << " entries).\n";
2138
2139 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2140 E = IndicesMap.end(); I != E; ++I) {
2141 uint64_t VTableIndex = I->first;
2142 const std::string &MethodName = I->second;
2143
Benjamin Kramer79a55012012-03-10 02:06:27 +00002144 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
2145 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002146 }
2147 }
2148
2149 Out << '\n';
2150}
2151
2152}
2153
2154VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2155 const VTableComponent *VTableComponents,
2156 uint64_t NumVTableThunks,
2157 const VTableThunkTy *VTableThunks,
2158 const AddressPointsMapTy &AddressPoints)
2159 : NumVTableComponents(NumVTableComponents),
2160 VTableComponents(new VTableComponent[NumVTableComponents]),
2161 NumVTableThunks(NumVTableThunks),
2162 VTableThunks(new VTableThunkTy[NumVTableThunks]),
2163 AddressPoints(AddressPoints) {
2164 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002165 this->VTableComponents.get());
2166 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2167 this->VTableThunks.get());
Peter Collingbourne24018462011-09-26 01:57:12 +00002168}
2169
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002170VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002171
2172VTableContext::~VTableContext() {
2173 llvm::DeleteContainerSeconds(VTableLayouts);
2174}
2175
2176static void
2177CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2178 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2179 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2180 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2181
2182 if (!PrimaryBase)
2183 return;
2184
2185 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2186
2187 if (!PrimaryBases.insert(PrimaryBase))
2188 llvm_unreachable("Found a duplicate primary base!");
2189}
2190
2191void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2192
2193 // Itanium C++ ABI 2.5.2:
2194 // The order of the virtual function pointers in a virtual table is the
2195 // order of declaration of the corresponding member functions in the class.
2196 //
2197 // There is an entry for any virtual function declared in a class,
2198 // whether it is a new function or overrides a base class function,
2199 // unless it overrides a function from the primary base, and conversion
2200 // between their return types does not require an adjustment.
2201
2202 int64_t CurrentIndex = 0;
2203
2204 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2205 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2206
2207 if (PrimaryBase) {
John McCall5e1cdac2011-10-07 06:10:15 +00002208 assert(PrimaryBase->isCompleteDefinition() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00002209 "Should have the definition decl of the primary base!");
2210
2211 // Since the record decl shares its vtable pointer with the primary base
2212 // we need to start counting at the end of the primary base's vtable.
2213 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2214 }
2215
2216 // Collect all the primary bases, so we can check whether methods override
2217 // a method from the base.
2218 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2219 CollectPrimaryBases(RD, Context, PrimaryBases);
2220
2221 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2222
2223 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2224 e = RD->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002225 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002226
2227 // We only want virtual methods.
2228 if (!MD->isVirtual())
2229 continue;
2230
2231 // Check if this method overrides a method in the primary base.
2232 if (const CXXMethodDecl *OverriddenMD =
2233 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2234 // Check if converting from the return type of the method to the
2235 // return type of the overridden method requires conversion.
2236 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2237 OverriddenMD).isEmpty()) {
2238 // This index is shared between the index in the vtable of the primary
2239 // base class.
2240 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2241 const CXXDestructorDecl *OverriddenDD =
2242 cast<CXXDestructorDecl>(OverriddenMD);
2243
2244 // Add both the complete and deleting entries.
2245 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2246 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2247 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2248 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2249 } else {
2250 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2251 }
2252
2253 // We don't need to add an entry for this method.
2254 continue;
2255 }
2256 }
2257
2258 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2259 if (MD->isImplicit()) {
2260 assert(!ImplicitVirtualDtor &&
2261 "Did already see an implicit virtual dtor!");
2262 ImplicitVirtualDtor = DD;
2263 continue;
2264 }
2265
2266 // Add the complete dtor.
2267 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2268
2269 // Add the deleting dtor.
2270 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2271 } else {
2272 // Add the entry.
2273 MethodVTableIndices[MD] = CurrentIndex++;
2274 }
2275 }
2276
2277 if (ImplicitVirtualDtor) {
2278 // Itanium C++ ABI 2.5.2:
2279 // If a class has an implicitly-defined virtual destructor,
2280 // its entries come after the declared virtual function pointers.
2281
2282 // Add the complete dtor.
2283 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2284 CurrentIndex++;
2285
2286 // Add the deleting dtor.
2287 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2288 CurrentIndex++;
2289 }
2290
2291 NumVirtualFunctionPointers[RD] = CurrentIndex;
2292}
2293
2294uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2295 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2296 NumVirtualFunctionPointers.find(RD);
2297 if (I != NumVirtualFunctionPointers.end())
2298 return I->second;
2299
2300 ComputeMethodVTableIndices(RD);
2301
2302 I = NumVirtualFunctionPointers.find(RD);
2303 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2304 return I->second;
2305}
2306
2307uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2308 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2309 if (I != MethodVTableIndices.end())
2310 return I->second;
2311
2312 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2313
2314 ComputeMethodVTableIndices(RD);
2315
2316 I = MethodVTableIndices.find(GD);
2317 assert(I != MethodVTableIndices.end() && "Did not find index!");
2318 return I->second;
2319}
2320
2321CharUnits
2322VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2323 const CXXRecordDecl *VBase) {
2324 ClassPairTy ClassPair(RD, VBase);
2325
2326 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2327 VirtualBaseClassOffsetOffsets.find(ClassPair);
2328 if (I != VirtualBaseClassOffsetOffsets.end())
2329 return I->second;
2330
2331 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2332 BaseSubobject(RD, CharUnits::Zero()),
2333 /*BaseIsVirtual=*/false,
2334 /*OffsetInLayoutClass=*/CharUnits::Zero());
2335
2336 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2337 Builder.getVBaseOffsetOffsets().begin(),
2338 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2339 // Insert all types.
2340 ClassPairTy ClassPair(RD, I->first);
2341
2342 VirtualBaseClassOffsetOffsets.insert(
2343 std::make_pair(ClassPair, I->second));
2344 }
2345
2346 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2347 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2348
2349 return I->second;
2350}
2351
2352static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2353 SmallVector<VTableLayout::VTableThunkTy, 1>
2354 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2355 std::sort(VTableThunks.begin(), VTableThunks.end());
2356
2357 return new VTableLayout(Builder.getNumVTableComponents(),
2358 Builder.vtable_component_begin(),
2359 VTableThunks.size(),
2360 VTableThunks.data(),
2361 Builder.getAddressPoints());
2362}
2363
2364void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2365 const VTableLayout *&Entry = VTableLayouts[RD];
2366
2367 // Check if we've computed this information before.
2368 if (Entry)
2369 return;
2370
2371 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2372 /*MostDerivedClassIsVirtual=*/0, RD);
2373 Entry = CreateVTableLayout(Builder);
2374
2375 // Add the known thunks.
2376 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2377
2378 // If we don't have the vbase information for this class, insert it.
2379 // getVirtualBaseOffsetOffset will compute it separately without computing
2380 // the rest of the vtable related information.
2381 if (!RD->getNumVBases())
2382 return;
2383
2384 const RecordType *VBaseRT =
2385 RD->vbases_begin()->getType()->getAs<RecordType>();
2386 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2387
2388 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2389 return;
2390
2391 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2392 Builder.getVBaseOffsetOffsets().begin(),
2393 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2394 // Insert all types.
2395 ClassPairTy ClassPair(RD, I->first);
2396
2397 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2398 }
2399}
2400
2401VTableLayout *VTableContext::createConstructionVTableLayout(
2402 const CXXRecordDecl *MostDerivedClass,
2403 CharUnits MostDerivedClassOffset,
2404 bool MostDerivedClassIsVirtual,
2405 const CXXRecordDecl *LayoutClass) {
2406 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2407 MostDerivedClassIsVirtual, LayoutClass);
2408 return CreateVTableLayout(Builder);
2409}