1 //===--- 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"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <algorithm>
22 #include <cstdio>
23
24 using namespace clang;
25
26 #define DUMP_OVERRIDERS 0
27
28 namespace {
29
30 /// BaseOffset - Represents an offset from a derived class to a direct or
31 /// indirect base class.
32 struct 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
BaseOffset__anon4882463e0111::BaseOffset46 BaseOffset() : DerivedClass(0), VirtualBase(0),
47 NonVirtualOffset(CharUnits::Zero()) { }
BaseOffset__anon4882463e0111::BaseOffset48 BaseOffset(const CXXRecordDecl *DerivedClass,
49 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
50 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
51 NonVirtualOffset(NonVirtualOffset) { }
52
isEmpty__anon4882463e0111::BaseOffset53 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.
58 class FinalOverriders {
59 public:
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
OverriderInfo__anon4882463e0111::FinalOverriders::OverriderInfo68 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
69 };
70
71 private:
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
125 public:
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.
getOverrider(const CXXMethodDecl * MD,CharUnits BaseOffset) const132 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.
dump()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
FinalOverriders(const CXXRecordDecl * MostDerivedClass,CharUnits MostDerivedClassOffset,const CXXRecordDecl * LayoutClass)151 FinalOverriders::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
169 // Get the final overriders.
170 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
ComputeBaseOffset(ASTContext & Context,const CXXRecordDecl * DerivedRD,const CXXBasePath & Path)213 static 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
ComputeBaseOffset(ASTContext & Context,const CXXRecordDecl * BaseRD,const CXXRecordDecl * DerivedRD)255 static BaseOffset ComputeBaseOffset(ASTContext &Context,
256 const CXXRecordDecl *BaseRD,
257 const CXXRecordDecl *DerivedRD) {
258 CXXBasePaths Paths(/*FindAmbiguities=*/false,
259 /*RecordPaths=*/true, /*DetectVirtual=*/false);
260
261 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
262 llvm_unreachable("Class must be derived from the passed in base class!");
263
264 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
265 }
266
267 static BaseOffset
ComputeReturnAdjustmentBaseOffset(ASTContext & Context,const CXXMethodDecl * DerivedMD,const CXXMethodDecl * BaseMD)268 ComputeReturnAdjustmentBaseOffset(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
321 void
ComputeBaseOffsets(BaseSubobject Base,bool IsVirtual,CharUnits OffsetInLayoutClass,SubobjectOffsetMapTy & SubobjectOffsets,SubobjectOffsetMapTy & SubobjectLayoutClassOffsets,SubobjectCountMapTy & SubobjectCounts)322 FinalOverriders::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
dump(raw_ostream & Out,BaseSubobject Base,VisitedVirtualBasesSetTy & VisitedVirtualBases)377 void 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) {
412 const CXXMethodDecl *MD = *I;
413
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.
440 struct 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
453 public:
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.
empty__anon4882463e0111::VCallOffsetMap464 bool empty() const { return Offsets.empty(); }
465 };
466
HasSameVirtualSignature(const CXXMethodDecl * LHS,const CXXMethodDecl * RHS)467 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
468 const CXXMethodDecl *RHS) {
469 const FunctionProtoType *LT =
470 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
471 const FunctionProtoType *RT =
472 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
473
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.
480 if (LT->getTypeQuals() != RT->getTypeQuals() ||
481 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
MethodsCanShareVCallOffset(const CXXMethodDecl * LHS,const CXXMethodDecl * RHS)489 bool 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
AddVCallOffset(const CXXMethodDecl * MD,CharUnits OffsetOffset)510 bool 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
getVCallOffsetOffset(const CXXMethodDecl * MD)523 CharUnits 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.
534 class VCallAndVBaseOffsetBuilder {
535 public:
536 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
537 VBaseOffsetOffsetsMapTy;
538
539 private:
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
587 public:
VCallAndVBaseOffsetBuilder(const CXXRecordDecl * MostDerivedClass,const CXXRecordDecl * LayoutClass,const FinalOverriders * Overriders,BaseSubobject Base,bool BaseIsVirtual,CharUnits OffsetInLayoutClass)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;
components_begin() const602 const_iterator components_begin() const { return Components.rbegin(); }
components_end() const603 const_iterator components_end() const { return Components.rend(); }
604
getVCallOffsets() const605 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
getVBaseOffsetOffsets() const606 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
607 return VBaseOffsetOffsets;
608 }
609 };
610
611 void
AddVCallAndVBaseOffsets(BaseSubobject Base,bool BaseIsVirtual,CharUnits RealBaseOffset)612 VCallAndVBaseOffsetBuilder::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) {
633 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
634 "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 {
642 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
643 "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
getCurrentOffsetOffset() const660 CharUnits 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
AddVCallOffsets(BaseSubobject Base,CharUnits VBaseOffset)673 void 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.
685 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
686 "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) {
695 const CXXMethodDecl *MD = *I;
696
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
744 void
AddVBaseOffsets(const CXXRecordDecl * RD,CharUnits OffsetInLayoutClass)745 VCallAndVBaseOffsetBuilder::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.
779 class VTableBuilder {
780 public:
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
792 private:
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
MethodInfo__anon4882463e0111::VTableBuilder::MethodInfo847 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
848 uint64_t VTableIndex)
849 : BaseOffset(BaseOffset),
850 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851 VTableIndex(VTableIndex) { }
852
MethodInfo__anon4882463e0111::VTableBuilder::MethodInfo853 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.
isBuildingConstructorVTable() const982 bool isBuildingConstructorVTable() const {
983 return MostDerivedClass != LayoutClass;
984 }
985
986 public:
VTableBuilder(VTableContext & VTables,const CXXRecordDecl * MostDerivedClass,CharUnits MostDerivedClassOffset,bool MostDerivedClassIsVirtual,const CXXRecordDecl * LayoutClass)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
999 if (Context.getLangOpts().DumpVTableLayouts)
1000 dumpLayout(llvm::errs());
1001 }
1002
isMicrosoftABI() const1003 bool isMicrosoftABI() const {
1004 return VTables.isMicrosoftABI();
1005 }
1006
getNumThunks() const1007 uint64_t getNumThunks() const {
1008 return Thunks.size();
1009 }
1010
thunks_begin() const1011 ThunksMapTy::const_iterator thunks_begin() const {
1012 return Thunks.begin();
1013 }
1014
thunks_end() const1015 ThunksMapTy::const_iterator thunks_end() const {
1016 return Thunks.end();
1017 }
1018
getVBaseOffsetOffsets() const1019 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1020 return VBaseOffsetOffsets;
1021 }
1022
getAddressPoints() const1023 const AddressPointsMapTy &getAddressPoints() const {
1024 return AddressPoints;
1025 }
1026
1027 /// getNumVTableComponents - Return the number of components in the vtable
1028 /// currently built.
getNumVTableComponents() const1029 uint64_t getNumVTableComponents() const {
1030 return Components.size();
1031 }
1032
vtable_component_begin() const1033 const VTableComponent *vtable_component_begin() const {
1034 return Components.begin();
1035 }
1036
vtable_component_end() const1037 const VTableComponent *vtable_component_end() const {
1038 return Components.end();
1039 }
1040
address_points_begin() const1041 AddressPointsMapTy::const_iterator address_points_begin() const {
1042 return AddressPoints.begin();
1043 }
1044
address_points_end() const1045 AddressPointsMapTy::const_iterator address_points_end() const {
1046 return AddressPoints.end();
1047 }
1048
vtable_thunks_begin() const1049 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1050 return VTableThunks.begin();
1051 }
1052
vtable_thunks_end() const1053 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
AddThunk(const CXXMethodDecl * MD,const ThunkInfo & Thunk)1061 void 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
1075 typedef 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.
1079 static void
ComputeAllOverriddenMethods(const CXXMethodDecl * MD,OverriddenMethodsSetTy & OverriddenMethods)1080 ComputeAllOverriddenMethods(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
ComputeThisAdjustments()1094 void 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 // FIXME: check how this works in the Microsoft ABI
1164 // while working on the multiple inheritance patch.
1165 continue;
1166 }
1167
1168 if (MD->getParent() == MostDerivedClass)
1169 AddThunk(MD, Thunk);
1170 }
1171 }
1172
ComputeReturnAdjustment(BaseOffset Offset)1173 ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1174 ReturnAdjustment Adjustment;
1175
1176 if (!Offset.isEmpty()) {
1177 if (Offset.VirtualBase) {
1178 // Get the virtual base offset offset.
1179 if (Offset.DerivedClass == MostDerivedClass) {
1180 // We can get the offset offset directly from our map.
1181 Adjustment.VBaseOffsetOffset =
1182 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1183 } else {
1184 Adjustment.VBaseOffsetOffset =
1185 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1186 Offset.VirtualBase).getQuantity();
1187 }
1188 }
1189
1190 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1191 }
1192
1193 return Adjustment;
1194 }
1195
1196 BaseOffset
ComputeThisAdjustmentBaseOffset(BaseSubobject Base,BaseSubobject Derived) const1197 VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1198 BaseSubobject Derived) const {
1199 const CXXRecordDecl *BaseRD = Base.getBase();
1200 const CXXRecordDecl *DerivedRD = Derived.getBase();
1201
1202 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1203 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1204
1205 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1206 llvm_unreachable("Class must be derived from the passed in base class!");
1207
1208 // We have to go through all the paths, and see which one leads us to the
1209 // right base subobject.
1210 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1211 I != E; ++I) {
1212 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1213
1214 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1215
1216 if (Offset.VirtualBase) {
1217 // If we have a virtual base class, the non-virtual offset is relative
1218 // to the virtual base class offset.
1219 const ASTRecordLayout &LayoutClassLayout =
1220 Context.getASTRecordLayout(LayoutClass);
1221
1222 /// Get the virtual base offset, relative to the most derived class
1223 /// layout.
1224 OffsetToBaseSubobject +=
1225 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1226 } else {
1227 // Otherwise, the non-virtual offset is relative to the derived class
1228 // offset.
1229 OffsetToBaseSubobject += Derived.getBaseOffset();
1230 }
1231
1232 // Check if this path gives us the right base subobject.
1233 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1234 // Since we're going from the base class _to_ the derived class, we'll
1235 // invert the non-virtual offset here.
1236 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1237 return Offset;
1238 }
1239 }
1240
1241 return BaseOffset();
1242 }
1243
1244 ThisAdjustment
ComputeThisAdjustment(const CXXMethodDecl * MD,CharUnits BaseOffsetInLayoutClass,FinalOverriders::OverriderInfo Overrider)1245 VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1246 CharUnits BaseOffsetInLayoutClass,
1247 FinalOverriders::OverriderInfo Overrider) {
1248 // Ignore adjustments for pure virtual member functions.
1249 if (Overrider.Method->isPure())
1250 return ThisAdjustment();
1251
1252 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1253 BaseOffsetInLayoutClass);
1254
1255 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1256 Overrider.Offset);
1257
1258 // Compute the adjustment offset.
1259 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1260 OverriderBaseSubobject);
1261 if (Offset.isEmpty())
1262 return ThisAdjustment();
1263
1264 ThisAdjustment Adjustment;
1265
1266 if (Offset.VirtualBase) {
1267 // Get the vcall offset map for this virtual base.
1268 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1269
1270 if (VCallOffsets.empty()) {
1271 // We don't have vcall offsets for this virtual base, go ahead and
1272 // build them.
1273 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1274 /*FinalOverriders=*/0,
1275 BaseSubobject(Offset.VirtualBase,
1276 CharUnits::Zero()),
1277 /*BaseIsVirtual=*/true,
1278 /*OffsetInLayoutClass=*/
1279 CharUnits::Zero());
1280
1281 VCallOffsets = Builder.getVCallOffsets();
1282 }
1283
1284 Adjustment.VCallOffsetOffset =
1285 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1286 }
1287
1288 // Set the non-virtual part of the adjustment.
1289 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1290
1291 return Adjustment;
1292 }
1293
1294 void
AddMethod(const CXXMethodDecl * MD,ReturnAdjustment ReturnAdjustment)1295 VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1296 ReturnAdjustment ReturnAdjustment) {
1297 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1298 assert(ReturnAdjustment.isEmpty() &&
1299 "Destructor can't have return adjustment!");
1300
1301 // FIXME: Should probably add a layer of abstraction for vtable generation.
1302 if (!isMicrosoftABI()) {
1303 // Add both the complete destructor and the deleting destructor.
1304 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1305 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1306 } else {
1307 // Add the scalar deleting destructor.
1308 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1309 }
1310 } else {
1311 // Add the return adjustment if necessary.
1312 if (!ReturnAdjustment.isEmpty())
1313 VTableThunks[Components.size()].Return = ReturnAdjustment;
1314
1315 // Add the function.
1316 Components.push_back(VTableComponent::MakeFunction(MD));
1317 }
1318 }
1319
1320 /// OverridesIndirectMethodInBase - Return whether the given member function
1321 /// overrides any methods in the set of given bases.
1322 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1323 /// For example, if we have:
1324 ///
1325 /// struct A { virtual void f(); }
1326 /// struct B : A { virtual void f(); }
1327 /// struct C : B { virtual void f(); }
1328 ///
1329 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1330 /// and { A } as the set of bases.
1331 static bool
OverridesIndirectMethodInBases(const CXXMethodDecl * MD,VTableBuilder::PrimaryBasesSetVectorTy & Bases)1332 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1333 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1334 if (Bases.count(MD->getParent()))
1335 return true;
1336
1337 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1338 E = MD->end_overridden_methods(); I != E; ++I) {
1339 const CXXMethodDecl *OverriddenMD = *I;
1340
1341 // Check "indirect overriders".
1342 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1343 return true;
1344 }
1345
1346 return false;
1347 }
1348
1349 bool
IsOverriderUsed(const CXXMethodDecl * Overrider,CharUnits BaseOffsetInLayoutClass,const CXXRecordDecl * FirstBaseInPrimaryBaseChain,CharUnits FirstBaseOffsetInLayoutClass) const1350 VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1351 CharUnits BaseOffsetInLayoutClass,
1352 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1353 CharUnits FirstBaseOffsetInLayoutClass) const {
1354 // If the base and the first base in the primary base chain have the same
1355 // offsets, then this overrider will be used.
1356 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1357 return true;
1358
1359 // We know now that Base (or a direct or indirect base of it) is a primary
1360 // base in part of the class hierarchy, but not a primary base in the most
1361 // derived class.
1362
1363 // If the overrider is the first base in the primary base chain, we know
1364 // that the overrider will be used.
1365 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1366 return true;
1367
1368 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1369
1370 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1371 PrimaryBases.insert(RD);
1372
1373 // Now traverse the base chain, starting with the first base, until we find
1374 // the base that is no longer a primary base.
1375 while (true) {
1376 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1377 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1378
1379 if (!PrimaryBase)
1380 break;
1381
1382 if (Layout.isPrimaryBaseVirtual()) {
1383 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1384 "Primary base should always be at offset 0!");
1385
1386 const ASTRecordLayout &LayoutClassLayout =
1387 Context.getASTRecordLayout(LayoutClass);
1388
1389 // Now check if this is the primary base that is not a primary base in the
1390 // most derived class.
1391 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1392 FirstBaseOffsetInLayoutClass) {
1393 // We found it, stop walking the chain.
1394 break;
1395 }
1396 } else {
1397 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1398 "Primary base should always be at offset 0!");
1399 }
1400
1401 if (!PrimaryBases.insert(PrimaryBase))
1402 llvm_unreachable("Found a duplicate primary base!");
1403
1404 RD = PrimaryBase;
1405 }
1406
1407 // If the final overrider is an override of one of the primary bases,
1408 // then we know that it will be used.
1409 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1410 }
1411
1412 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1413 /// from the nearest base. Returns null if no method was found.
1414 static const CXXMethodDecl *
FindNearestOverriddenMethod(const CXXMethodDecl * MD,VTableBuilder::PrimaryBasesSetVectorTy & Bases)1415 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1416 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1417 OverriddenMethodsSetTy OverriddenMethods;
1418 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1419
1420 for (int I = Bases.size(), E = 0; I != E; --I) {
1421 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1422
1423 // Now check the overriden methods.
1424 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1425 E = OverriddenMethods.end(); I != E; ++I) {
1426 const CXXMethodDecl *OverriddenMD = *I;
1427
1428 // We found our overridden method.
1429 if (OverriddenMD->getParent() == PrimaryBase)
1430 return OverriddenMD;
1431 }
1432 }
1433
1434 return 0;
1435 }
1436
1437 void
AddMethods(BaseSubobject Base,CharUnits BaseOffsetInLayoutClass,const CXXRecordDecl * FirstBaseInPrimaryBaseChain,CharUnits FirstBaseOffsetInLayoutClass,PrimaryBasesSetVectorTy & PrimaryBases)1438 VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1439 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1440 CharUnits FirstBaseOffsetInLayoutClass,
1441 PrimaryBasesSetVectorTy &PrimaryBases) {
1442 const CXXRecordDecl *RD = Base.getBase();
1443 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1444
1445 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1446 CharUnits PrimaryBaseOffset;
1447 CharUnits PrimaryBaseOffsetInLayoutClass;
1448 if (Layout.isPrimaryBaseVirtual()) {
1449 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1450 "Primary vbase should have a zero offset!");
1451
1452 const ASTRecordLayout &MostDerivedClassLayout =
1453 Context.getASTRecordLayout(MostDerivedClass);
1454
1455 PrimaryBaseOffset =
1456 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1457
1458 const ASTRecordLayout &LayoutClassLayout =
1459 Context.getASTRecordLayout(LayoutClass);
1460
1461 PrimaryBaseOffsetInLayoutClass =
1462 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1463 } else {
1464 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1465 "Primary base should have a zero offset!");
1466
1467 PrimaryBaseOffset = Base.getBaseOffset();
1468 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1469 }
1470
1471 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1472 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1473 FirstBaseOffsetInLayoutClass, PrimaryBases);
1474
1475 if (!PrimaryBases.insert(PrimaryBase))
1476 llvm_unreachable("Found a duplicate primary base!");
1477 }
1478
1479 // Now go through all virtual member functions and add them.
1480 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1481 E = RD->method_end(); I != E; ++I) {
1482 const CXXMethodDecl *MD = *I;
1483
1484 if (!MD->isVirtual())
1485 continue;
1486
1487 // Get the final overrider.
1488 FinalOverriders::OverriderInfo Overrider =
1489 Overriders.getOverrider(MD, Base.getBaseOffset());
1490
1491 // Check if this virtual member function overrides a method in a primary
1492 // base. If this is the case, and the return type doesn't require adjustment
1493 // then we can just use the member function from the primary base.
1494 if (const CXXMethodDecl *OverriddenMD =
1495 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1496 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1497 OverriddenMD).isEmpty()) {
1498 // Replace the method info of the overridden method with our own
1499 // method.
1500 assert(MethodInfoMap.count(OverriddenMD) &&
1501 "Did not find the overridden method!");
1502 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1503
1504 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1505 OverriddenMethodInfo.VTableIndex);
1506
1507 assert(!MethodInfoMap.count(MD) &&
1508 "Should not have method info for this method yet!");
1509
1510 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1511 MethodInfoMap.erase(OverriddenMD);
1512
1513 // If the overridden method exists in a virtual base class or a direct
1514 // or indirect base class of a virtual base class, we need to emit a
1515 // thunk if we ever have a class hierarchy where the base class is not
1516 // a primary base in the complete object.
1517 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1518 // Compute the this adjustment.
1519 ThisAdjustment ThisAdjustment =
1520 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1521 Overrider);
1522
1523 if (ThisAdjustment.VCallOffsetOffset &&
1524 Overrider.Method->getParent() == MostDerivedClass) {
1525
1526 // There's no return adjustment from OverriddenMD and MD,
1527 // but that doesn't mean there isn't one between MD and
1528 // the final overrider.
1529 BaseOffset ReturnAdjustmentOffset =
1530 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1531 ReturnAdjustment ReturnAdjustment =
1532 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1533
1534 // This is a virtual thunk for the most derived class, add it.
1535 AddThunk(Overrider.Method,
1536 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1537 }
1538 }
1539
1540 continue;
1541 }
1542 }
1543
1544 // Insert the method info for this method.
1545 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1546 Components.size());
1547
1548 assert(!MethodInfoMap.count(MD) &&
1549 "Should not have method info for this method yet!");
1550 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1551
1552 // Check if this overrider is going to be used.
1553 const CXXMethodDecl *OverriderMD = Overrider.Method;
1554 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1555 FirstBaseInPrimaryBaseChain,
1556 FirstBaseOffsetInLayoutClass)) {
1557 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1558 continue;
1559 }
1560
1561 // Check if this overrider needs a return adjustment.
1562 // We don't want to do this for pure virtual member functions.
1563 BaseOffset ReturnAdjustmentOffset;
1564 if (!OverriderMD->isPure()) {
1565 ReturnAdjustmentOffset =
1566 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1567 }
1568
1569 ReturnAdjustment ReturnAdjustment =
1570 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1571
1572 AddMethod(Overrider.Method, ReturnAdjustment);
1573 }
1574 }
1575
LayoutVTable()1576 void VTableBuilder::LayoutVTable() {
1577 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1578 CharUnits::Zero()),
1579 /*BaseIsMorallyVirtual=*/false,
1580 MostDerivedClassIsVirtual,
1581 MostDerivedClassOffset);
1582
1583 VisitedVirtualBasesSetTy VBases;
1584
1585 // Determine the primary virtual bases.
1586 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1587 VBases);
1588 VBases.clear();
1589
1590 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1591
1592 // -fapple-kext adds an extra entry at end of vtbl.
1593 bool IsAppleKext = Context.getLangOpts().AppleKext;
1594 if (IsAppleKext)
1595 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1596 }
1597
1598 void
LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,bool BaseIsMorallyVirtual,bool BaseIsVirtualInLayoutClass,CharUnits OffsetInLayoutClass)1599 VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1600 bool BaseIsMorallyVirtual,
1601 bool BaseIsVirtualInLayoutClass,
1602 CharUnits OffsetInLayoutClass) {
1603 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1604
1605 // Add vcall and vbase offsets for this vtable.
1606 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1607 Base, BaseIsVirtualInLayoutClass,
1608 OffsetInLayoutClass);
1609 Components.append(Builder.components_begin(), Builder.components_end());
1610
1611 // Check if we need to add these vcall offsets.
1612 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1613 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1614
1615 if (VCallOffsets.empty())
1616 VCallOffsets = Builder.getVCallOffsets();
1617 }
1618
1619 // If we're laying out the most derived class we want to keep track of the
1620 // virtual base class offset offsets.
1621 if (Base.getBase() == MostDerivedClass)
1622 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1623
1624 // FIXME: Should probably add a layer of abstraction for vtable generation.
1625 if (!isMicrosoftABI()) {
1626 // Add the offset to top.
1627 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1628 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1629
1630 // Next, add the RTTI.
1631 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1632 } else {
1633 // FIXME: unclear what to do with RTTI in MS ABI as emitting it anywhere
1634 // breaks the vftable layout. Just skip RTTI for now, can't mangle anyway.
1635 }
1636
1637 uint64_t AddressPoint = Components.size();
1638
1639 // Now go through all virtual member functions and add them.
1640 PrimaryBasesSetVectorTy PrimaryBases;
1641 AddMethods(Base, OffsetInLayoutClass,
1642 Base.getBase(), OffsetInLayoutClass,
1643 PrimaryBases);
1644
1645 // Compute 'this' pointer adjustments.
1646 ComputeThisAdjustments();
1647
1648 // Add all address points.
1649 const CXXRecordDecl *RD = Base.getBase();
1650 while (true) {
1651 AddressPoints.insert(std::make_pair(
1652 BaseSubobject(RD, OffsetInLayoutClass),
1653 AddressPoint));
1654
1655 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1656 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1657
1658 if (!PrimaryBase)
1659 break;
1660
1661 if (Layout.isPrimaryBaseVirtual()) {
1662 // Check if this virtual primary base is a primary base in the layout
1663 // class. If it's not, we don't want to add it.
1664 const ASTRecordLayout &LayoutClassLayout =
1665 Context.getASTRecordLayout(LayoutClass);
1666
1667 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1668 OffsetInLayoutClass) {
1669 // We don't want to add this class (or any of its primary bases).
1670 break;
1671 }
1672 }
1673
1674 RD = PrimaryBase;
1675 }
1676
1677 // Layout secondary vtables.
1678 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1679 }
1680
LayoutSecondaryVTables(BaseSubobject Base,bool BaseIsMorallyVirtual,CharUnits OffsetInLayoutClass)1681 void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1682 bool BaseIsMorallyVirtual,
1683 CharUnits OffsetInLayoutClass) {
1684 // Itanium C++ ABI 2.5.2:
1685 // Following the primary virtual table of a derived class are secondary
1686 // virtual tables for each of its proper base classes, except any primary
1687 // base(s) with which it shares its primary virtual table.
1688
1689 const CXXRecordDecl *RD = Base.getBase();
1690 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1691 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1692
1693 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1694 E = RD->bases_end(); I != E; ++I) {
1695 // Ignore virtual bases, we'll emit them later.
1696 if (I->isVirtual())
1697 continue;
1698
1699 const CXXRecordDecl *BaseDecl =
1700 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1701
1702 // Ignore bases that don't have a vtable.
1703 if (!BaseDecl->isDynamicClass())
1704 continue;
1705
1706 if (isBuildingConstructorVTable()) {
1707 // Itanium C++ ABI 2.6.4:
1708 // Some of the base class subobjects may not need construction virtual
1709 // tables, which will therefore not be present in the construction
1710 // virtual table group, even though the subobject virtual tables are
1711 // present in the main virtual table group for the complete object.
1712 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1713 continue;
1714 }
1715
1716 // Get the base offset of this base.
1717 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1718 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1719
1720 CharUnits BaseOffsetInLayoutClass =
1721 OffsetInLayoutClass + RelativeBaseOffset;
1722
1723 // Don't emit a secondary vtable for a primary base. We might however want
1724 // to emit secondary vtables for other bases of this base.
1725 if (BaseDecl == PrimaryBase) {
1726 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1727 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1728 continue;
1729 }
1730
1731 // Layout the primary vtable (and any secondary vtables) for this base.
1732 LayoutPrimaryAndSecondaryVTables(
1733 BaseSubobject(BaseDecl, BaseOffset),
1734 BaseIsMorallyVirtual,
1735 /*BaseIsVirtualInLayoutClass=*/false,
1736 BaseOffsetInLayoutClass);
1737 }
1738 }
1739
1740 void
DeterminePrimaryVirtualBases(const CXXRecordDecl * RD,CharUnits OffsetInLayoutClass,VisitedVirtualBasesSetTy & VBases)1741 VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1742 CharUnits OffsetInLayoutClass,
1743 VisitedVirtualBasesSetTy &VBases) {
1744 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1745
1746 // Check if this base has a primary base.
1747 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1748
1749 // Check if it's virtual.
1750 if (Layout.isPrimaryBaseVirtual()) {
1751 bool IsPrimaryVirtualBase = true;
1752
1753 if (isBuildingConstructorVTable()) {
1754 // Check if the base is actually a primary base in the class we use for
1755 // layout.
1756 const ASTRecordLayout &LayoutClassLayout =
1757 Context.getASTRecordLayout(LayoutClass);
1758
1759 CharUnits PrimaryBaseOffsetInLayoutClass =
1760 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1761
1762 // We know that the base is not a primary base in the layout class if
1763 // the base offsets are different.
1764 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1765 IsPrimaryVirtualBase = false;
1766 }
1767
1768 if (IsPrimaryVirtualBase)
1769 PrimaryVirtualBases.insert(PrimaryBase);
1770 }
1771 }
1772
1773 // Traverse bases, looking for more primary virtual bases.
1774 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1775 E = RD->bases_end(); I != E; ++I) {
1776 const CXXRecordDecl *BaseDecl =
1777 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1778
1779 CharUnits BaseOffsetInLayoutClass;
1780
1781 if (I->isVirtual()) {
1782 if (!VBases.insert(BaseDecl))
1783 continue;
1784
1785 const ASTRecordLayout &LayoutClassLayout =
1786 Context.getASTRecordLayout(LayoutClass);
1787
1788 BaseOffsetInLayoutClass =
1789 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1790 } else {
1791 BaseOffsetInLayoutClass =
1792 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1793 }
1794
1795 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1796 }
1797 }
1798
1799 void
LayoutVTablesForVirtualBases(const CXXRecordDecl * RD,VisitedVirtualBasesSetTy & VBases)1800 VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1801 VisitedVirtualBasesSetTy &VBases) {
1802 // Itanium C++ ABI 2.5.2:
1803 // Then come the virtual base virtual tables, also in inheritance graph
1804 // order, and again excluding primary bases (which share virtual tables with
1805 // the classes for which they are primary).
1806 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1807 E = RD->bases_end(); I != E; ++I) {
1808 const CXXRecordDecl *BaseDecl =
1809 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1810
1811 // Check if this base needs a vtable. (If it's virtual, not a primary base
1812 // of some other class, and we haven't visited it before).
1813 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1814 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1815 const ASTRecordLayout &MostDerivedClassLayout =
1816 Context.getASTRecordLayout(MostDerivedClass);
1817 CharUnits BaseOffset =
1818 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1819
1820 const ASTRecordLayout &LayoutClassLayout =
1821 Context.getASTRecordLayout(LayoutClass);
1822 CharUnits BaseOffsetInLayoutClass =
1823 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1824
1825 LayoutPrimaryAndSecondaryVTables(
1826 BaseSubobject(BaseDecl, BaseOffset),
1827 /*BaseIsMorallyVirtual=*/true,
1828 /*BaseIsVirtualInLayoutClass=*/true,
1829 BaseOffsetInLayoutClass);
1830 }
1831
1832 // We only need to check the base for virtual base vtables if it actually
1833 // has virtual bases.
1834 if (BaseDecl->getNumVBases())
1835 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1836 }
1837 }
1838
1839 /// dumpLayout - Dump the vtable layout.
dumpLayout(raw_ostream & Out)1840 void VTableBuilder::dumpLayout(raw_ostream& Out) {
1841
1842 if (isBuildingConstructorVTable()) {
1843 Out << "Construction vtable for ('";
1844 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1845 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1846 Out << LayoutClass->getQualifiedNameAsString();
1847 } else {
1848 Out << "Vtable for '";
1849 Out << MostDerivedClass->getQualifiedNameAsString();
1850 }
1851 Out << "' (" << Components.size() << " entries).\n";
1852
1853 // Iterate through the address points and insert them into a new map where
1854 // they are keyed by the index and not the base object.
1855 // Since an address point can be shared by multiple subobjects, we use an
1856 // STL multimap.
1857 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1858 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1859 E = AddressPoints.end(); I != E; ++I) {
1860 const BaseSubobject& Base = I->first;
1861 uint64_t Index = I->second;
1862
1863 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1864 }
1865
1866 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1867 uint64_t Index = I;
1868
1869 Out << llvm::format("%4d | ", I);
1870
1871 const VTableComponent &Component = Components[I];
1872
1873 // Dump the component.
1874 switch (Component.getKind()) {
1875
1876 case VTableComponent::CK_VCallOffset:
1877 Out << "vcall_offset ("
1878 << Component.getVCallOffset().getQuantity()
1879 << ")";
1880 break;
1881
1882 case VTableComponent::CK_VBaseOffset:
1883 Out << "vbase_offset ("
1884 << Component.getVBaseOffset().getQuantity()
1885 << ")";
1886 break;
1887
1888 case VTableComponent::CK_OffsetToTop:
1889 Out << "offset_to_top ("
1890 << Component.getOffsetToTop().getQuantity()
1891 << ")";
1892 break;
1893
1894 case VTableComponent::CK_RTTI:
1895 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1896 break;
1897
1898 case VTableComponent::CK_FunctionPointer: {
1899 const CXXMethodDecl *MD = Component.getFunctionDecl();
1900
1901 std::string Str =
1902 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1903 MD);
1904 Out << Str;
1905 if (MD->isPure())
1906 Out << " [pure]";
1907
1908 if (MD->isDeleted())
1909 Out << " [deleted]";
1910
1911 ThunkInfo Thunk = VTableThunks.lookup(I);
1912 if (!Thunk.isEmpty()) {
1913 // If this function pointer has a return adjustment, dump it.
1914 if (!Thunk.Return.isEmpty()) {
1915 Out << "\n [return adjustment: ";
1916 Out << Thunk.Return.NonVirtual << " non-virtual";
1917
1918 if (Thunk.Return.VBaseOffsetOffset) {
1919 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1920 Out << " vbase offset offset";
1921 }
1922
1923 Out << ']';
1924 }
1925
1926 // If this function pointer has a 'this' pointer adjustment, dump it.
1927 if (!Thunk.This.isEmpty()) {
1928 Out << "\n [this adjustment: ";
1929 Out << Thunk.This.NonVirtual << " non-virtual";
1930
1931 if (Thunk.This.VCallOffsetOffset) {
1932 Out << ", " << Thunk.This.VCallOffsetOffset;
1933 Out << " vcall offset offset";
1934 }
1935
1936 Out << ']';
1937 }
1938 }
1939
1940 break;
1941 }
1942
1943 case VTableComponent::CK_CompleteDtorPointer:
1944 case VTableComponent::CK_DeletingDtorPointer: {
1945 bool IsComplete =
1946 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1947
1948 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1949
1950 Out << DD->getQualifiedNameAsString();
1951 if (IsComplete)
1952 Out << "() [complete]";
1953 else if (isMicrosoftABI())
1954 Out << "() [scalar deleting]";
1955 else
1956 Out << "() [deleting]";
1957
1958 if (DD->isPure())
1959 Out << " [pure]";
1960
1961 ThunkInfo Thunk = VTableThunks.lookup(I);
1962 if (!Thunk.isEmpty()) {
1963 // If this destructor has a 'this' pointer adjustment, dump it.
1964 if (!Thunk.This.isEmpty()) {
1965 Out << "\n [this adjustment: ";
1966 Out << Thunk.This.NonVirtual << " non-virtual";
1967
1968 if (Thunk.This.VCallOffsetOffset) {
1969 Out << ", " << Thunk.This.VCallOffsetOffset;
1970 Out << " vcall offset offset";
1971 }
1972
1973 Out << ']';
1974 }
1975 }
1976
1977 break;
1978 }
1979
1980 case VTableComponent::CK_UnusedFunctionPointer: {
1981 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1982
1983 std::string Str =
1984 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1985 MD);
1986 Out << "[unused] " << Str;
1987 if (MD->isPure())
1988 Out << " [pure]";
1989 }
1990
1991 }
1992
1993 Out << '\n';
1994
1995 // Dump the next address point.
1996 uint64_t NextIndex = Index + 1;
1997 if (AddressPointsByIndex.count(NextIndex)) {
1998 if (AddressPointsByIndex.count(NextIndex) == 1) {
1999 const BaseSubobject &Base =
2000 AddressPointsByIndex.find(NextIndex)->second;
2001
2002 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2003 Out << ", " << Base.getBaseOffset().getQuantity();
2004 Out << ") vtable address --\n";
2005 } else {
2006 CharUnits BaseOffset =
2007 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2008
2009 // We store the class names in a set to get a stable order.
2010 std::set<std::string> ClassNames;
2011 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2012 AddressPointsByIndex.lower_bound(NextIndex), E =
2013 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2014 assert(I->second.getBaseOffset() == BaseOffset &&
2015 "Invalid base offset!");
2016 const CXXRecordDecl *RD = I->second.getBase();
2017 ClassNames.insert(RD->getQualifiedNameAsString());
2018 }
2019
2020 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2021 E = ClassNames.end(); I != E; ++I) {
2022 Out << " -- (" << *I;
2023 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2024 }
2025 }
2026 }
2027 }
2028
2029 Out << '\n';
2030
2031 if (isBuildingConstructorVTable())
2032 return;
2033
2034 if (MostDerivedClass->getNumVBases()) {
2035 // We store the virtual base class names and their offsets in a map to get
2036 // a stable order.
2037
2038 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2039 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2040 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2041 std::string ClassName = I->first->getQualifiedNameAsString();
2042 CharUnits OffsetOffset = I->second;
2043 ClassNamesAndOffsets.insert(
2044 std::make_pair(ClassName, OffsetOffset));
2045 }
2046
2047 Out << "Virtual base offset offsets for '";
2048 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2049 Out << ClassNamesAndOffsets.size();
2050 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2051
2052 for (std::map<std::string, CharUnits>::const_iterator I =
2053 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2054 I != E; ++I)
2055 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2056
2057 Out << "\n";
2058 }
2059
2060 if (!Thunks.empty()) {
2061 // We store the method names in a map to get a stable order.
2062 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2063
2064 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2065 I != E; ++I) {
2066 const CXXMethodDecl *MD = I->first;
2067 std::string MethodName =
2068 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2069 MD);
2070
2071 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2072 }
2073
2074 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2075 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2076 I != E; ++I) {
2077 const std::string &MethodName = I->first;
2078 const CXXMethodDecl *MD = I->second;
2079
2080 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2081 std::sort(ThunksVector.begin(), ThunksVector.end());
2082
2083 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2084 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2085
2086 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2087 const ThunkInfo &Thunk = ThunksVector[I];
2088
2089 Out << llvm::format("%4d | ", I);
2090
2091 // If this function pointer has a return pointer adjustment, dump it.
2092 if (!Thunk.Return.isEmpty()) {
2093 Out << "return adjustment: " << Thunk.This.NonVirtual;
2094 Out << " non-virtual";
2095 if (Thunk.Return.VBaseOffsetOffset) {
2096 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2097 Out << " vbase offset offset";
2098 }
2099
2100 if (!Thunk.This.isEmpty())
2101 Out << "\n ";
2102 }
2103
2104 // If this function pointer has a 'this' pointer adjustment, dump it.
2105 if (!Thunk.This.isEmpty()) {
2106 Out << "this adjustment: ";
2107 Out << Thunk.This.NonVirtual << " non-virtual";
2108
2109 if (Thunk.This.VCallOffsetOffset) {
2110 Out << ", " << Thunk.This.VCallOffsetOffset;
2111 Out << " vcall offset offset";
2112 }
2113 }
2114
2115 Out << '\n';
2116 }
2117
2118 Out << '\n';
2119 }
2120 }
2121
2122 // Compute the vtable indices for all the member functions.
2123 // Store them in a map keyed by the index so we'll get a sorted table.
2124 std::map<uint64_t, std::string> IndicesMap;
2125
2126 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2127 e = MostDerivedClass->method_end(); i != e; ++i) {
2128 const CXXMethodDecl *MD = *i;
2129
2130 // We only want virtual member functions.
2131 if (!MD->isVirtual())
2132 continue;
2133
2134 std::string MethodName =
2135 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2136 MD);
2137
2138 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2139 // FIXME: Should add a layer of abstraction for vtable generation.
2140 if (!isMicrosoftABI()) {
2141 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))]
2142 = MethodName + " [complete]";
2143 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2144 = MethodName + " [deleting]";
2145 } else {
2146 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2147 = MethodName + " [scalar deleting]";
2148 }
2149 } else {
2150 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2151 }
2152 }
2153
2154 // Print the vtable indices for all the member functions.
2155 if (!IndicesMap.empty()) {
2156 Out << "VTable indices for '";
2157 Out << MostDerivedClass->getQualifiedNameAsString();
2158 Out << "' (" << IndicesMap.size() << " entries).\n";
2159
2160 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2161 E = IndicesMap.end(); I != E; ++I) {
2162 uint64_t VTableIndex = I->first;
2163 const std::string &MethodName = I->second;
2164
2165 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
2166 << '\n';
2167 }
2168 }
2169
2170 Out << '\n';
2171 }
2172
2173 }
2174
VTableLayout(uint64_t NumVTableComponents,const VTableComponent * VTableComponents,uint64_t NumVTableThunks,const VTableThunkTy * VTableThunks,const AddressPointsMapTy & AddressPoints,bool IsMicrosoftABI)2175 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2176 const VTableComponent *VTableComponents,
2177 uint64_t NumVTableThunks,
2178 const VTableThunkTy *VTableThunks,
2179 const AddressPointsMapTy &AddressPoints,
2180 bool IsMicrosoftABI)
2181 : NumVTableComponents(NumVTableComponents),
2182 VTableComponents(new VTableComponent[NumVTableComponents]),
2183 NumVTableThunks(NumVTableThunks),
2184 VTableThunks(new VTableThunkTy[NumVTableThunks]),
2185 AddressPoints(AddressPoints),
2186 IsMicrosoftABI(IsMicrosoftABI) {
2187 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2188 this->VTableComponents.get());
2189 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2190 this->VTableThunks.get());
2191 }
2192
~VTableLayout()2193 VTableLayout::~VTableLayout() { }
2194
VTableContext(ASTContext & Context)2195 VTableContext::VTableContext(ASTContext &Context)
2196 : Context(Context),
2197 IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2198 }
2199
~VTableContext()2200 VTableContext::~VTableContext() {
2201 llvm::DeleteContainerSeconds(VTableLayouts);
2202 }
2203
2204 static void
CollectPrimaryBases(const CXXRecordDecl * RD,ASTContext & Context,VTableBuilder::PrimaryBasesSetVectorTy & PrimaryBases)2205 CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2206 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2207 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2208 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2209
2210 if (!PrimaryBase)
2211 return;
2212
2213 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2214
2215 if (!PrimaryBases.insert(PrimaryBase))
2216 llvm_unreachable("Found a duplicate primary base!");
2217 }
2218
ComputeMethodVTableIndices(const CXXRecordDecl * RD)2219 void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2220
2221 // Itanium C++ ABI 2.5.2:
2222 // The order of the virtual function pointers in a virtual table is the
2223 // order of declaration of the corresponding member functions in the class.
2224 //
2225 // There is an entry for any virtual function declared in a class,
2226 // whether it is a new function or overrides a base class function,
2227 // unless it overrides a function from the primary base, and conversion
2228 // between their return types does not require an adjustment.
2229
2230 int64_t CurrentIndex = 0;
2231
2232 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2233 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2234
2235 if (PrimaryBase) {
2236 assert(PrimaryBase->isCompleteDefinition() &&
2237 "Should have the definition decl of the primary base!");
2238
2239 // Since the record decl shares its vtable pointer with the primary base
2240 // we need to start counting at the end of the primary base's vtable.
2241 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2242 }
2243
2244 // Collect all the primary bases, so we can check whether methods override
2245 // a method from the base.
2246 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2247 CollectPrimaryBases(RD, Context, PrimaryBases);
2248
2249 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2250
2251 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2252 e = RD->method_end(); i != e; ++i) {
2253 const CXXMethodDecl *MD = *i;
2254
2255 // We only want virtual methods.
2256 if (!MD->isVirtual())
2257 continue;
2258
2259 // Check if this method overrides a method in the primary base.
2260 if (const CXXMethodDecl *OverriddenMD =
2261 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2262 // Check if converting from the return type of the method to the
2263 // return type of the overridden method requires conversion.
2264 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2265 OverriddenMD).isEmpty()) {
2266 // This index is shared between the index in the vtable of the primary
2267 // base class.
2268 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2269 const CXXDestructorDecl *OverriddenDD =
2270 cast<CXXDestructorDecl>(OverriddenMD);
2271
2272 if (!isMicrosoftABI()) {
2273 // Add both the complete and deleting entries.
2274 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2275 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2276 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2277 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2278 } else {
2279 // Add the scalar deleting destructor.
2280 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2281 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2282 }
2283 } else {
2284 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2285 }
2286
2287 // We don't need to add an entry for this method.
2288 continue;
2289 }
2290 }
2291
2292 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2293 if (MD->isImplicit()) {
2294 assert(!ImplicitVirtualDtor &&
2295 "Did already see an implicit virtual dtor!");
2296 ImplicitVirtualDtor = DD;
2297 continue;
2298 }
2299
2300 if (!isMicrosoftABI()) {
2301 // Add the complete dtor.
2302 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2303
2304 // Add the deleting dtor.
2305 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2306 } else {
2307 // Add the scalar deleting dtor.
2308 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2309 }
2310 } else {
2311 // Add the entry.
2312 MethodVTableIndices[MD] = CurrentIndex++;
2313 }
2314 }
2315
2316 if (ImplicitVirtualDtor) {
2317 // Itanium C++ ABI 2.5.2:
2318 // If a class has an implicitly-defined virtual destructor,
2319 // its entries come after the declared virtual function pointers.
2320
2321 if (isMicrosoftABI()) {
2322 ErrorUnsupported("implicit virtual destructor in the Microsoft ABI",
2323 ImplicitVirtualDtor->getLocation());
2324 }
2325
2326 // Add the complete dtor.
2327 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2328 CurrentIndex++;
2329
2330 // Add the deleting dtor.
2331 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2332 CurrentIndex++;
2333 }
2334
2335 NumVirtualFunctionPointers[RD] = CurrentIndex;
2336 }
2337
getNumVirtualFunctionPointers(const CXXRecordDecl * RD)2338 uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2339 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2340 NumVirtualFunctionPointers.find(RD);
2341 if (I != NumVirtualFunctionPointers.end())
2342 return I->second;
2343
2344 ComputeMethodVTableIndices(RD);
2345
2346 I = NumVirtualFunctionPointers.find(RD);
2347 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2348 return I->second;
2349 }
2350
getMethodVTableIndex(GlobalDecl GD)2351 uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2352 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2353 if (I != MethodVTableIndices.end())
2354 return I->second;
2355
2356 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2357
2358 ComputeMethodVTableIndices(RD);
2359
2360 I = MethodVTableIndices.find(GD);
2361 assert(I != MethodVTableIndices.end() && "Did not find index!");
2362 return I->second;
2363 }
2364
2365 CharUnits
getVirtualBaseOffsetOffset(const CXXRecordDecl * RD,const CXXRecordDecl * VBase)2366 VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2367 const CXXRecordDecl *VBase) {
2368 ClassPairTy ClassPair(RD, VBase);
2369
2370 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2371 VirtualBaseClassOffsetOffsets.find(ClassPair);
2372 if (I != VirtualBaseClassOffsetOffsets.end())
2373 return I->second;
2374
2375 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2376 BaseSubobject(RD, CharUnits::Zero()),
2377 /*BaseIsVirtual=*/false,
2378 /*OffsetInLayoutClass=*/CharUnits::Zero());
2379
2380 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2381 Builder.getVBaseOffsetOffsets().begin(),
2382 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2383 // Insert all types.
2384 ClassPairTy ClassPair(RD, I->first);
2385
2386 VirtualBaseClassOffsetOffsets.insert(
2387 std::make_pair(ClassPair, I->second));
2388 }
2389
2390 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2391 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2392
2393 return I->second;
2394 }
2395
CreateVTableLayout(const VTableBuilder & Builder)2396 static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2397 SmallVector<VTableLayout::VTableThunkTy, 1>
2398 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2399 std::sort(VTableThunks.begin(), VTableThunks.end());
2400
2401 return new VTableLayout(Builder.getNumVTableComponents(),
2402 Builder.vtable_component_begin(),
2403 VTableThunks.size(),
2404 VTableThunks.data(),
2405 Builder.getAddressPoints(),
2406 Builder.isMicrosoftABI());
2407 }
2408
ComputeVTableRelatedInformation(const CXXRecordDecl * RD)2409 void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2410 const VTableLayout *&Entry = VTableLayouts[RD];
2411
2412 // Check if we've computed this information before.
2413 if (Entry)
2414 return;
2415
2416 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2417 /*MostDerivedClassIsVirtual=*/0, RD);
2418 Entry = CreateVTableLayout(Builder);
2419
2420 // Add the known thunks.
2421 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2422
2423 // If we don't have the vbase information for this class, insert it.
2424 // getVirtualBaseOffsetOffset will compute it separately without computing
2425 // the rest of the vtable related information.
2426 if (!RD->getNumVBases())
2427 return;
2428
2429 const RecordType *VBaseRT =
2430 RD->vbases_begin()->getType()->getAs<RecordType>();
2431 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2432
2433 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2434 return;
2435
2436 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2437 Builder.getVBaseOffsetOffsets().begin(),
2438 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2439 // Insert all types.
2440 ClassPairTy ClassPair(RD, I->first);
2441
2442 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2443 }
2444 }
2445
ErrorUnsupported(StringRef Feature,SourceLocation Location)2446 void VTableContext::ErrorUnsupported(StringRef Feature,
2447 SourceLocation Location) {
2448 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2449 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2450 "v-table layout for %0 is not supported yet");
2451 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2452 }
2453
createConstructionVTableLayout(const CXXRecordDecl * MostDerivedClass,CharUnits MostDerivedClassOffset,bool MostDerivedClassIsVirtual,const CXXRecordDecl * LayoutClass)2454 VTableLayout *VTableContext::createConstructionVTableLayout(
2455 const CXXRecordDecl *MostDerivedClass,
2456 CharUnits MostDerivedClassOffset,
2457 bool MostDerivedClassIsVirtual,
2458 const CXXRecordDecl *LayoutClass) {
2459 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2460 MostDerivedClassIsVirtual, LayoutClass);
2461 return CreateVTableLayout(Builder);
2462 }
2463