blob: 9a03faace2d8e83949cea27fefa282b967836fa8 [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);
Benjamin Kramer922cec22013-02-03 18:55:34 +0000260
261 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +0000262 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +0000263
264 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
265}
266
267static BaseOffset
268ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
269 const CXXMethodDecl *DerivedMD,
270 const CXXMethodDecl *BaseMD) {
271 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
272 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
273
274 // Canonicalize the return types.
275 CanQualType CanDerivedReturnType =
276 Context.getCanonicalType(DerivedFT->getResultType());
277 CanQualType CanBaseReturnType =
278 Context.getCanonicalType(BaseFT->getResultType());
279
280 assert(CanDerivedReturnType->getTypeClass() ==
281 CanBaseReturnType->getTypeClass() &&
282 "Types must have same type class!");
283
284 if (CanDerivedReturnType == CanBaseReturnType) {
285 // No adjustment needed.
286 return BaseOffset();
287 }
288
289 if (isa<ReferenceType>(CanDerivedReturnType)) {
290 CanDerivedReturnType =
291 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
292 CanBaseReturnType =
293 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
294 } else if (isa<PointerType>(CanDerivedReturnType)) {
295 CanDerivedReturnType =
296 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
297 CanBaseReturnType =
298 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
299 } else {
300 llvm_unreachable("Unexpected return type!");
301 }
302
303 // We need to compare unqualified types here; consider
304 // const T *Base::foo();
305 // T *Derived::foo();
306 if (CanDerivedReturnType.getUnqualifiedType() ==
307 CanBaseReturnType.getUnqualifiedType()) {
308 // No adjustment needed.
309 return BaseOffset();
310 }
311
312 const CXXRecordDecl *DerivedRD =
313 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
314
315 const CXXRecordDecl *BaseRD =
316 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
317
318 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
319}
320
321void
322FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
323 CharUnits OffsetInLayoutClass,
324 SubobjectOffsetMapTy &SubobjectOffsets,
325 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
326 SubobjectCountMapTy &SubobjectCounts) {
327 const CXXRecordDecl *RD = Base.getBase();
328
329 unsigned SubobjectNumber = 0;
330 if (!IsVirtual)
331 SubobjectNumber = ++SubobjectCounts[RD];
332
333 // Set up the subobject to offset mapping.
334 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
335 && "Subobject offset already exists!");
336 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
337 && "Subobject offset already exists!");
338
339 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
340 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
341 OffsetInLayoutClass;
342
343 // Traverse our bases.
344 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
345 E = RD->bases_end(); I != E; ++I) {
346 const CXXRecordDecl *BaseDecl =
347 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
348
349 CharUnits BaseOffset;
350 CharUnits BaseOffsetInLayoutClass;
351 if (I->isVirtual()) {
352 // Check if we've visited this virtual base before.
353 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
354 continue;
355
356 const ASTRecordLayout &LayoutClassLayout =
357 Context.getASTRecordLayout(LayoutClass);
358
359 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
360 BaseOffsetInLayoutClass =
361 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
362 } else {
363 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
364 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
365
366 BaseOffset = Base.getBaseOffset() + Offset;
367 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
368 }
369
370 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
371 I->isVirtual(), BaseOffsetInLayoutClass,
372 SubobjectOffsets, SubobjectLayoutClassOffsets,
373 SubobjectCounts);
374 }
375}
376
377void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
378 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
379 const CXXRecordDecl *RD = Base.getBase();
380 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
381
382 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
383 E = RD->bases_end(); I != E; ++I) {
384 const CXXRecordDecl *BaseDecl =
385 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
386
387 // Ignore bases that don't have any virtual member functions.
388 if (!BaseDecl->isPolymorphic())
389 continue;
390
391 CharUnits BaseOffset;
392 if (I->isVirtual()) {
393 if (!VisitedVirtualBases.insert(BaseDecl)) {
394 // We've visited this base before.
395 continue;
396 }
397
398 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
399 } else {
400 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
401 }
402
403 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
404 }
405
406 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
407 Out << Base.getBaseOffset().getQuantity() << ")\n";
408
409 // Now dump the overriders for this base subobject.
410 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
411 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000412 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000413
414 if (!MD->isVirtual())
415 continue;
416
417 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
418
419 Out << " " << MD->getQualifiedNameAsString() << " - (";
420 Out << Overrider.Method->getQualifiedNameAsString();
421 Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
422
423 BaseOffset Offset;
424 if (!Overrider.Method->isPure())
425 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
426
427 if (!Offset.isEmpty()) {
428 Out << " [ret-adj: ";
429 if (Offset.VirtualBase)
430 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
431
432 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
433 }
434
435 Out << "\n";
436 }
437}
438
439/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
440struct VCallOffsetMap {
441
442 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
443
444 /// Offsets - Keeps track of methods and their offsets.
445 // FIXME: This should be a real map and not a vector.
446 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
447
448 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
449 /// can share the same vcall offset.
450 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
451 const CXXMethodDecl *RHS);
452
453public:
454 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
455 /// add was successful, or false if there was already a member function with
456 /// the same signature in the map.
457 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
458
459 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
460 /// vtable address point) for the given virtual member function.
461 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
462
463 // empty - Return whether the offset map is empty or not.
464 bool empty() const { return Offsets.empty(); }
465};
466
467static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
468 const CXXMethodDecl *RHS) {
John McCall260a3e42012-03-21 06:57:19 +0000469 const FunctionProtoType *LT =
470 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
471 const FunctionProtoType *RT =
472 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbourne24018462011-09-26 01:57:12 +0000473
474 // Fast-path matches in the canonical types.
475 if (LT == RT) return true;
476
477 // Force the signatures to match. We can't rely on the overrides
478 // list here because there isn't necessarily an inheritance
479 // relationship between the two methods.
John McCall260a3e42012-03-21 06:57:19 +0000480 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Peter Collingbourne24018462011-09-26 01:57:12 +0000481 LT->getNumArgs() != RT->getNumArgs())
482 return false;
483 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
484 if (LT->getArgType(I) != RT->getArgType(I))
485 return false;
486 return true;
487}
488
489bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
490 const CXXMethodDecl *RHS) {
491 assert(LHS->isVirtual() && "LHS must be virtual!");
492 assert(RHS->isVirtual() && "LHS must be virtual!");
493
494 // A destructor can share a vcall offset with another destructor.
495 if (isa<CXXDestructorDecl>(LHS))
496 return isa<CXXDestructorDecl>(RHS);
497
498 // FIXME: We need to check more things here.
499
500 // The methods must have the same name.
501 DeclarationName LHSName = LHS->getDeclName();
502 DeclarationName RHSName = RHS->getDeclName();
503 if (LHSName != RHSName)
504 return false;
505
506 // And the same signatures.
507 return HasSameVirtualSignature(LHS, RHS);
508}
509
510bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
511 CharUnits OffsetOffset) {
512 // Check if we can reuse an offset.
513 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
514 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
515 return false;
516 }
517
518 // Add the offset.
519 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
520 return true;
521}
522
523CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
524 // Look for an offset.
525 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
526 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
527 return Offsets[I].second;
528 }
529
530 llvm_unreachable("Should always find a vcall offset offset!");
531}
532
533/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
534class VCallAndVBaseOffsetBuilder {
535public:
536 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
537 VBaseOffsetOffsetsMapTy;
538
539private:
540 /// MostDerivedClass - The most derived class for which we're building vcall
541 /// and vbase offsets.
542 const CXXRecordDecl *MostDerivedClass;
543
544 /// LayoutClass - The class we're using for layout information. Will be
545 /// different than the most derived class if we're building a construction
546 /// vtable.
547 const CXXRecordDecl *LayoutClass;
548
549 /// Context - The ASTContext which we will use for layout information.
550 ASTContext &Context;
551
552 /// Components - vcall and vbase offset components
553 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
554 VTableComponentVectorTy Components;
555
556 /// VisitedVirtualBases - Visited virtual bases.
557 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
558
559 /// VCallOffsets - Keeps track of vcall offsets.
560 VCallOffsetMap VCallOffsets;
561
562
563 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
564 /// relative to the address point.
565 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
566
567 /// FinalOverriders - The final overriders of the most derived class.
568 /// (Can be null when we're not building a vtable of the most derived class).
569 const FinalOverriders *Overriders;
570
571 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
572 /// given base subobject.
573 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
574 CharUnits RealBaseOffset);
575
576 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
577 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
578
579 /// AddVBaseOffsets - Add vbase offsets for the given class.
580 void AddVBaseOffsets(const CXXRecordDecl *Base,
581 CharUnits OffsetInLayoutClass);
582
583 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
584 /// chars, relative to the vtable address point.
585 CharUnits getCurrentOffsetOffset() const;
586
587public:
588 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
589 const CXXRecordDecl *LayoutClass,
590 const FinalOverriders *Overriders,
591 BaseSubobject Base, bool BaseIsVirtual,
592 CharUnits OffsetInLayoutClass)
593 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
594 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
595
596 // Add vcall and vbase offsets.
597 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
598 }
599
600 /// Methods for iterating over the components.
601 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
602 const_iterator components_begin() const { return Components.rbegin(); }
603 const_iterator components_end() const { return Components.rend(); }
604
605 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
606 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
607 return VBaseOffsetOffsets;
608 }
609};
610
611void
612VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
613 bool BaseIsVirtual,
614 CharUnits RealBaseOffset) {
615 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
616
617 // Itanium C++ ABI 2.5.2:
618 // ..in classes sharing a virtual table with a primary base class, the vcall
619 // and vbase offsets added by the derived class all come before the vcall
620 // and vbase offsets required by the base class, so that the latter may be
621 // laid out as required by the base class without regard to additions from
622 // the derived class(es).
623
624 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
625 // emit them for the primary base first).
626 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
627 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
628
629 CharUnits PrimaryBaseOffset;
630
631 // Get the base offset of the primary base.
632 if (PrimaryBaseIsVirtual) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000633 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000634 "Primary vbase should have a zero offset!");
635
636 const ASTRecordLayout &MostDerivedClassLayout =
637 Context.getASTRecordLayout(MostDerivedClass);
638
639 PrimaryBaseOffset =
640 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
641 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000642 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000643 "Primary base should have a zero offset!");
644
645 PrimaryBaseOffset = Base.getBaseOffset();
646 }
647
648 AddVCallAndVBaseOffsets(
649 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
650 PrimaryBaseIsVirtual, RealBaseOffset);
651 }
652
653 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
654
655 // We only want to add vcall offsets for virtual bases.
656 if (BaseIsVirtual)
657 AddVCallOffsets(Base, RealBaseOffset);
658}
659
660CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
661 // OffsetIndex is the index of this vcall or vbase offset, relative to the
662 // vtable address point. (We subtract 3 to account for the information just
663 // above the address point, the RTTI info, the offset to top, and the
664 // vcall offset itself).
665 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
666
667 CharUnits PointerWidth =
668 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
669 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
670 return OffsetOffset;
671}
672
673void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
674 CharUnits VBaseOffset) {
675 const CXXRecordDecl *RD = Base.getBase();
676 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
677
678 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
679
680 // Handle the primary base first.
681 // We only want to add vcall offsets if the base is non-virtual; a virtual
682 // primary base will have its vcall and vbase offsets emitted already.
683 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
684 // Get the base offset of the primary base.
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000685 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000686 "Primary base should have a zero offset!");
687
688 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
689 VBaseOffset);
690 }
691
692 // Add the vcall offsets.
693 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
694 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000695 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000696
697 if (!MD->isVirtual())
698 continue;
699
700 CharUnits OffsetOffset = getCurrentOffsetOffset();
701
702 // Don't add a vcall offset if we already have one for this member function
703 // signature.
704 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
705 continue;
706
707 CharUnits Offset = CharUnits::Zero();
708
709 if (Overriders) {
710 // Get the final overrider.
711 FinalOverriders::OverriderInfo Overrider =
712 Overriders->getOverrider(MD, Base.getBaseOffset());
713
714 /// The vcall offset is the offset from the virtual base to the object
715 /// where the function was overridden.
716 Offset = Overrider.Offset - VBaseOffset;
717 }
718
719 Components.push_back(
720 VTableComponent::MakeVCallOffset(Offset));
721 }
722
723 // And iterate over all non-virtual bases (ignoring the primary base).
724 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
725 E = RD->bases_end(); I != E; ++I) {
726
727 if (I->isVirtual())
728 continue;
729
730 const CXXRecordDecl *BaseDecl =
731 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
732 if (BaseDecl == PrimaryBase)
733 continue;
734
735 // Get the base offset of this base.
736 CharUnits BaseOffset = Base.getBaseOffset() +
737 Layout.getBaseClassOffset(BaseDecl);
738
739 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
740 VBaseOffset);
741 }
742}
743
744void
745VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
746 CharUnits OffsetInLayoutClass) {
747 const ASTRecordLayout &LayoutClassLayout =
748 Context.getASTRecordLayout(LayoutClass);
749
750 // Add vbase offsets.
751 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
752 E = RD->bases_end(); I != E; ++I) {
753 const CXXRecordDecl *BaseDecl =
754 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
755
756 // Check if this is a virtual base that we haven't visited before.
757 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
758 CharUnits Offset =
759 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
760
761 // Add the vbase offset offset.
762 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
763 "vbase offset offset already exists!");
764
765 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
766 VBaseOffsetOffsets.insert(
767 std::make_pair(BaseDecl, VBaseOffsetOffset));
768
769 Components.push_back(
770 VTableComponent::MakeVBaseOffset(Offset));
771 }
772
773 // Check the base class looking for more vbase offsets.
774 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
775 }
776}
777
778/// VTableBuilder - Class for building vtable layout information.
779class VTableBuilder {
780public:
781 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
782 /// primary bases.
783 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
784 PrimaryBasesSetVectorTy;
785
786 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
787 VBaseOffsetOffsetsMapTy;
788
789 typedef llvm::DenseMap<BaseSubobject, uint64_t>
790 AddressPointsMapTy;
791
792private:
793 /// VTables - Global vtable information.
794 VTableContext &VTables;
795
796 /// MostDerivedClass - The most derived class for which we're building this
797 /// vtable.
798 const CXXRecordDecl *MostDerivedClass;
799
800 /// MostDerivedClassOffset - If we're building a construction vtable, this
801 /// holds the offset from the layout class to the most derived class.
802 const CharUnits MostDerivedClassOffset;
803
804 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
805 /// base. (This only makes sense when building a construction vtable).
806 bool MostDerivedClassIsVirtual;
807
808 /// LayoutClass - The class we're using for layout information. Will be
809 /// different than the most derived class if we're building a construction
810 /// vtable.
811 const CXXRecordDecl *LayoutClass;
812
813 /// Context - The ASTContext which we will use for layout information.
814 ASTContext &Context;
815
816 /// FinalOverriders - The final overriders of the most derived class.
817 const FinalOverriders Overriders;
818
819 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
820 /// bases in this vtable.
821 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
822
823 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
824 /// the most derived class.
825 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
826
827 /// Components - The components of the vtable being built.
828 SmallVector<VTableComponent, 64> Components;
829
830 /// AddressPoints - Address points for the vtable being built.
831 AddressPointsMapTy AddressPoints;
832
833 /// MethodInfo - Contains information about a method in a vtable.
834 /// (Used for computing 'this' pointer adjustment thunks.
835 struct MethodInfo {
836 /// BaseOffset - The base offset of this method.
837 const CharUnits BaseOffset;
838
839 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
840 /// method.
841 const CharUnits BaseOffsetInLayoutClass;
842
843 /// VTableIndex - The index in the vtable that this method has.
844 /// (For destructors, this is the index of the complete destructor).
845 const uint64_t VTableIndex;
846
847 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
848 uint64_t VTableIndex)
849 : BaseOffset(BaseOffset),
850 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851 VTableIndex(VTableIndex) { }
852
853 MethodInfo()
854 : BaseOffset(CharUnits::Zero()),
855 BaseOffsetInLayoutClass(CharUnits::Zero()),
856 VTableIndex(0) { }
857 };
858
859 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
860
861 /// MethodInfoMap - The information for all methods in the vtable we're
862 /// currently building.
863 MethodInfoMapTy MethodInfoMap;
864
865 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
866
867 /// VTableThunks - The thunks by vtable index in the vtable currently being
868 /// built.
869 VTableThunksMapTy VTableThunks;
870
871 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
872 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
873
874 /// Thunks - A map that contains all the thunks needed for all methods in the
875 /// most derived class for which the vtable is currently being built.
876 ThunksMapTy Thunks;
877
878 /// AddThunk - Add a thunk for the given method.
879 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
880
881 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
882 /// part of the vtable we're currently building.
883 void ComputeThisAdjustments();
884
885 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
886
887 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
888 /// some other base.
889 VisitedVirtualBasesSetTy PrimaryVirtualBases;
890
891 /// ComputeReturnAdjustment - Compute the return adjustment given a return
892 /// adjustment base offset.
893 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
894
895 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
896 /// the 'this' pointer from the base subobject to the derived subobject.
897 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
898 BaseSubobject Derived) const;
899
900 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
901 /// given virtual member function, its offset in the layout class and its
902 /// final overrider.
903 ThisAdjustment
904 ComputeThisAdjustment(const CXXMethodDecl *MD,
905 CharUnits BaseOffsetInLayoutClass,
906 FinalOverriders::OverriderInfo Overrider);
907
908 /// AddMethod - Add a single virtual member function to the vtable
909 /// components vector.
910 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
911
912 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
913 /// part of the vtable.
914 ///
915 /// Itanium C++ ABI 2.5.2:
916 ///
917 /// struct A { virtual void f(); };
918 /// struct B : virtual public A { int i; };
919 /// struct C : virtual public A { int j; };
920 /// struct D : public B, public C {};
921 ///
922 /// When B and C are declared, A is a primary base in each case, so although
923 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
924 /// adjustment is required and no thunk is generated. However, inside D
925 /// objects, A is no longer a primary base of C, so if we allowed calls to
926 /// C::f() to use the copy of A's vtable in the C subobject, we would need
927 /// to adjust this from C* to B::A*, which would require a third-party
928 /// thunk. Since we require that a call to C::f() first convert to A*,
929 /// C-in-D's copy of A's vtable is never referenced, so this is not
930 /// necessary.
931 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
932 CharUnits BaseOffsetInLayoutClass,
933 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
934 CharUnits FirstBaseOffsetInLayoutClass) const;
935
936
937 /// AddMethods - Add the methods of this base subobject and all its
938 /// primary bases to the vtable components vector.
939 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
940 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
941 CharUnits FirstBaseOffsetInLayoutClass,
942 PrimaryBasesSetVectorTy &PrimaryBases);
943
944 // LayoutVTable - Layout the vtable for the given base class, including its
945 // secondary vtables and any vtables for virtual bases.
946 void LayoutVTable();
947
948 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
949 /// given base subobject, as well as all its secondary vtables.
950 ///
951 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
952 /// or a direct or indirect base of a virtual base.
953 ///
954 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
955 /// in the layout class.
956 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
957 bool BaseIsMorallyVirtual,
958 bool BaseIsVirtualInLayoutClass,
959 CharUnits OffsetInLayoutClass);
960
961 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
962 /// subobject.
963 ///
964 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
965 /// or a direct or indirect base of a virtual base.
966 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
967 CharUnits OffsetInLayoutClass);
968
969 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
970 /// class hierarchy.
971 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
972 CharUnits OffsetInLayoutClass,
973 VisitedVirtualBasesSetTy &VBases);
974
975 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
976 /// given base (excluding any primary bases).
977 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
978 VisitedVirtualBasesSetTy &VBases);
979
980 /// isBuildingConstructionVTable - Return whether this vtable builder is
981 /// building a construction vtable.
982 bool isBuildingConstructorVTable() const {
983 return MostDerivedClass != LayoutClass;
984 }
985
986public:
987 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
988 CharUnits MostDerivedClassOffset,
989 bool MostDerivedClassIsVirtual, const
990 CXXRecordDecl *LayoutClass)
991 : VTables(VTables), MostDerivedClass(MostDerivedClass),
992 MostDerivedClassOffset(MostDerivedClassOffset),
993 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
994 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
995 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
996
997 LayoutVTable();
998
David Blaikie4e4d0842012-03-11 07:00:24 +0000999 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +00001000 dumpLayout(llvm::errs());
1001 }
1002
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001003 bool isMicrosoftABI() const {
1004 return VTables.isMicrosoftABI();
1005 }
1006
Peter Collingbourne24018462011-09-26 01:57:12 +00001007 uint64_t getNumThunks() const {
1008 return Thunks.size();
1009 }
1010
1011 ThunksMapTy::const_iterator thunks_begin() const {
1012 return Thunks.begin();
1013 }
1014
1015 ThunksMapTy::const_iterator thunks_end() const {
1016 return Thunks.end();
1017 }
1018
1019 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1020 return VBaseOffsetOffsets;
1021 }
1022
1023 const AddressPointsMapTy &getAddressPoints() const {
1024 return AddressPoints;
1025 }
1026
1027 /// getNumVTableComponents - Return the number of components in the vtable
1028 /// currently built.
1029 uint64_t getNumVTableComponents() const {
1030 return Components.size();
1031 }
1032
1033 const VTableComponent *vtable_component_begin() const {
1034 return Components.begin();
1035 }
1036
1037 const VTableComponent *vtable_component_end() const {
1038 return Components.end();
1039 }
1040
1041 AddressPointsMapTy::const_iterator address_points_begin() const {
1042 return AddressPoints.begin();
1043 }
1044
1045 AddressPointsMapTy::const_iterator address_points_end() const {
1046 return AddressPoints.end();
1047 }
1048
1049 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1050 return VTableThunks.begin();
1051 }
1052
1053 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1054 return VTableThunks.end();
1055 }
1056
1057 /// dumpLayout - Dump the vtable layout.
1058 void dumpLayout(raw_ostream&);
1059};
1060
1061void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1062 assert(!isBuildingConstructorVTable() &&
1063 "Can't add thunks for construction vtable");
1064
1065 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1066
1067 // Check if we have this thunk already.
1068 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1069 ThunksVector.end())
1070 return;
1071
1072 ThunksVector.push_back(Thunk);
1073}
1074
1075typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1076
1077/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1078/// the overridden methods that the function decl overrides.
1079static void
1080ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1081 OverriddenMethodsSetTy& OverriddenMethods) {
1082 assert(MD->isVirtual() && "Method is not virtual!");
1083
1084 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1085 E = MD->end_overridden_methods(); I != E; ++I) {
1086 const CXXMethodDecl *OverriddenMD = *I;
1087
1088 OverriddenMethods.insert(OverriddenMD);
1089
1090 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1091 }
1092}
1093
1094void VTableBuilder::ComputeThisAdjustments() {
1095 // Now go through the method info map and see if any of the methods need
1096 // 'this' pointer adjustments.
1097 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1098 E = MethodInfoMap.end(); I != E; ++I) {
1099 const CXXMethodDecl *MD = I->first;
1100 const MethodInfo &MethodInfo = I->second;
1101
1102 // Ignore adjustments for unused function pointers.
1103 uint64_t VTableIndex = MethodInfo.VTableIndex;
1104 if (Components[VTableIndex].getKind() ==
1105 VTableComponent::CK_UnusedFunctionPointer)
1106 continue;
1107
1108 // Get the final overrider for this method.
1109 FinalOverriders::OverriderInfo Overrider =
1110 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1111
1112 // Check if we need an adjustment at all.
1113 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1114 // When a return thunk is needed by a derived class that overrides a
1115 // virtual base, gcc uses a virtual 'this' adjustment as well.
1116 // While the thunk itself might be needed by vtables in subclasses or
1117 // in construction vtables, there doesn't seem to be a reason for using
1118 // the thunk in this vtable. Still, we do so to match gcc.
1119 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1120 continue;
1121 }
1122
1123 ThisAdjustment ThisAdjustment =
1124 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1125
1126 if (ThisAdjustment.isEmpty())
1127 continue;
1128
1129 // Add it.
1130 VTableThunks[VTableIndex].This = ThisAdjustment;
1131
1132 if (isa<CXXDestructorDecl>(MD)) {
1133 // Add an adjustment for the deleting destructor as well.
1134 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1135 }
1136 }
1137
1138 /// Clear the method info map.
1139 MethodInfoMap.clear();
1140
1141 if (isBuildingConstructorVTable()) {
1142 // We don't need to store thunk information for construction vtables.
1143 return;
1144 }
1145
1146 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1147 E = VTableThunks.end(); I != E; ++I) {
1148 const VTableComponent &Component = Components[I->first];
1149 const ThunkInfo &Thunk = I->second;
1150 const CXXMethodDecl *MD;
1151
1152 switch (Component.getKind()) {
1153 default:
1154 llvm_unreachable("Unexpected vtable component kind!");
1155 case VTableComponent::CK_FunctionPointer:
1156 MD = Component.getFunctionDecl();
1157 break;
1158 case VTableComponent::CK_CompleteDtorPointer:
1159 MD = Component.getDestructorDecl();
1160 break;
1161 case VTableComponent::CK_DeletingDtorPointer:
1162 // We've already added the thunk when we saw the complete dtor pointer.
1163 continue;
1164 }
1165
1166 if (MD->getParent() == MostDerivedClass)
1167 AddThunk(MD, Thunk);
1168 }
1169}
1170
1171ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1172 ReturnAdjustment Adjustment;
1173
1174 if (!Offset.isEmpty()) {
1175 if (Offset.VirtualBase) {
1176 // Get the virtual base offset offset.
1177 if (Offset.DerivedClass == MostDerivedClass) {
1178 // We can get the offset offset directly from our map.
1179 Adjustment.VBaseOffsetOffset =
1180 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1181 } else {
1182 Adjustment.VBaseOffsetOffset =
1183 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1184 Offset.VirtualBase).getQuantity();
1185 }
1186 }
1187
1188 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1189 }
1190
1191 return Adjustment;
1192}
1193
1194BaseOffset
1195VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1196 BaseSubobject Derived) const {
1197 const CXXRecordDecl *BaseRD = Base.getBase();
1198 const CXXRecordDecl *DerivedRD = Derived.getBase();
1199
1200 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1201 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1202
Benjamin Kramer922cec22013-02-03 18:55:34 +00001203 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +00001204 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +00001205
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
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001299 // FIXME: Should probably add a layer of abstraction for vtable generation.
1300 if (!isMicrosoftABI()) {
1301 // Add both the complete destructor and the deleting destructor.
1302 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1303 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1304 } else {
1305 // Add only one destructor in MS mode.
1306 // FIXME: The virtual destructors are handled differently in MS ABI,
1307 // we should add such a support later. For now, put the complete
1308 // destructor into the vftable just to make its layout right.
1309 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1310 }
Peter Collingbourne24018462011-09-26 01:57:12 +00001311 } else {
1312 // Add the return adjustment if necessary.
1313 if (!ReturnAdjustment.isEmpty())
1314 VTableThunks[Components.size()].Return = ReturnAdjustment;
1315
1316 // Add the function.
1317 Components.push_back(VTableComponent::MakeFunction(MD));
1318 }
1319}
1320
1321/// OverridesIndirectMethodInBase - Return whether the given member function
1322/// overrides any methods in the set of given bases.
1323/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1324/// For example, if we have:
1325///
1326/// struct A { virtual void f(); }
1327/// struct B : A { virtual void f(); }
1328/// struct C : B { virtual void f(); }
1329///
1330/// OverridesIndirectMethodInBase will return true if given C::f as the method
1331/// and { A } as the set of bases.
1332static bool
1333OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1334 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1335 if (Bases.count(MD->getParent()))
1336 return true;
1337
1338 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1339 E = MD->end_overridden_methods(); I != E; ++I) {
1340 const CXXMethodDecl *OverriddenMD = *I;
1341
1342 // Check "indirect overriders".
1343 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1344 return true;
1345 }
1346
1347 return false;
1348}
1349
1350bool
1351VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1352 CharUnits BaseOffsetInLayoutClass,
1353 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1354 CharUnits FirstBaseOffsetInLayoutClass) const {
1355 // If the base and the first base in the primary base chain have the same
1356 // offsets, then this overrider will be used.
1357 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1358 return true;
1359
1360 // We know now that Base (or a direct or indirect base of it) is a primary
1361 // base in part of the class hierarchy, but not a primary base in the most
1362 // derived class.
1363
1364 // If the overrider is the first base in the primary base chain, we know
1365 // that the overrider will be used.
1366 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1367 return true;
1368
1369 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1370
1371 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1372 PrimaryBases.insert(RD);
1373
1374 // Now traverse the base chain, starting with the first base, until we find
1375 // the base that is no longer a primary base.
1376 while (true) {
1377 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1378 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1379
1380 if (!PrimaryBase)
1381 break;
1382
1383 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001384 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001385 "Primary base should always be at offset 0!");
1386
1387 const ASTRecordLayout &LayoutClassLayout =
1388 Context.getASTRecordLayout(LayoutClass);
1389
1390 // Now check if this is the primary base that is not a primary base in the
1391 // most derived class.
1392 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1393 FirstBaseOffsetInLayoutClass) {
1394 // We found it, stop walking the chain.
1395 break;
1396 }
1397 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001398 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001399 "Primary base should always be at offset 0!");
1400 }
1401
1402 if (!PrimaryBases.insert(PrimaryBase))
1403 llvm_unreachable("Found a duplicate primary base!");
1404
1405 RD = PrimaryBase;
1406 }
1407
1408 // If the final overrider is an override of one of the primary bases,
1409 // then we know that it will be used.
1410 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1411}
1412
1413/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1414/// from the nearest base. Returns null if no method was found.
1415static const CXXMethodDecl *
1416FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1417 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1418 OverriddenMethodsSetTy OverriddenMethods;
1419 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1420
1421 for (int I = Bases.size(), E = 0; I != E; --I) {
1422 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1423
1424 // Now check the overriden methods.
1425 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1426 E = OverriddenMethods.end(); I != E; ++I) {
1427 const CXXMethodDecl *OverriddenMD = *I;
1428
1429 // We found our overridden method.
1430 if (OverriddenMD->getParent() == PrimaryBase)
1431 return OverriddenMD;
1432 }
1433 }
1434
1435 return 0;
1436}
1437
1438void
1439VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1440 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1441 CharUnits FirstBaseOffsetInLayoutClass,
1442 PrimaryBasesSetVectorTy &PrimaryBases) {
1443 const CXXRecordDecl *RD = Base.getBase();
1444 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1445
1446 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1447 CharUnits PrimaryBaseOffset;
1448 CharUnits PrimaryBaseOffsetInLayoutClass;
1449 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001450 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001451 "Primary vbase should have a zero offset!");
1452
1453 const ASTRecordLayout &MostDerivedClassLayout =
1454 Context.getASTRecordLayout(MostDerivedClass);
1455
1456 PrimaryBaseOffset =
1457 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1458
1459 const ASTRecordLayout &LayoutClassLayout =
1460 Context.getASTRecordLayout(LayoutClass);
1461
1462 PrimaryBaseOffsetInLayoutClass =
1463 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1464 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001465 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001466 "Primary base should have a zero offset!");
1467
1468 PrimaryBaseOffset = Base.getBaseOffset();
1469 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1470 }
1471
1472 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1473 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1474 FirstBaseOffsetInLayoutClass, PrimaryBases);
1475
1476 if (!PrimaryBases.insert(PrimaryBase))
1477 llvm_unreachable("Found a duplicate primary base!");
1478 }
1479
1480 // Now go through all virtual member functions and add them.
1481 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1482 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001483 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001484
1485 if (!MD->isVirtual())
1486 continue;
1487
1488 // Get the final overrider.
1489 FinalOverriders::OverriderInfo Overrider =
1490 Overriders.getOverrider(MD, Base.getBaseOffset());
1491
1492 // Check if this virtual member function overrides a method in a primary
1493 // base. If this is the case, and the return type doesn't require adjustment
1494 // then we can just use the member function from the primary base.
1495 if (const CXXMethodDecl *OverriddenMD =
1496 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1497 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1498 OverriddenMD).isEmpty()) {
1499 // Replace the method info of the overridden method with our own
1500 // method.
1501 assert(MethodInfoMap.count(OverriddenMD) &&
1502 "Did not find the overridden method!");
1503 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1504
1505 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1506 OverriddenMethodInfo.VTableIndex);
1507
1508 assert(!MethodInfoMap.count(MD) &&
1509 "Should not have method info for this method yet!");
1510
1511 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1512 MethodInfoMap.erase(OverriddenMD);
1513
1514 // If the overridden method exists in a virtual base class or a direct
1515 // or indirect base class of a virtual base class, we need to emit a
1516 // thunk if we ever have a class hierarchy where the base class is not
1517 // a primary base in the complete object.
1518 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1519 // Compute the this adjustment.
1520 ThisAdjustment ThisAdjustment =
1521 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1522 Overrider);
1523
1524 if (ThisAdjustment.VCallOffsetOffset &&
1525 Overrider.Method->getParent() == MostDerivedClass) {
1526
1527 // There's no return adjustment from OverriddenMD and MD,
1528 // but that doesn't mean there isn't one between MD and
1529 // the final overrider.
1530 BaseOffset ReturnAdjustmentOffset =
1531 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1532 ReturnAdjustment ReturnAdjustment =
1533 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1534
1535 // This is a virtual thunk for the most derived class, add it.
1536 AddThunk(Overrider.Method,
1537 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1538 }
1539 }
1540
1541 continue;
1542 }
1543 }
1544
1545 // Insert the method info for this method.
1546 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1547 Components.size());
1548
1549 assert(!MethodInfoMap.count(MD) &&
1550 "Should not have method info for this method yet!");
1551 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1552
1553 // Check if this overrider is going to be used.
1554 const CXXMethodDecl *OverriderMD = Overrider.Method;
1555 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1556 FirstBaseInPrimaryBaseChain,
1557 FirstBaseOffsetInLayoutClass)) {
1558 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1559 continue;
1560 }
1561
1562 // Check if this overrider needs a return adjustment.
1563 // We don't want to do this for pure virtual member functions.
1564 BaseOffset ReturnAdjustmentOffset;
1565 if (!OverriderMD->isPure()) {
1566 ReturnAdjustmentOffset =
1567 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1568 }
1569
1570 ReturnAdjustment ReturnAdjustment =
1571 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1572
1573 AddMethod(Overrider.Method, ReturnAdjustment);
1574 }
1575}
1576
1577void VTableBuilder::LayoutVTable() {
1578 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1579 CharUnits::Zero()),
1580 /*BaseIsMorallyVirtual=*/false,
1581 MostDerivedClassIsVirtual,
1582 MostDerivedClassOffset);
1583
1584 VisitedVirtualBasesSetTy VBases;
1585
1586 // Determine the primary virtual bases.
1587 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1588 VBases);
1589 VBases.clear();
1590
1591 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1592
1593 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001594 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001595 if (IsAppleKext)
1596 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1597}
1598
1599void
1600VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1601 bool BaseIsMorallyVirtual,
1602 bool BaseIsVirtualInLayoutClass,
1603 CharUnits OffsetInLayoutClass) {
1604 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1605
1606 // Add vcall and vbase offsets for this vtable.
1607 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1608 Base, BaseIsVirtualInLayoutClass,
1609 OffsetInLayoutClass);
1610 Components.append(Builder.components_begin(), Builder.components_end());
1611
1612 // Check if we need to add these vcall offsets.
1613 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1614 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1615
1616 if (VCallOffsets.empty())
1617 VCallOffsets = Builder.getVCallOffsets();
1618 }
1619
1620 // If we're laying out the most derived class we want to keep track of the
1621 // virtual base class offset offsets.
1622 if (Base.getBase() == MostDerivedClass)
1623 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1624
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001625 // FIXME: Should probably add a layer of abstraction for vtable generation.
1626 if (!isMicrosoftABI()) {
1627 // Add the offset to top.
1628 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1629 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1630
1631 // Next, add the RTTI.
1632 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1633 } else {
1634 // FIXME: unclear what to do with RTTI in MS ABI as emitting it anywhere
1635 // breaks the vftable layout. Just skip RTTI for now, can't mangle anyway.
1636 }
1637
Peter Collingbourne24018462011-09-26 01:57:12 +00001638 uint64_t AddressPoint = Components.size();
1639
1640 // Now go through all virtual member functions and add them.
1641 PrimaryBasesSetVectorTy PrimaryBases;
1642 AddMethods(Base, OffsetInLayoutClass,
1643 Base.getBase(), OffsetInLayoutClass,
1644 PrimaryBases);
1645
1646 // Compute 'this' pointer adjustments.
1647 ComputeThisAdjustments();
1648
1649 // Add all address points.
1650 const CXXRecordDecl *RD = Base.getBase();
1651 while (true) {
1652 AddressPoints.insert(std::make_pair(
1653 BaseSubobject(RD, OffsetInLayoutClass),
1654 AddressPoint));
1655
1656 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1657 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1658
1659 if (!PrimaryBase)
1660 break;
1661
1662 if (Layout.isPrimaryBaseVirtual()) {
1663 // Check if this virtual primary base is a primary base in the layout
1664 // class. If it's not, we don't want to add it.
1665 const ASTRecordLayout &LayoutClassLayout =
1666 Context.getASTRecordLayout(LayoutClass);
1667
1668 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1669 OffsetInLayoutClass) {
1670 // We don't want to add this class (or any of its primary bases).
1671 break;
1672 }
1673 }
1674
1675 RD = PrimaryBase;
1676 }
1677
1678 // Layout secondary vtables.
1679 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1680}
1681
1682void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1683 bool BaseIsMorallyVirtual,
1684 CharUnits OffsetInLayoutClass) {
1685 // Itanium C++ ABI 2.5.2:
1686 // Following the primary virtual table of a derived class are secondary
1687 // virtual tables for each of its proper base classes, except any primary
1688 // base(s) with which it shares its primary virtual table.
1689
1690 const CXXRecordDecl *RD = Base.getBase();
1691 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1692 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1693
1694 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1695 E = RD->bases_end(); I != E; ++I) {
1696 // Ignore virtual bases, we'll emit them later.
1697 if (I->isVirtual())
1698 continue;
1699
1700 const CXXRecordDecl *BaseDecl =
1701 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1702
1703 // Ignore bases that don't have a vtable.
1704 if (!BaseDecl->isDynamicClass())
1705 continue;
1706
1707 if (isBuildingConstructorVTable()) {
1708 // Itanium C++ ABI 2.6.4:
1709 // Some of the base class subobjects may not need construction virtual
1710 // tables, which will therefore not be present in the construction
1711 // virtual table group, even though the subobject virtual tables are
1712 // present in the main virtual table group for the complete object.
1713 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1714 continue;
1715 }
1716
1717 // Get the base offset of this base.
1718 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1719 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1720
1721 CharUnits BaseOffsetInLayoutClass =
1722 OffsetInLayoutClass + RelativeBaseOffset;
1723
1724 // Don't emit a secondary vtable for a primary base. We might however want
1725 // to emit secondary vtables for other bases of this base.
1726 if (BaseDecl == PrimaryBase) {
1727 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1728 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1729 continue;
1730 }
1731
1732 // Layout the primary vtable (and any secondary vtables) for this base.
1733 LayoutPrimaryAndSecondaryVTables(
1734 BaseSubobject(BaseDecl, BaseOffset),
1735 BaseIsMorallyVirtual,
1736 /*BaseIsVirtualInLayoutClass=*/false,
1737 BaseOffsetInLayoutClass);
1738 }
1739}
1740
1741void
1742VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1743 CharUnits OffsetInLayoutClass,
1744 VisitedVirtualBasesSetTy &VBases) {
1745 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1746
1747 // Check if this base has a primary base.
1748 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1749
1750 // Check if it's virtual.
1751 if (Layout.isPrimaryBaseVirtual()) {
1752 bool IsPrimaryVirtualBase = true;
1753
1754 if (isBuildingConstructorVTable()) {
1755 // Check if the base is actually a primary base in the class we use for
1756 // layout.
1757 const ASTRecordLayout &LayoutClassLayout =
1758 Context.getASTRecordLayout(LayoutClass);
1759
1760 CharUnits PrimaryBaseOffsetInLayoutClass =
1761 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1762
1763 // We know that the base is not a primary base in the layout class if
1764 // the base offsets are different.
1765 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1766 IsPrimaryVirtualBase = false;
1767 }
1768
1769 if (IsPrimaryVirtualBase)
1770 PrimaryVirtualBases.insert(PrimaryBase);
1771 }
1772 }
1773
1774 // Traverse bases, looking for more primary virtual bases.
1775 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1776 E = RD->bases_end(); I != E; ++I) {
1777 const CXXRecordDecl *BaseDecl =
1778 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1779
1780 CharUnits BaseOffsetInLayoutClass;
1781
1782 if (I->isVirtual()) {
1783 if (!VBases.insert(BaseDecl))
1784 continue;
1785
1786 const ASTRecordLayout &LayoutClassLayout =
1787 Context.getASTRecordLayout(LayoutClass);
1788
1789 BaseOffsetInLayoutClass =
1790 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1791 } else {
1792 BaseOffsetInLayoutClass =
1793 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1794 }
1795
1796 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1797 }
1798}
1799
1800void
1801VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1802 VisitedVirtualBasesSetTy &VBases) {
1803 // Itanium C++ ABI 2.5.2:
1804 // Then come the virtual base virtual tables, also in inheritance graph
1805 // order, and again excluding primary bases (which share virtual tables with
1806 // the classes for which they are primary).
1807 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1808 E = RD->bases_end(); I != E; ++I) {
1809 const CXXRecordDecl *BaseDecl =
1810 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1811
1812 // Check if this base needs a vtable. (If it's virtual, not a primary base
1813 // of some other class, and we haven't visited it before).
1814 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1815 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1816 const ASTRecordLayout &MostDerivedClassLayout =
1817 Context.getASTRecordLayout(MostDerivedClass);
1818 CharUnits BaseOffset =
1819 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1820
1821 const ASTRecordLayout &LayoutClassLayout =
1822 Context.getASTRecordLayout(LayoutClass);
1823 CharUnits BaseOffsetInLayoutClass =
1824 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1825
1826 LayoutPrimaryAndSecondaryVTables(
1827 BaseSubobject(BaseDecl, BaseOffset),
1828 /*BaseIsMorallyVirtual=*/true,
1829 /*BaseIsVirtualInLayoutClass=*/true,
1830 BaseOffsetInLayoutClass);
1831 }
1832
1833 // We only need to check the base for virtual base vtables if it actually
1834 // has virtual bases.
1835 if (BaseDecl->getNumVBases())
1836 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1837 }
1838}
1839
1840/// dumpLayout - Dump the vtable layout.
1841void VTableBuilder::dumpLayout(raw_ostream& Out) {
1842
1843 if (isBuildingConstructorVTable()) {
1844 Out << "Construction vtable for ('";
1845 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1846 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1847 Out << LayoutClass->getQualifiedNameAsString();
1848 } else {
1849 Out << "Vtable for '";
1850 Out << MostDerivedClass->getQualifiedNameAsString();
1851 }
1852 Out << "' (" << Components.size() << " entries).\n";
1853
1854 // Iterate through the address points and insert them into a new map where
1855 // they are keyed by the index and not the base object.
1856 // Since an address point can be shared by multiple subobjects, we use an
1857 // STL multimap.
1858 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1859 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1860 E = AddressPoints.end(); I != E; ++I) {
1861 const BaseSubobject& Base = I->first;
1862 uint64_t Index = I->second;
1863
1864 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1865 }
1866
1867 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1868 uint64_t Index = I;
1869
1870 Out << llvm::format("%4d | ", I);
1871
1872 const VTableComponent &Component = Components[I];
1873
1874 // Dump the component.
1875 switch (Component.getKind()) {
1876
1877 case VTableComponent::CK_VCallOffset:
1878 Out << "vcall_offset ("
1879 << Component.getVCallOffset().getQuantity()
1880 << ")";
1881 break;
1882
1883 case VTableComponent::CK_VBaseOffset:
1884 Out << "vbase_offset ("
1885 << Component.getVBaseOffset().getQuantity()
1886 << ")";
1887 break;
1888
1889 case VTableComponent::CK_OffsetToTop:
1890 Out << "offset_to_top ("
1891 << Component.getOffsetToTop().getQuantity()
1892 << ")";
1893 break;
1894
1895 case VTableComponent::CK_RTTI:
1896 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1897 break;
1898
1899 case VTableComponent::CK_FunctionPointer: {
1900 const CXXMethodDecl *MD = Component.getFunctionDecl();
1901
1902 std::string Str =
1903 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1904 MD);
1905 Out << Str;
1906 if (MD->isPure())
1907 Out << " [pure]";
1908
David Blaikied954ab42012-10-16 20:25:33 +00001909 if (MD->isDeleted())
1910 Out << " [deleted]";
1911
Peter Collingbourne24018462011-09-26 01:57:12 +00001912 ThunkInfo Thunk = VTableThunks.lookup(I);
1913 if (!Thunk.isEmpty()) {
1914 // If this function pointer has a return adjustment, dump it.
1915 if (!Thunk.Return.isEmpty()) {
1916 Out << "\n [return adjustment: ";
1917 Out << Thunk.Return.NonVirtual << " non-virtual";
1918
1919 if (Thunk.Return.VBaseOffsetOffset) {
1920 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1921 Out << " vbase offset offset";
1922 }
1923
1924 Out << ']';
1925 }
1926
1927 // If this function pointer has a 'this' pointer adjustment, dump it.
1928 if (!Thunk.This.isEmpty()) {
1929 Out << "\n [this adjustment: ";
1930 Out << Thunk.This.NonVirtual << " non-virtual";
1931
1932 if (Thunk.This.VCallOffsetOffset) {
1933 Out << ", " << Thunk.This.VCallOffsetOffset;
1934 Out << " vcall offset offset";
1935 }
1936
1937 Out << ']';
1938 }
1939 }
1940
1941 break;
1942 }
1943
1944 case VTableComponent::CK_CompleteDtorPointer:
1945 case VTableComponent::CK_DeletingDtorPointer: {
1946 bool IsComplete =
1947 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1948
1949 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1950
1951 Out << DD->getQualifiedNameAsString();
1952 if (IsComplete)
1953 Out << "() [complete]";
1954 else
1955 Out << "() [deleting]";
1956
1957 if (DD->isPure())
1958 Out << " [pure]";
1959
1960 ThunkInfo Thunk = VTableThunks.lookup(I);
1961 if (!Thunk.isEmpty()) {
1962 // If this destructor has a 'this' pointer adjustment, dump it.
1963 if (!Thunk.This.isEmpty()) {
1964 Out << "\n [this adjustment: ";
1965 Out << Thunk.This.NonVirtual << " non-virtual";
1966
1967 if (Thunk.This.VCallOffsetOffset) {
1968 Out << ", " << Thunk.This.VCallOffsetOffset;
1969 Out << " vcall offset offset";
1970 }
1971
1972 Out << ']';
1973 }
1974 }
1975
1976 break;
1977 }
1978
1979 case VTableComponent::CK_UnusedFunctionPointer: {
1980 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1981
1982 std::string Str =
1983 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1984 MD);
1985 Out << "[unused] " << Str;
1986 if (MD->isPure())
1987 Out << " [pure]";
1988 }
1989
1990 }
1991
1992 Out << '\n';
1993
1994 // Dump the next address point.
1995 uint64_t NextIndex = Index + 1;
1996 if (AddressPointsByIndex.count(NextIndex)) {
1997 if (AddressPointsByIndex.count(NextIndex) == 1) {
1998 const BaseSubobject &Base =
1999 AddressPointsByIndex.find(NextIndex)->second;
2000
2001 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2002 Out << ", " << Base.getBaseOffset().getQuantity();
2003 Out << ") vtable address --\n";
2004 } else {
2005 CharUnits BaseOffset =
2006 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2007
2008 // We store the class names in a set to get a stable order.
2009 std::set<std::string> ClassNames;
2010 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2011 AddressPointsByIndex.lower_bound(NextIndex), E =
2012 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2013 assert(I->second.getBaseOffset() == BaseOffset &&
2014 "Invalid base offset!");
2015 const CXXRecordDecl *RD = I->second.getBase();
2016 ClassNames.insert(RD->getQualifiedNameAsString());
2017 }
2018
2019 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2020 E = ClassNames.end(); I != E; ++I) {
2021 Out << " -- (" << *I;
2022 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2023 }
2024 }
2025 }
2026 }
2027
2028 Out << '\n';
2029
2030 if (isBuildingConstructorVTable())
2031 return;
2032
2033 if (MostDerivedClass->getNumVBases()) {
2034 // We store the virtual base class names and their offsets in a map to get
2035 // a stable order.
2036
2037 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2038 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2039 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2040 std::string ClassName = I->first->getQualifiedNameAsString();
2041 CharUnits OffsetOffset = I->second;
2042 ClassNamesAndOffsets.insert(
2043 std::make_pair(ClassName, OffsetOffset));
2044 }
2045
2046 Out << "Virtual base offset offsets for '";
2047 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2048 Out << ClassNamesAndOffsets.size();
2049 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2050
2051 for (std::map<std::string, CharUnits>::const_iterator I =
2052 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2053 I != E; ++I)
2054 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2055
2056 Out << "\n";
2057 }
2058
2059 if (!Thunks.empty()) {
2060 // We store the method names in a map to get a stable order.
2061 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2062
2063 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2064 I != E; ++I) {
2065 const CXXMethodDecl *MD = I->first;
2066 std::string MethodName =
2067 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2068 MD);
2069
2070 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2071 }
2072
2073 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2074 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2075 I != E; ++I) {
2076 const std::string &MethodName = I->first;
2077 const CXXMethodDecl *MD = I->second;
2078
2079 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2080 std::sort(ThunksVector.begin(), ThunksVector.end());
2081
2082 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2083 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2084
2085 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2086 const ThunkInfo &Thunk = ThunksVector[I];
2087
2088 Out << llvm::format("%4d | ", I);
2089
2090 // If this function pointer has a return pointer adjustment, dump it.
2091 if (!Thunk.Return.isEmpty()) {
2092 Out << "return adjustment: " << Thunk.This.NonVirtual;
2093 Out << " non-virtual";
2094 if (Thunk.Return.VBaseOffsetOffset) {
2095 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2096 Out << " vbase offset offset";
2097 }
2098
2099 if (!Thunk.This.isEmpty())
2100 Out << "\n ";
2101 }
2102
2103 // If this function pointer has a 'this' pointer adjustment, dump it.
2104 if (!Thunk.This.isEmpty()) {
2105 Out << "this adjustment: ";
2106 Out << Thunk.This.NonVirtual << " non-virtual";
2107
2108 if (Thunk.This.VCallOffsetOffset) {
2109 Out << ", " << Thunk.This.VCallOffsetOffset;
2110 Out << " vcall offset offset";
2111 }
2112 }
2113
2114 Out << '\n';
2115 }
2116
2117 Out << '\n';
2118 }
2119 }
2120
2121 // Compute the vtable indices for all the member functions.
2122 // Store them in a map keyed by the index so we'll get a sorted table.
2123 std::map<uint64_t, std::string> IndicesMap;
2124
2125 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2126 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002127 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002128
2129 // We only want virtual member functions.
2130 if (!MD->isVirtual())
2131 continue;
2132
2133 std::string MethodName =
2134 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2135 MD);
2136
2137 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002138 // FIXME: Should add a layer of abstraction for vtable generation.
2139 if (!isMicrosoftABI()) {
2140 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))]
2141 = MethodName + " [complete]";
2142 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2143 = MethodName + " [deleting]";
2144 } else {
2145 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))]
2146 = MethodName;
2147 }
Peter Collingbourne24018462011-09-26 01:57:12 +00002148 } else {
2149 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2150 }
2151 }
2152
2153 // Print the vtable indices for all the member functions.
2154 if (!IndicesMap.empty()) {
2155 Out << "VTable indices for '";
2156 Out << MostDerivedClass->getQualifiedNameAsString();
2157 Out << "' (" << IndicesMap.size() << " entries).\n";
2158
2159 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2160 E = IndicesMap.end(); I != E; ++I) {
2161 uint64_t VTableIndex = I->first;
2162 const std::string &MethodName = I->second;
2163
Benjamin Kramer79a55012012-03-10 02:06:27 +00002164 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
2165 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002166 }
2167 }
2168
2169 Out << '\n';
2170}
2171
2172}
2173
2174VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2175 const VTableComponent *VTableComponents,
2176 uint64_t NumVTableThunks,
2177 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002178 const AddressPointsMapTy &AddressPoints,
2179 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002180 : NumVTableComponents(NumVTableComponents),
2181 VTableComponents(new VTableComponent[NumVTableComponents]),
2182 NumVTableThunks(NumVTableThunks),
2183 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002184 AddressPoints(AddressPoints),
2185 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002186 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002187 this->VTableComponents.get());
2188 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2189 this->VTableThunks.get());
Peter Collingbourne24018462011-09-26 01:57:12 +00002190}
2191
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002192VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002193
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002194VTableContext::VTableContext(ASTContext &Context)
2195 : Context(Context),
John McCallb8b2c9d2013-01-25 22:30:49 +00002196 IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2197}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002198
Peter Collingbourne24018462011-09-26 01:57:12 +00002199VTableContext::~VTableContext() {
2200 llvm::DeleteContainerSeconds(VTableLayouts);
2201}
2202
2203static void
2204CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2205 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2206 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2207 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2208
2209 if (!PrimaryBase)
2210 return;
2211
2212 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2213
2214 if (!PrimaryBases.insert(PrimaryBase))
2215 llvm_unreachable("Found a duplicate primary base!");
2216}
2217
2218void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2219
2220 // Itanium C++ ABI 2.5.2:
2221 // The order of the virtual function pointers in a virtual table is the
2222 // order of declaration of the corresponding member functions in the class.
2223 //
2224 // There is an entry for any virtual function declared in a class,
2225 // whether it is a new function or overrides a base class function,
2226 // unless it overrides a function from the primary base, and conversion
2227 // between their return types does not require an adjustment.
2228
2229 int64_t CurrentIndex = 0;
2230
2231 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2232 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2233
2234 if (PrimaryBase) {
John McCall5e1cdac2011-10-07 06:10:15 +00002235 assert(PrimaryBase->isCompleteDefinition() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00002236 "Should have the definition decl of the primary base!");
2237
2238 // Since the record decl shares its vtable pointer with the primary base
2239 // we need to start counting at the end of the primary base's vtable.
2240 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2241 }
2242
2243 // Collect all the primary bases, so we can check whether methods override
2244 // a method from the base.
2245 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2246 CollectPrimaryBases(RD, Context, PrimaryBases);
2247
2248 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2249
2250 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2251 e = RD->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002252 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002253
2254 // We only want virtual methods.
2255 if (!MD->isVirtual())
2256 continue;
2257
2258 // Check if this method overrides a method in the primary base.
2259 if (const CXXMethodDecl *OverriddenMD =
2260 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2261 // Check if converting from the return type of the method to the
2262 // return type of the overridden method requires conversion.
2263 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2264 OverriddenMD).isEmpty()) {
2265 // This index is shared between the index in the vtable of the primary
2266 // base class.
2267 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2268 const CXXDestructorDecl *OverriddenDD =
2269 cast<CXXDestructorDecl>(OverriddenMD);
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002270
2271 if (!isMicrosoftABI()) {
2272 // Add both the complete and deleting entries.
2273 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2274 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2275 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2276 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2277 } else {
2278 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2279 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2280 }
Peter Collingbourne24018462011-09-26 01:57:12 +00002281 } else {
2282 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2283 }
2284
2285 // We don't need to add an entry for this method.
2286 continue;
2287 }
2288 }
2289
2290 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2291 if (MD->isImplicit()) {
2292 assert(!ImplicitVirtualDtor &&
2293 "Did already see an implicit virtual dtor!");
2294 ImplicitVirtualDtor = DD;
2295 continue;
2296 }
2297
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002298 if (!isMicrosoftABI()) {
2299 // Add the complete dtor.
2300 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2301
2302 // Add the deleting dtor.
2303 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2304 } else {
2305 // Add only the deleting dtor.
2306 // FIXME: The virtual destructors are handled differently in MS ABI,
2307 // we should add such a support later. For now, put the complete
2308 // destructor into the vftable indices.
2309 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2310 }
Peter Collingbourne24018462011-09-26 01:57:12 +00002311 } else {
2312 // Add the entry.
2313 MethodVTableIndices[MD] = CurrentIndex++;
2314 }
2315 }
2316
2317 if (ImplicitVirtualDtor) {
2318 // Itanium C++ ABI 2.5.2:
2319 // If a class has an implicitly-defined virtual destructor,
2320 // its entries come after the declared virtual function pointers.
2321
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002322 if (isMicrosoftABI()) {
2323 ErrorUnsupported("implicit virtual destructor in the Microsoft ABI",
2324 ImplicitVirtualDtor->getLocation());
2325 }
2326
Peter Collingbourne24018462011-09-26 01:57:12 +00002327 // Add the complete dtor.
2328 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2329 CurrentIndex++;
2330
2331 // Add the deleting dtor.
2332 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2333 CurrentIndex++;
2334 }
2335
2336 NumVirtualFunctionPointers[RD] = CurrentIndex;
2337}
2338
2339uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2340 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2341 NumVirtualFunctionPointers.find(RD);
2342 if (I != NumVirtualFunctionPointers.end())
2343 return I->second;
2344
2345 ComputeMethodVTableIndices(RD);
2346
2347 I = NumVirtualFunctionPointers.find(RD);
2348 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2349 return I->second;
2350}
2351
2352uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2353 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2354 if (I != MethodVTableIndices.end())
2355 return I->second;
2356
2357 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2358
2359 ComputeMethodVTableIndices(RD);
2360
2361 I = MethodVTableIndices.find(GD);
2362 assert(I != MethodVTableIndices.end() && "Did not find index!");
2363 return I->second;
2364}
2365
2366CharUnits
2367VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2368 const CXXRecordDecl *VBase) {
2369 ClassPairTy ClassPair(RD, VBase);
2370
2371 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2372 VirtualBaseClassOffsetOffsets.find(ClassPair);
2373 if (I != VirtualBaseClassOffsetOffsets.end())
2374 return I->second;
2375
2376 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2377 BaseSubobject(RD, CharUnits::Zero()),
2378 /*BaseIsVirtual=*/false,
2379 /*OffsetInLayoutClass=*/CharUnits::Zero());
2380
2381 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2382 Builder.getVBaseOffsetOffsets().begin(),
2383 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2384 // Insert all types.
2385 ClassPairTy ClassPair(RD, I->first);
2386
2387 VirtualBaseClassOffsetOffsets.insert(
2388 std::make_pair(ClassPair, I->second));
2389 }
2390
2391 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2392 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2393
2394 return I->second;
2395}
2396
2397static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2398 SmallVector<VTableLayout::VTableThunkTy, 1>
2399 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2400 std::sort(VTableThunks.begin(), VTableThunks.end());
2401
2402 return new VTableLayout(Builder.getNumVTableComponents(),
2403 Builder.vtable_component_begin(),
2404 VTableThunks.size(),
2405 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002406 Builder.getAddressPoints(),
2407 Builder.isMicrosoftABI());
Peter Collingbourne24018462011-09-26 01:57:12 +00002408}
2409
2410void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2411 const VTableLayout *&Entry = VTableLayouts[RD];
2412
2413 // Check if we've computed this information before.
2414 if (Entry)
2415 return;
2416
2417 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2418 /*MostDerivedClassIsVirtual=*/0, RD);
2419 Entry = CreateVTableLayout(Builder);
2420
2421 // Add the known thunks.
2422 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2423
2424 // If we don't have the vbase information for this class, insert it.
2425 // getVirtualBaseOffsetOffset will compute it separately without computing
2426 // the rest of the vtable related information.
2427 if (!RD->getNumVBases())
2428 return;
2429
2430 const RecordType *VBaseRT =
2431 RD->vbases_begin()->getType()->getAs<RecordType>();
2432 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2433
2434 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2435 return;
2436
2437 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2438 Builder.getVBaseOffsetOffsets().begin(),
2439 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2440 // Insert all types.
2441 ClassPairTy ClassPair(RD, I->first);
2442
2443 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2444 }
2445}
2446
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002447void VTableContext::ErrorUnsupported(StringRef Feature,
2448 SourceLocation Location) {
2449 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2450 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2451 "v-table layout for %0 is not supported yet");
2452 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2453}
2454
Peter Collingbourne24018462011-09-26 01:57:12 +00002455VTableLayout *VTableContext::createConstructionVTableLayout(
2456 const CXXRecordDecl *MostDerivedClass,
2457 CharUnits MostDerivedClassOffset,
2458 bool MostDerivedClassIsVirtual,
2459 const CXXRecordDecl *LayoutClass) {
2460 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2461 MostDerivedClassIsVirtual, LayoutClass);
2462 return CreateVTableLayout(Builder);
2463}