blob: f6c8f1c3cf5f8357ec8c8f9d57ade1fc78f9f7b4 [file] [log] [blame]
Peter Collingbournecfd23562011-09-26 01:57:12 +00001//===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with generation of the layout of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/VTableBuilder.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000015#include "clang/AST/ASTContext.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/Support/Format.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000020#include "llvm/Support/raw_ostream.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000021#include <algorithm>
22#include <cstdio>
23
24using namespace clang;
25
26#define DUMP_OVERRIDERS 0
27
28namespace {
29
30/// BaseOffset - Represents an offset from a derived class to a direct or
31/// indirect base class.
32struct BaseOffset {
33 /// DerivedClass - The derived class.
34 const CXXRecordDecl *DerivedClass;
35
36 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +000037 /// involves virtual base classes, this holds the declaration of the last
38 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbournecfd23562011-09-26 01:57:12 +000039 const CXXRecordDecl *VirtualBase;
40
41 /// NonVirtualOffset - The offset from the derived class to the base class.
42 /// (Or the offset from the virtual base class to the base class, if the
43 /// path from the derived class to the base class involves a virtual base
44 /// class.
45 CharUnits NonVirtualOffset;
46
47 BaseOffset() : DerivedClass(0), VirtualBase(0),
48 NonVirtualOffset(CharUnits::Zero()) { }
49 BaseOffset(const CXXRecordDecl *DerivedClass,
50 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
51 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
52 NonVirtualOffset(NonVirtualOffset) { }
53
54 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
55};
56
57/// FinalOverriders - Contains the final overrider member functions for all
58/// member functions in the base subobjects of a class.
59class FinalOverriders {
60public:
61 /// OverriderInfo - Information about a final overrider.
62 struct OverriderInfo {
63 /// Method - The method decl of the overrider.
64 const CXXMethodDecl *Method;
65
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000066 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +000067 CharUnits Offset;
68
69 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
70 };
71
72private:
73 /// MostDerivedClass - The most derived class for which the final overriders
74 /// are stored.
75 const CXXRecordDecl *MostDerivedClass;
76
77 /// MostDerivedClassOffset - If we're building final overriders for a
78 /// construction vtable, this holds the offset from the layout class to the
79 /// most derived class.
80 const CharUnits MostDerivedClassOffset;
81
82 /// LayoutClass - The class we're using for layout information. Will be
83 /// different than the most derived class if the final overriders are for a
84 /// construction vtable.
85 const CXXRecordDecl *LayoutClass;
86
87 ASTContext &Context;
88
89 /// MostDerivedClassLayout - the AST record layout of the most derived class.
90 const ASTRecordLayout &MostDerivedClassLayout;
91
92 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
93 /// in a base subobject.
94 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
95
96 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
97 OverriderInfo> OverridersMapTy;
98
99 /// OverridersMap - The final overriders for all virtual member functions of
100 /// all the base subobjects of the most derived class.
101 OverridersMapTy OverridersMap;
102
103 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
104 /// as a record decl and a subobject number) and its offsets in the most
105 /// derived class as well as the layout class.
106 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
107 CharUnits> SubobjectOffsetMapTy;
108
109 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
110
111 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
112 /// given base.
113 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
114 CharUnits OffsetInLayoutClass,
115 SubobjectOffsetMapTy &SubobjectOffsets,
116 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
117 SubobjectCountMapTy &SubobjectCounts);
118
119 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
120
121 /// dump - dump the final overriders for a base subobject, and all its direct
122 /// and indirect base subobjects.
123 void dump(raw_ostream &Out, BaseSubobject Base,
124 VisitedVirtualBasesSetTy& VisitedVirtualBases);
125
126public:
127 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
128 CharUnits MostDerivedClassOffset,
129 const CXXRecordDecl *LayoutClass);
130
131 /// getOverrider - Get the final overrider for the given method declaration in
132 /// the subobject with the given base offset.
133 OverriderInfo getOverrider(const CXXMethodDecl *MD,
134 CharUnits BaseOffset) const {
135 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
136 "Did not find overrider!");
137
138 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
139 }
140
141 /// dump - dump the final overriders.
142 void dump() {
143 VisitedVirtualBasesSetTy VisitedVirtualBases;
144 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
145 VisitedVirtualBases);
146 }
147
148};
149
Peter Collingbournecfd23562011-09-26 01:57:12 +0000150FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
151 CharUnits MostDerivedClassOffset,
152 const CXXRecordDecl *LayoutClass)
153 : MostDerivedClass(MostDerivedClass),
154 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
155 Context(MostDerivedClass->getASTContext()),
156 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
157
158 // Compute base offsets.
159 SubobjectOffsetMapTy SubobjectOffsets;
160 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
161 SubobjectCountMapTy SubobjectCounts;
162 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
163 /*IsVirtual=*/false,
164 MostDerivedClassOffset,
165 SubobjectOffsets, SubobjectLayoutClassOffsets,
166 SubobjectCounts);
167
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000168 // Get the final overriders.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000169 CXXFinalOverriderMap FinalOverriders;
170 MostDerivedClass->getFinalOverriders(FinalOverriders);
171
172 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
173 E = FinalOverriders.end(); I != E; ++I) {
174 const CXXMethodDecl *MD = I->first;
175 const OverridingMethods& Methods = I->second;
176
177 for (OverridingMethods::const_iterator I = Methods.begin(),
178 E = Methods.end(); I != E; ++I) {
179 unsigned SubobjectNumber = I->first;
180 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
181 SubobjectNumber)) &&
182 "Did not find subobject offset!");
183
184 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
185 SubobjectNumber)];
186
187 assert(I->second.size() == 1 && "Final overrider is not unique!");
188 const UniqueVirtualMethod &Method = I->second.front();
189
190 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
191 assert(SubobjectLayoutClassOffsets.count(
192 std::make_pair(OverriderRD, Method.Subobject))
193 && "Did not find subobject offset!");
194 CharUnits OverriderOffset =
195 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
196 Method.Subobject)];
197
198 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
199 assert(!Overrider.Method && "Overrider should not exist yet!");
200
201 Overrider.Offset = OverriderOffset;
202 Overrider.Method = Method.Method;
203 }
204 }
205
206#if DUMP_OVERRIDERS
207 // And dump them (for now).
208 dump();
209#endif
210}
211
212static BaseOffset ComputeBaseOffset(ASTContext &Context,
213 const CXXRecordDecl *DerivedRD,
214 const CXXBasePath &Path) {
215 CharUnits NonVirtualOffset = CharUnits::Zero();
216
217 unsigned NonVirtualStart = 0;
218 const CXXRecordDecl *VirtualBase = 0;
219
220 // First, look for the virtual base class.
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000221 for (int I = Path.size(), E = 0; I != E; --I) {
222 const CXXBasePathElement &Element = Path[I - 1];
223
Peter Collingbournecfd23562011-09-26 01:57:12 +0000224 if (Element.Base->isVirtual()) {
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000225 NonVirtualStart = I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000226 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000227 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000228 break;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000229 }
230 }
231
232 // Now compute the non-virtual offset.
233 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
234 const CXXBasePathElement &Element = Path[I];
235
236 // Check the base class offset.
237 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
238
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000239 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000240
241 NonVirtualOffset += Layout.getBaseClassOffset(Base);
242 }
243
244 // FIXME: This should probably use CharUnits or something. Maybe we should
245 // even change the base offsets in ASTRecordLayout to be specified in
246 // CharUnits.
247 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
248
249}
250
251static BaseOffset ComputeBaseOffset(ASTContext &Context,
252 const CXXRecordDecl *BaseRD,
253 const CXXRecordDecl *DerivedRD) {
254 CXXBasePaths Paths(/*FindAmbiguities=*/false,
255 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer325d7452013-02-03 18:55:34 +0000256
257 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000258 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +0000259
260 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
261}
262
263static BaseOffset
264ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
265 const CXXMethodDecl *DerivedMD,
266 const CXXMethodDecl *BaseMD) {
267 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
268 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
269
270 // Canonicalize the return types.
271 CanQualType CanDerivedReturnType =
272 Context.getCanonicalType(DerivedFT->getResultType());
273 CanQualType CanBaseReturnType =
274 Context.getCanonicalType(BaseFT->getResultType());
275
276 assert(CanDerivedReturnType->getTypeClass() ==
277 CanBaseReturnType->getTypeClass() &&
278 "Types must have same type class!");
279
280 if (CanDerivedReturnType == CanBaseReturnType) {
281 // No adjustment needed.
282 return BaseOffset();
283 }
284
285 if (isa<ReferenceType>(CanDerivedReturnType)) {
286 CanDerivedReturnType =
287 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
288 CanBaseReturnType =
289 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
290 } else if (isa<PointerType>(CanDerivedReturnType)) {
291 CanDerivedReturnType =
292 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
293 CanBaseReturnType =
294 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
295 } else {
296 llvm_unreachable("Unexpected return type!");
297 }
298
299 // We need to compare unqualified types here; consider
300 // const T *Base::foo();
301 // T *Derived::foo();
302 if (CanDerivedReturnType.getUnqualifiedType() ==
303 CanBaseReturnType.getUnqualifiedType()) {
304 // No adjustment needed.
305 return BaseOffset();
306 }
307
308 const CXXRecordDecl *DerivedRD =
309 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
310
311 const CXXRecordDecl *BaseRD =
312 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
313
314 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
315}
316
317void
318FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
319 CharUnits OffsetInLayoutClass,
320 SubobjectOffsetMapTy &SubobjectOffsets,
321 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
322 SubobjectCountMapTy &SubobjectCounts) {
323 const CXXRecordDecl *RD = Base.getBase();
324
325 unsigned SubobjectNumber = 0;
326 if (!IsVirtual)
327 SubobjectNumber = ++SubobjectCounts[RD];
328
329 // Set up the subobject to offset mapping.
330 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
331 && "Subobject offset already exists!");
332 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
333 && "Subobject offset already exists!");
334
335 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
336 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
337 OffsetInLayoutClass;
338
339 // Traverse our bases.
340 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
341 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000342 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000343
344 CharUnits BaseOffset;
345 CharUnits BaseOffsetInLayoutClass;
346 if (I->isVirtual()) {
347 // Check if we've visited this virtual base before.
348 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
349 continue;
350
351 const ASTRecordLayout &LayoutClassLayout =
352 Context.getASTRecordLayout(LayoutClass);
353
354 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
355 BaseOffsetInLayoutClass =
356 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
357 } else {
358 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
359 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
360
361 BaseOffset = Base.getBaseOffset() + Offset;
362 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
363 }
364
365 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
366 I->isVirtual(), BaseOffsetInLayoutClass,
367 SubobjectOffsets, SubobjectLayoutClassOffsets,
368 SubobjectCounts);
369 }
370}
371
372void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
373 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
374 const CXXRecordDecl *RD = Base.getBase();
375 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
376
377 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
378 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000379 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000380
381 // Ignore bases that don't have any virtual member functions.
382 if (!BaseDecl->isPolymorphic())
383 continue;
384
385 CharUnits BaseOffset;
386 if (I->isVirtual()) {
387 if (!VisitedVirtualBases.insert(BaseDecl)) {
388 // We've visited this base before.
389 continue;
390 }
391
392 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
393 } else {
394 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
395 }
396
397 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
398 }
399
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000400 Out << "Final overriders for (";
401 RD->printQualifiedName(Out);
402 Out << ", ";
Peter Collingbournecfd23562011-09-26 01:57:12 +0000403 Out << Base.getBaseOffset().getQuantity() << ")\n";
404
405 // Now dump the overriders for this base subobject.
406 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
407 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +0000408 const CXXMethodDecl *MD = *I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000409
410 if (!MD->isVirtual())
411 continue;
412
413 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
414
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000415 Out << " ";
416 MD->printQualifiedName(Out);
417 Out << " - (";
418 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000419 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000420
421 BaseOffset Offset;
422 if (!Overrider.Method->isPure())
423 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
424
425 if (!Offset.isEmpty()) {
426 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000427 if (Offset.VirtualBase) {
428 Offset.VirtualBase->printQualifiedName(Out);
429 Out << " vbase, ";
430 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000431
432 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
433 }
434
435 Out << "\n";
436 }
437}
438
439/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
440struct VCallOffsetMap {
441
442 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
443
444 /// Offsets - Keeps track of methods and their offsets.
445 // FIXME: This should be a real map and not a vector.
446 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
447
448 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
449 /// can share the same vcall offset.
450 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
451 const CXXMethodDecl *RHS);
452
453public:
454 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
455 /// add was successful, or false if there was already a member function with
456 /// the same signature in the map.
457 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
458
459 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
460 /// vtable address point) for the given virtual member function.
461 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
462
463 // empty - Return whether the offset map is empty or not.
464 bool empty() const { return Offsets.empty(); }
465};
466
467static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
468 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000469 const FunctionProtoType *LT =
470 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
471 const FunctionProtoType *RT =
472 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000473
474 // Fast-path matches in the canonical types.
475 if (LT == RT) return true;
476
477 // Force the signatures to match. We can't rely on the overrides
478 // list here because there isn't necessarily an inheritance
479 // relationship between the two methods.
John McCallb6c4a7e2012-03-21 06:57:19 +0000480 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Peter Collingbournecfd23562011-09-26 01:57:12 +0000481 LT->getNumArgs() != RT->getNumArgs())
482 return false;
483 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
484 if (LT->getArgType(I) != RT->getArgType(I))
485 return false;
486 return true;
487}
488
489bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
490 const CXXMethodDecl *RHS) {
491 assert(LHS->isVirtual() && "LHS must be virtual!");
492 assert(RHS->isVirtual() && "LHS must be virtual!");
493
494 // A destructor can share a vcall offset with another destructor.
495 if (isa<CXXDestructorDecl>(LHS))
496 return isa<CXXDestructorDecl>(RHS);
497
498 // FIXME: We need to check more things here.
499
500 // The methods must have the same name.
501 DeclarationName LHSName = LHS->getDeclName();
502 DeclarationName RHSName = RHS->getDeclName();
503 if (LHSName != RHSName)
504 return false;
505
506 // And the same signatures.
507 return HasSameVirtualSignature(LHS, RHS);
508}
509
510bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
511 CharUnits OffsetOffset) {
512 // Check if we can reuse an offset.
513 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
514 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
515 return false;
516 }
517
518 // Add the offset.
519 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
520 return true;
521}
522
523CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
524 // Look for an offset.
525 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
526 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
527 return Offsets[I].second;
528 }
529
530 llvm_unreachable("Should always find a vcall offset offset!");
531}
532
533/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
534class VCallAndVBaseOffsetBuilder {
535public:
536 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
537 VBaseOffsetOffsetsMapTy;
538
539private:
540 /// MostDerivedClass - The most derived class for which we're building vcall
541 /// and vbase offsets.
542 const CXXRecordDecl *MostDerivedClass;
543
544 /// LayoutClass - The class we're using for layout information. Will be
545 /// different than the most derived class if we're building a construction
546 /// vtable.
547 const CXXRecordDecl *LayoutClass;
548
549 /// Context - The ASTContext which we will use for layout information.
550 ASTContext &Context;
551
552 /// Components - vcall and vbase offset components
553 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
554 VTableComponentVectorTy Components;
555
556 /// VisitedVirtualBases - Visited virtual bases.
557 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
558
559 /// VCallOffsets - Keeps track of vcall offsets.
560 VCallOffsetMap VCallOffsets;
561
562
563 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
564 /// relative to the address point.
565 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
566
567 /// FinalOverriders - The final overriders of the most derived class.
568 /// (Can be null when we're not building a vtable of the most derived class).
569 const FinalOverriders *Overriders;
570
571 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
572 /// given base subobject.
573 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
574 CharUnits RealBaseOffset);
575
576 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
577 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
578
579 /// AddVBaseOffsets - Add vbase offsets for the given class.
580 void AddVBaseOffsets(const CXXRecordDecl *Base,
581 CharUnits OffsetInLayoutClass);
582
583 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
584 /// chars, relative to the vtable address point.
585 CharUnits getCurrentOffsetOffset() const;
586
587public:
588 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
589 const CXXRecordDecl *LayoutClass,
590 const FinalOverriders *Overriders,
591 BaseSubobject Base, bool BaseIsVirtual,
592 CharUnits OffsetInLayoutClass)
593 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
594 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
595
596 // Add vcall and vbase offsets.
597 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
598 }
599
600 /// Methods for iterating over the components.
601 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
602 const_iterator components_begin() const { return Components.rbegin(); }
603 const_iterator components_end() const { return Components.rend(); }
604
605 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
606 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
607 return VBaseOffsetOffsets;
608 }
609};
610
611void
612VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
613 bool BaseIsVirtual,
614 CharUnits RealBaseOffset) {
615 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
616
617 // Itanium C++ ABI 2.5.2:
618 // ..in classes sharing a virtual table with a primary base class, the vcall
619 // and vbase offsets added by the derived class all come before the vcall
620 // and vbase offsets required by the base class, so that the latter may be
621 // laid out as required by the base class without regard to additions from
622 // the derived class(es).
623
624 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
625 // emit them for the primary base first).
626 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
627 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
628
629 CharUnits PrimaryBaseOffset;
630
631 // Get the base offset of the primary base.
632 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000633 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000634 "Primary vbase should have a zero offset!");
635
636 const ASTRecordLayout &MostDerivedClassLayout =
637 Context.getASTRecordLayout(MostDerivedClass);
638
639 PrimaryBaseOffset =
640 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
641 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000642 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000643 "Primary base should have a zero offset!");
644
645 PrimaryBaseOffset = Base.getBaseOffset();
646 }
647
648 AddVCallAndVBaseOffsets(
649 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
650 PrimaryBaseIsVirtual, RealBaseOffset);
651 }
652
653 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
654
655 // We only want to add vcall offsets for virtual bases.
656 if (BaseIsVirtual)
657 AddVCallOffsets(Base, RealBaseOffset);
658}
659
660CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
661 // OffsetIndex is the index of this vcall or vbase offset, relative to the
662 // vtable address point. (We subtract 3 to account for the information just
663 // above the address point, the RTTI info, the offset to top, and the
664 // vcall offset itself).
665 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
666
667 CharUnits PointerWidth =
668 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
669 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
670 return OffsetOffset;
671}
672
673void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
674 CharUnits VBaseOffset) {
675 const CXXRecordDecl *RD = Base.getBase();
676 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
677
678 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
679
680 // Handle the primary base first.
681 // We only want to add vcall offsets if the base is non-virtual; a virtual
682 // primary base will have its vcall and vbase offsets emitted already.
683 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
684 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000685 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000686 "Primary base should have a zero offset!");
687
688 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
689 VBaseOffset);
690 }
691
692 // Add the vcall offsets.
693 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
694 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +0000695 const CXXMethodDecl *MD = *I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000696
697 if (!MD->isVirtual())
698 continue;
699
700 CharUnits OffsetOffset = getCurrentOffsetOffset();
701
702 // Don't add a vcall offset if we already have one for this member function
703 // signature.
704 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
705 continue;
706
707 CharUnits Offset = CharUnits::Zero();
708
709 if (Overriders) {
710 // Get the final overrider.
711 FinalOverriders::OverriderInfo Overrider =
712 Overriders->getOverrider(MD, Base.getBaseOffset());
713
714 /// The vcall offset is the offset from the virtual base to the object
715 /// where the function was overridden.
716 Offset = Overrider.Offset - VBaseOffset;
717 }
718
719 Components.push_back(
720 VTableComponent::MakeVCallOffset(Offset));
721 }
722
723 // And iterate over all non-virtual bases (ignoring the primary base).
724 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
725 E = RD->bases_end(); I != E; ++I) {
726
727 if (I->isVirtual())
728 continue;
729
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000730 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000731 if (BaseDecl == PrimaryBase)
732 continue;
733
734 // Get the base offset of this base.
735 CharUnits BaseOffset = Base.getBaseOffset() +
736 Layout.getBaseClassOffset(BaseDecl);
737
738 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
739 VBaseOffset);
740 }
741}
742
743void
744VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
745 CharUnits OffsetInLayoutClass) {
746 const ASTRecordLayout &LayoutClassLayout =
747 Context.getASTRecordLayout(LayoutClass);
748
749 // Add vbase offsets.
750 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
751 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000752 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000753
754 // Check if this is a virtual base that we haven't visited before.
755 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
756 CharUnits Offset =
757 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
758
759 // Add the vbase offset offset.
760 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
761 "vbase offset offset already exists!");
762
763 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
764 VBaseOffsetOffsets.insert(
765 std::make_pair(BaseDecl, VBaseOffsetOffset));
766
767 Components.push_back(
768 VTableComponent::MakeVBaseOffset(Offset));
769 }
770
771 // Check the base class looking for more vbase offsets.
772 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
773 }
774}
775
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000776/// ItaniumVTableBuilder - Class for building vtable layout information.
777class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000778public:
779 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
780 /// primary bases.
781 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
782 PrimaryBasesSetVectorTy;
783
784 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
785 VBaseOffsetOffsetsMapTy;
786
787 typedef llvm::DenseMap<BaseSubobject, uint64_t>
788 AddressPointsMapTy;
789
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000790 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
791
Peter Collingbournecfd23562011-09-26 01:57:12 +0000792private:
793 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000794 ItaniumVTableContext &VTables;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000795
796 /// MostDerivedClass - The most derived class for which we're building this
797 /// vtable.
798 const CXXRecordDecl *MostDerivedClass;
799
800 /// MostDerivedClassOffset - If we're building a construction vtable, this
801 /// holds the offset from the layout class to the most derived class.
802 const CharUnits MostDerivedClassOffset;
803
804 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
805 /// base. (This only makes sense when building a construction vtable).
806 bool MostDerivedClassIsVirtual;
807
808 /// LayoutClass - The class we're using for layout information. Will be
809 /// different than the most derived class if we're building a construction
810 /// vtable.
811 const CXXRecordDecl *LayoutClass;
812
813 /// Context - The ASTContext which we will use for layout information.
814 ASTContext &Context;
815
816 /// FinalOverriders - The final overriders of the most derived class.
817 const FinalOverriders Overriders;
818
819 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
820 /// bases in this vtable.
821 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
822
823 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
824 /// the most derived class.
825 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
826
827 /// Components - The components of the vtable being built.
828 SmallVector<VTableComponent, 64> Components;
829
830 /// AddressPoints - Address points for the vtable being built.
831 AddressPointsMapTy AddressPoints;
832
833 /// MethodInfo - Contains information about a method in a vtable.
834 /// (Used for computing 'this' pointer adjustment thunks.
835 struct MethodInfo {
836 /// BaseOffset - The base offset of this method.
837 const CharUnits BaseOffset;
838
839 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
840 /// method.
841 const CharUnits BaseOffsetInLayoutClass;
842
843 /// VTableIndex - The index in the vtable that this method has.
844 /// (For destructors, this is the index of the complete destructor).
845 const uint64_t VTableIndex;
846
847 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
848 uint64_t VTableIndex)
849 : BaseOffset(BaseOffset),
850 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851 VTableIndex(VTableIndex) { }
852
853 MethodInfo()
854 : BaseOffset(CharUnits::Zero()),
855 BaseOffsetInLayoutClass(CharUnits::Zero()),
856 VTableIndex(0) { }
857 };
858
859 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
860
861 /// MethodInfoMap - The information for all methods in the vtable we're
862 /// currently building.
863 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000864
865 /// MethodVTableIndices - Contains the index (relative to the vtable address
866 /// point) where the function pointer for a virtual function is stored.
867 MethodVTableIndicesTy MethodVTableIndices;
868
Peter Collingbournecfd23562011-09-26 01:57:12 +0000869 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
870
871 /// VTableThunks - The thunks by vtable index in the vtable currently being
872 /// built.
873 VTableThunksMapTy VTableThunks;
874
875 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
876 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
877
878 /// Thunks - A map that contains all the thunks needed for all methods in the
879 /// most derived class for which the vtable is currently being built.
880 ThunksMapTy Thunks;
881
882 /// AddThunk - Add a thunk for the given method.
883 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
884
885 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
886 /// part of the vtable we're currently building.
887 void ComputeThisAdjustments();
888
889 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
890
891 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
892 /// some other base.
893 VisitedVirtualBasesSetTy PrimaryVirtualBases;
894
895 /// ComputeReturnAdjustment - Compute the return adjustment given a return
896 /// adjustment base offset.
897 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
898
899 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
900 /// the 'this' pointer from the base subobject to the derived subobject.
901 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
902 BaseSubobject Derived) const;
903
904 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
905 /// given virtual member function, its offset in the layout class and its
906 /// final overrider.
907 ThisAdjustment
908 ComputeThisAdjustment(const CXXMethodDecl *MD,
909 CharUnits BaseOffsetInLayoutClass,
910 FinalOverriders::OverriderInfo Overrider);
911
912 /// AddMethod - Add a single virtual member function to the vtable
913 /// components vector.
914 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
915
916 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
917 /// part of the vtable.
918 ///
919 /// Itanium C++ ABI 2.5.2:
920 ///
921 /// struct A { virtual void f(); };
922 /// struct B : virtual public A { int i; };
923 /// struct C : virtual public A { int j; };
924 /// struct D : public B, public C {};
925 ///
926 /// When B and C are declared, A is a primary base in each case, so although
927 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
928 /// adjustment is required and no thunk is generated. However, inside D
929 /// objects, A is no longer a primary base of C, so if we allowed calls to
930 /// C::f() to use the copy of A's vtable in the C subobject, we would need
931 /// to adjust this from C* to B::A*, which would require a third-party
932 /// thunk. Since we require that a call to C::f() first convert to A*,
933 /// C-in-D's copy of A's vtable is never referenced, so this is not
934 /// necessary.
935 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
936 CharUnits BaseOffsetInLayoutClass,
937 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
938 CharUnits FirstBaseOffsetInLayoutClass) const;
939
940
941 /// AddMethods - Add the methods of this base subobject and all its
942 /// primary bases to the vtable components vector.
943 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
944 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
945 CharUnits FirstBaseOffsetInLayoutClass,
946 PrimaryBasesSetVectorTy &PrimaryBases);
947
948 // LayoutVTable - Layout the vtable for the given base class, including its
949 // secondary vtables and any vtables for virtual bases.
950 void LayoutVTable();
951
952 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
953 /// given base subobject, as well as all its secondary vtables.
954 ///
955 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
956 /// or a direct or indirect base of a virtual base.
957 ///
958 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
959 /// in the layout class.
960 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
961 bool BaseIsMorallyVirtual,
962 bool BaseIsVirtualInLayoutClass,
963 CharUnits OffsetInLayoutClass);
964
965 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
966 /// subobject.
967 ///
968 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
969 /// or a direct or indirect base of a virtual base.
970 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
971 CharUnits OffsetInLayoutClass);
972
973 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
974 /// class hierarchy.
975 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
976 CharUnits OffsetInLayoutClass,
977 VisitedVirtualBasesSetTy &VBases);
978
979 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
980 /// given base (excluding any primary bases).
981 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
982 VisitedVirtualBasesSetTy &VBases);
983
984 /// isBuildingConstructionVTable - Return whether this vtable builder is
985 /// building a construction vtable.
986 bool isBuildingConstructorVTable() const {
987 return MostDerivedClass != LayoutClass;
988 }
989
990public:
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000991 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
992 const CXXRecordDecl *MostDerivedClass,
993 CharUnits MostDerivedClassOffset,
994 bool MostDerivedClassIsVirtual,
995 const CXXRecordDecl *LayoutClass)
996 : VTables(VTables), MostDerivedClass(MostDerivedClass),
997 MostDerivedClassOffset(MostDerivedClassOffset),
998 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
999 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1000 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00001001 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001002
1003 LayoutVTable();
1004
David Blaikiebbafb8a2012-03-11 07:00:24 +00001005 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00001006 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001007 }
1008
1009 uint64_t getNumThunks() const {
1010 return Thunks.size();
1011 }
1012
1013 ThunksMapTy::const_iterator thunks_begin() const {
1014 return Thunks.begin();
1015 }
1016
1017 ThunksMapTy::const_iterator thunks_end() const {
1018 return Thunks.end();
1019 }
1020
1021 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1022 return VBaseOffsetOffsets;
1023 }
1024
1025 const AddressPointsMapTy &getAddressPoints() const {
1026 return AddressPoints;
1027 }
1028
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001029 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1030 return MethodVTableIndices.begin();
1031 }
1032
1033 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1034 return MethodVTableIndices.end();
1035 }
1036
Peter Collingbournecfd23562011-09-26 01:57:12 +00001037 /// getNumVTableComponents - Return the number of components in the vtable
1038 /// currently built.
1039 uint64_t getNumVTableComponents() const {
1040 return Components.size();
1041 }
1042
1043 const VTableComponent *vtable_component_begin() const {
1044 return Components.begin();
1045 }
1046
1047 const VTableComponent *vtable_component_end() const {
1048 return Components.end();
1049 }
1050
1051 AddressPointsMapTy::const_iterator address_points_begin() const {
1052 return AddressPoints.begin();
1053 }
1054
1055 AddressPointsMapTy::const_iterator address_points_end() const {
1056 return AddressPoints.end();
1057 }
1058
1059 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1060 return VTableThunks.begin();
1061 }
1062
1063 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1064 return VTableThunks.end();
1065 }
1066
1067 /// dumpLayout - Dump the vtable layout.
1068 void dumpLayout(raw_ostream&);
1069};
1070
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001071void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1072 const ThunkInfo &Thunk) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001073 assert(!isBuildingConstructorVTable() &&
1074 "Can't add thunks for construction vtable");
1075
Craig Topper5603df42013-07-05 19:34:19 +00001076 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1077
Peter Collingbournecfd23562011-09-26 01:57:12 +00001078 // Check if we have this thunk already.
1079 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1080 ThunksVector.end())
1081 return;
1082
1083 ThunksVector.push_back(Thunk);
1084}
1085
1086typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1087
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001088/// Visit all the methods overridden by the given method recursively,
1089/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1090/// indicating whether to continue the recursion for the given overridden
1091/// method (i.e. returning false stops the iteration).
1092template <class VisitorTy>
1093static void
1094visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001095 assert(MD->isVirtual() && "Method is not virtual!");
1096
1097 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1098 E = MD->end_overridden_methods(); I != E; ++I) {
1099 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001100 if (!Visitor.visit(OverriddenMD))
1101 continue;
1102 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001103 }
1104}
1105
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001106namespace {
1107 struct OverriddenMethodsCollector {
1108 OverriddenMethodsSetTy *Methods;
1109
1110 bool visit(const CXXMethodDecl *MD) {
1111 // Don't recurse on this method if we've already collected it.
1112 return Methods->insert(MD);
1113 }
1114 };
1115}
1116
1117/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1118/// the overridden methods that the function decl overrides.
1119static void
1120ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1121 OverriddenMethodsSetTy& OverriddenMethods) {
1122 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1123 visitAllOverriddenMethods(MD, Collector);
1124}
1125
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001126void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001127 // Now go through the method info map and see if any of the methods need
1128 // 'this' pointer adjustments.
1129 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1130 E = MethodInfoMap.end(); I != E; ++I) {
1131 const CXXMethodDecl *MD = I->first;
1132 const MethodInfo &MethodInfo = I->second;
1133
1134 // Ignore adjustments for unused function pointers.
1135 uint64_t VTableIndex = MethodInfo.VTableIndex;
1136 if (Components[VTableIndex].getKind() ==
1137 VTableComponent::CK_UnusedFunctionPointer)
1138 continue;
1139
1140 // Get the final overrider for this method.
1141 FinalOverriders::OverriderInfo Overrider =
1142 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1143
1144 // Check if we need an adjustment at all.
1145 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1146 // When a return thunk is needed by a derived class that overrides a
1147 // virtual base, gcc uses a virtual 'this' adjustment as well.
1148 // While the thunk itself might be needed by vtables in subclasses or
1149 // in construction vtables, there doesn't seem to be a reason for using
1150 // the thunk in this vtable. Still, we do so to match gcc.
1151 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1152 continue;
1153 }
1154
1155 ThisAdjustment ThisAdjustment =
1156 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1157
1158 if (ThisAdjustment.isEmpty())
1159 continue;
1160
1161 // Add it.
1162 VTableThunks[VTableIndex].This = ThisAdjustment;
1163
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001164 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001165 // Add an adjustment for the deleting destructor as well.
1166 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1167 }
1168 }
1169
1170 /// Clear the method info map.
1171 MethodInfoMap.clear();
1172
1173 if (isBuildingConstructorVTable()) {
1174 // We don't need to store thunk information for construction vtables.
1175 return;
1176 }
1177
1178 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1179 E = VTableThunks.end(); I != E; ++I) {
1180 const VTableComponent &Component = Components[I->first];
1181 const ThunkInfo &Thunk = I->second;
1182 const CXXMethodDecl *MD;
1183
1184 switch (Component.getKind()) {
1185 default:
1186 llvm_unreachable("Unexpected vtable component kind!");
1187 case VTableComponent::CK_FunctionPointer:
1188 MD = Component.getFunctionDecl();
1189 break;
1190 case VTableComponent::CK_CompleteDtorPointer:
1191 MD = Component.getDestructorDecl();
1192 break;
1193 case VTableComponent::CK_DeletingDtorPointer:
1194 // We've already added the thunk when we saw the complete dtor pointer.
1195 continue;
1196 }
1197
1198 if (MD->getParent() == MostDerivedClass)
1199 AddThunk(MD, Thunk);
1200 }
1201}
1202
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001203ReturnAdjustment
1204ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001205 ReturnAdjustment Adjustment;
1206
1207 if (!Offset.isEmpty()) {
1208 if (Offset.VirtualBase) {
1209 // Get the virtual base offset offset.
1210 if (Offset.DerivedClass == MostDerivedClass) {
1211 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001212 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001213 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1214 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001215 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001216 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1217 Offset.VirtualBase).getQuantity();
1218 }
1219 }
1220
1221 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1222 }
1223
1224 return Adjustment;
1225}
1226
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001227BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1228 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001229 const CXXRecordDecl *BaseRD = Base.getBase();
1230 const CXXRecordDecl *DerivedRD = Derived.getBase();
1231
1232 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1233 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1234
Benjamin Kramer325d7452013-02-03 18:55:34 +00001235 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001236 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001237
1238 // We have to go through all the paths, and see which one leads us to the
1239 // right base subobject.
1240 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1241 I != E; ++I) {
1242 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1243
1244 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1245
1246 if (Offset.VirtualBase) {
1247 // If we have a virtual base class, the non-virtual offset is relative
1248 // to the virtual base class offset.
1249 const ASTRecordLayout &LayoutClassLayout =
1250 Context.getASTRecordLayout(LayoutClass);
1251
1252 /// Get the virtual base offset, relative to the most derived class
1253 /// layout.
1254 OffsetToBaseSubobject +=
1255 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1256 } else {
1257 // Otherwise, the non-virtual offset is relative to the derived class
1258 // offset.
1259 OffsetToBaseSubobject += Derived.getBaseOffset();
1260 }
1261
1262 // Check if this path gives us the right base subobject.
1263 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1264 // Since we're going from the base class _to_ the derived class, we'll
1265 // invert the non-virtual offset here.
1266 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1267 return Offset;
1268 }
1269 }
1270
1271 return BaseOffset();
1272}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001273
1274ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1275 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1276 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001277 // Ignore adjustments for pure virtual member functions.
1278 if (Overrider.Method->isPure())
1279 return ThisAdjustment();
1280
1281 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1282 BaseOffsetInLayoutClass);
1283
1284 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1285 Overrider.Offset);
1286
1287 // Compute the adjustment offset.
1288 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1289 OverriderBaseSubobject);
1290 if (Offset.isEmpty())
1291 return ThisAdjustment();
1292
1293 ThisAdjustment Adjustment;
1294
1295 if (Offset.VirtualBase) {
1296 // Get the vcall offset map for this virtual base.
1297 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1298
1299 if (VCallOffsets.empty()) {
1300 // We don't have vcall offsets for this virtual base, go ahead and
1301 // build them.
1302 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1303 /*FinalOverriders=*/0,
1304 BaseSubobject(Offset.VirtualBase,
1305 CharUnits::Zero()),
1306 /*BaseIsVirtual=*/true,
1307 /*OffsetInLayoutClass=*/
1308 CharUnits::Zero());
1309
1310 VCallOffsets = Builder.getVCallOffsets();
1311 }
1312
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001313 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001314 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1315 }
1316
1317 // Set the non-virtual part of the adjustment.
1318 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1319
1320 return Adjustment;
1321}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001322
1323void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1324 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001325 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1326 assert(ReturnAdjustment.isEmpty() &&
1327 "Destructor can't have return adjustment!");
1328
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001329 // Add both the complete destructor and the deleting destructor.
1330 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1331 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001332 } else {
1333 // Add the return adjustment if necessary.
1334 if (!ReturnAdjustment.isEmpty())
1335 VTableThunks[Components.size()].Return = ReturnAdjustment;
1336
1337 // Add the function.
1338 Components.push_back(VTableComponent::MakeFunction(MD));
1339 }
1340}
1341
1342/// OverridesIndirectMethodInBase - Return whether the given member function
1343/// overrides any methods in the set of given bases.
1344/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1345/// For example, if we have:
1346///
1347/// struct A { virtual void f(); }
1348/// struct B : A { virtual void f(); }
1349/// struct C : B { virtual void f(); }
1350///
1351/// OverridesIndirectMethodInBase will return true if given C::f as the method
1352/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001353static bool OverridesIndirectMethodInBases(
1354 const CXXMethodDecl *MD,
1355 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001356 if (Bases.count(MD->getParent()))
1357 return true;
1358
1359 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1360 E = MD->end_overridden_methods(); I != E; ++I) {
1361 const CXXMethodDecl *OverriddenMD = *I;
1362
1363 // Check "indirect overriders".
1364 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1365 return true;
1366 }
1367
1368 return false;
1369}
1370
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001371bool ItaniumVTableBuilder::IsOverriderUsed(
1372 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1373 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1374 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001375 // If the base and the first base in the primary base chain have the same
1376 // offsets, then this overrider will be used.
1377 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1378 return true;
1379
1380 // We know now that Base (or a direct or indirect base of it) is a primary
1381 // base in part of the class hierarchy, but not a primary base in the most
1382 // derived class.
1383
1384 // If the overrider is the first base in the primary base chain, we know
1385 // that the overrider will be used.
1386 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1387 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001388
1389 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001390
1391 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1392 PrimaryBases.insert(RD);
1393
1394 // Now traverse the base chain, starting with the first base, until we find
1395 // the base that is no longer a primary base.
1396 while (true) {
1397 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1398 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1399
1400 if (!PrimaryBase)
1401 break;
1402
1403 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001404 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001405 "Primary base should always be at offset 0!");
1406
1407 const ASTRecordLayout &LayoutClassLayout =
1408 Context.getASTRecordLayout(LayoutClass);
1409
1410 // Now check if this is the primary base that is not a primary base in the
1411 // most derived class.
1412 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1413 FirstBaseOffsetInLayoutClass) {
1414 // We found it, stop walking the chain.
1415 break;
1416 }
1417 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001418 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001419 "Primary base should always be at offset 0!");
1420 }
1421
1422 if (!PrimaryBases.insert(PrimaryBase))
1423 llvm_unreachable("Found a duplicate primary base!");
1424
1425 RD = PrimaryBase;
1426 }
1427
1428 // If the final overrider is an override of one of the primary bases,
1429 // then we know that it will be used.
1430 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1431}
1432
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001433typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1434
Peter Collingbournecfd23562011-09-26 01:57:12 +00001435/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1436/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001437/// The Bases are expected to be sorted in a base-to-derived order.
1438static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001439FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001440 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001441 OverriddenMethodsSetTy OverriddenMethods;
1442 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1443
1444 for (int I = Bases.size(), E = 0; I != E; --I) {
1445 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1446
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001447 // Now check the overridden methods.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001448 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1449 E = OverriddenMethods.end(); I != E; ++I) {
1450 const CXXMethodDecl *OverriddenMD = *I;
1451
1452 // We found our overridden method.
1453 if (OverriddenMD->getParent() == PrimaryBase)
1454 return OverriddenMD;
1455 }
1456 }
1457
1458 return 0;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001459}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001460
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001461void ItaniumVTableBuilder::AddMethods(
1462 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1463 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1464 CharUnits FirstBaseOffsetInLayoutClass,
1465 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001466 // Itanium C++ ABI 2.5.2:
1467 // The order of the virtual function pointers in a virtual table is the
1468 // order of declaration of the corresponding member functions in the class.
1469 //
1470 // There is an entry for any virtual function declared in a class,
1471 // whether it is a new function or overrides a base class function,
1472 // unless it overrides a function from the primary base, and conversion
1473 // between their return types does not require an adjustment.
1474
Peter Collingbournecfd23562011-09-26 01:57:12 +00001475 const CXXRecordDecl *RD = Base.getBase();
1476 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1477
1478 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1479 CharUnits PrimaryBaseOffset;
1480 CharUnits PrimaryBaseOffsetInLayoutClass;
1481 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001482 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001483 "Primary vbase should have a zero offset!");
1484
1485 const ASTRecordLayout &MostDerivedClassLayout =
1486 Context.getASTRecordLayout(MostDerivedClass);
1487
1488 PrimaryBaseOffset =
1489 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1490
1491 const ASTRecordLayout &LayoutClassLayout =
1492 Context.getASTRecordLayout(LayoutClass);
1493
1494 PrimaryBaseOffsetInLayoutClass =
1495 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1496 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001497 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001498 "Primary base should have a zero offset!");
1499
1500 PrimaryBaseOffset = Base.getBaseOffset();
1501 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1502 }
1503
1504 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1505 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1506 FirstBaseOffsetInLayoutClass, PrimaryBases);
1507
1508 if (!PrimaryBases.insert(PrimaryBase))
1509 llvm_unreachable("Found a duplicate primary base!");
1510 }
1511
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001512 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1513
1514 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1515 NewVirtualFunctionsTy NewVirtualFunctions;
1516
Peter Collingbournecfd23562011-09-26 01:57:12 +00001517 // Now go through all virtual member functions and add them.
1518 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1519 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001520 const CXXMethodDecl *MD = *I;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001521
1522 if (!MD->isVirtual())
1523 continue;
1524
1525 // Get the final overrider.
1526 FinalOverriders::OverriderInfo Overrider =
1527 Overriders.getOverrider(MD, Base.getBaseOffset());
1528
1529 // Check if this virtual member function overrides a method in a primary
1530 // base. If this is the case, and the return type doesn't require adjustment
1531 // then we can just use the member function from the primary base.
1532 if (const CXXMethodDecl *OverriddenMD =
1533 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1534 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1535 OverriddenMD).isEmpty()) {
1536 // Replace the method info of the overridden method with our own
1537 // method.
1538 assert(MethodInfoMap.count(OverriddenMD) &&
1539 "Did not find the overridden method!");
1540 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1541
1542 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1543 OverriddenMethodInfo.VTableIndex);
1544
1545 assert(!MethodInfoMap.count(MD) &&
1546 "Should not have method info for this method yet!");
1547
1548 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1549 MethodInfoMap.erase(OverriddenMD);
1550
1551 // If the overridden method exists in a virtual base class or a direct
1552 // or indirect base class of a virtual base class, we need to emit a
1553 // thunk if we ever have a class hierarchy where the base class is not
1554 // a primary base in the complete object.
1555 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1556 // Compute the this adjustment.
1557 ThisAdjustment ThisAdjustment =
1558 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1559 Overrider);
1560
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001561 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001562 Overrider.Method->getParent() == MostDerivedClass) {
1563
1564 // There's no return adjustment from OverriddenMD and MD,
1565 // but that doesn't mean there isn't one between MD and
1566 // the final overrider.
1567 BaseOffset ReturnAdjustmentOffset =
1568 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1569 ReturnAdjustment ReturnAdjustment =
1570 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1571
1572 // This is a virtual thunk for the most derived class, add it.
1573 AddThunk(Overrider.Method,
1574 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1575 }
1576 }
1577
1578 continue;
1579 }
1580 }
1581
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001582 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1583 if (MD->isImplicit()) {
1584 // Itanium C++ ABI 2.5.2:
1585 // If a class has an implicitly-defined virtual destructor,
1586 // its entries come after the declared virtual function pointers.
1587
1588 assert(!ImplicitVirtualDtor &&
1589 "Did already see an implicit virtual dtor!");
1590 ImplicitVirtualDtor = DD;
1591 continue;
1592 }
1593 }
1594
1595 NewVirtualFunctions.push_back(MD);
1596 }
1597
1598 if (ImplicitVirtualDtor)
1599 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1600
1601 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1602 E = NewVirtualFunctions.end(); I != E; ++I) {
1603 const CXXMethodDecl *MD = *I;
1604
1605 // Get the final overrider.
1606 FinalOverriders::OverriderInfo Overrider =
1607 Overriders.getOverrider(MD, Base.getBaseOffset());
1608
Peter Collingbournecfd23562011-09-26 01:57:12 +00001609 // Insert the method info for this method.
1610 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1611 Components.size());
1612
1613 assert(!MethodInfoMap.count(MD) &&
1614 "Should not have method info for this method yet!");
1615 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1616
1617 // Check if this overrider is going to be used.
1618 const CXXMethodDecl *OverriderMD = Overrider.Method;
1619 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1620 FirstBaseInPrimaryBaseChain,
1621 FirstBaseOffsetInLayoutClass)) {
1622 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1623 continue;
1624 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001625
Peter Collingbournecfd23562011-09-26 01:57:12 +00001626 // Check if this overrider needs a return adjustment.
1627 // We don't want to do this for pure virtual member functions.
1628 BaseOffset ReturnAdjustmentOffset;
1629 if (!OverriderMD->isPure()) {
1630 ReturnAdjustmentOffset =
1631 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1632 }
1633
1634 ReturnAdjustment ReturnAdjustment =
1635 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1636
1637 AddMethod(Overrider.Method, ReturnAdjustment);
1638 }
1639}
1640
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001641void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001642 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1643 CharUnits::Zero()),
1644 /*BaseIsMorallyVirtual=*/false,
1645 MostDerivedClassIsVirtual,
1646 MostDerivedClassOffset);
1647
1648 VisitedVirtualBasesSetTy VBases;
1649
1650 // Determine the primary virtual bases.
1651 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1652 VBases);
1653 VBases.clear();
1654
1655 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1656
1657 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001659 if (IsAppleKext)
1660 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1661}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001662
1663void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1664 BaseSubobject Base, bool BaseIsMorallyVirtual,
1665 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001666 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1667
1668 // Add vcall and vbase offsets for this vtable.
1669 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1670 Base, BaseIsVirtualInLayoutClass,
1671 OffsetInLayoutClass);
1672 Components.append(Builder.components_begin(), Builder.components_end());
1673
1674 // Check if we need to add these vcall offsets.
1675 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1676 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1677
1678 if (VCallOffsets.empty())
1679 VCallOffsets = Builder.getVCallOffsets();
1680 }
1681
1682 // If we're laying out the most derived class we want to keep track of the
1683 // virtual base class offset offsets.
1684 if (Base.getBase() == MostDerivedClass)
1685 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1686
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001687 // Add the offset to top.
1688 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1689 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001690
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001691 // Next, add the RTTI.
1692 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001693
Peter Collingbournecfd23562011-09-26 01:57:12 +00001694 uint64_t AddressPoint = Components.size();
1695
1696 // Now go through all virtual member functions and add them.
1697 PrimaryBasesSetVectorTy PrimaryBases;
1698 AddMethods(Base, OffsetInLayoutClass,
1699 Base.getBase(), OffsetInLayoutClass,
1700 PrimaryBases);
1701
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001702 const CXXRecordDecl *RD = Base.getBase();
1703 if (RD == MostDerivedClass) {
1704 assert(MethodVTableIndices.empty());
1705 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1706 E = MethodInfoMap.end(); I != E; ++I) {
1707 const CXXMethodDecl *MD = I->first;
1708 const MethodInfo &MI = I->second;
1709 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001710 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1711 = MI.VTableIndex - AddressPoint;
1712 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1713 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001714 } else {
1715 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1716 }
1717 }
1718 }
1719
Peter Collingbournecfd23562011-09-26 01:57:12 +00001720 // Compute 'this' pointer adjustments.
1721 ComputeThisAdjustments();
1722
1723 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001724 while (true) {
1725 AddressPoints.insert(std::make_pair(
1726 BaseSubobject(RD, OffsetInLayoutClass),
1727 AddressPoint));
1728
1729 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1730 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1731
1732 if (!PrimaryBase)
1733 break;
1734
1735 if (Layout.isPrimaryBaseVirtual()) {
1736 // Check if this virtual primary base is a primary base in the layout
1737 // class. If it's not, we don't want to add it.
1738 const ASTRecordLayout &LayoutClassLayout =
1739 Context.getASTRecordLayout(LayoutClass);
1740
1741 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1742 OffsetInLayoutClass) {
1743 // We don't want to add this class (or any of its primary bases).
1744 break;
1745 }
1746 }
1747
1748 RD = PrimaryBase;
1749 }
1750
1751 // Layout secondary vtables.
1752 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1753}
1754
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001755void
1756ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1757 bool BaseIsMorallyVirtual,
1758 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001759 // Itanium C++ ABI 2.5.2:
1760 // Following the primary virtual table of a derived class are secondary
1761 // virtual tables for each of its proper base classes, except any primary
1762 // base(s) with which it shares its primary virtual table.
1763
1764 const CXXRecordDecl *RD = Base.getBase();
1765 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1766 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1767
1768 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1769 E = RD->bases_end(); I != E; ++I) {
1770 // Ignore virtual bases, we'll emit them later.
1771 if (I->isVirtual())
1772 continue;
1773
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00001774 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001775
1776 // Ignore bases that don't have a vtable.
1777 if (!BaseDecl->isDynamicClass())
1778 continue;
1779
1780 if (isBuildingConstructorVTable()) {
1781 // Itanium C++ ABI 2.6.4:
1782 // Some of the base class subobjects may not need construction virtual
1783 // tables, which will therefore not be present in the construction
1784 // virtual table group, even though the subobject virtual tables are
1785 // present in the main virtual table group for the complete object.
1786 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1787 continue;
1788 }
1789
1790 // Get the base offset of this base.
1791 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1792 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1793
1794 CharUnits BaseOffsetInLayoutClass =
1795 OffsetInLayoutClass + RelativeBaseOffset;
1796
1797 // Don't emit a secondary vtable for a primary base. We might however want
1798 // to emit secondary vtables for other bases of this base.
1799 if (BaseDecl == PrimaryBase) {
1800 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1801 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1802 continue;
1803 }
1804
1805 // Layout the primary vtable (and any secondary vtables) for this base.
1806 LayoutPrimaryAndSecondaryVTables(
1807 BaseSubobject(BaseDecl, BaseOffset),
1808 BaseIsMorallyVirtual,
1809 /*BaseIsVirtualInLayoutClass=*/false,
1810 BaseOffsetInLayoutClass);
1811 }
1812}
1813
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001814void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1815 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1816 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001817 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1818
1819 // Check if this base has a primary base.
1820 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1821
1822 // Check if it's virtual.
1823 if (Layout.isPrimaryBaseVirtual()) {
1824 bool IsPrimaryVirtualBase = true;
1825
1826 if (isBuildingConstructorVTable()) {
1827 // Check if the base is actually a primary base in the class we use for
1828 // layout.
1829 const ASTRecordLayout &LayoutClassLayout =
1830 Context.getASTRecordLayout(LayoutClass);
1831
1832 CharUnits PrimaryBaseOffsetInLayoutClass =
1833 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1834
1835 // We know that the base is not a primary base in the layout class if
1836 // the base offsets are different.
1837 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1838 IsPrimaryVirtualBase = false;
1839 }
1840
1841 if (IsPrimaryVirtualBase)
1842 PrimaryVirtualBases.insert(PrimaryBase);
1843 }
1844 }
1845
1846 // Traverse bases, looking for more primary virtual bases.
1847 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1848 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00001849 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001850
1851 CharUnits BaseOffsetInLayoutClass;
1852
1853 if (I->isVirtual()) {
1854 if (!VBases.insert(BaseDecl))
1855 continue;
1856
1857 const ASTRecordLayout &LayoutClassLayout =
1858 Context.getASTRecordLayout(LayoutClass);
1859
1860 BaseOffsetInLayoutClass =
1861 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1862 } else {
1863 BaseOffsetInLayoutClass =
1864 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1865 }
1866
1867 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1868 }
1869}
1870
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001871void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1872 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001873 // Itanium C++ ABI 2.5.2:
1874 // Then come the virtual base virtual tables, also in inheritance graph
1875 // order, and again excluding primary bases (which share virtual tables with
1876 // the classes for which they are primary).
1877 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1878 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00001879 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001880
1881 // Check if this base needs a vtable. (If it's virtual, not a primary base
1882 // of some other class, and we haven't visited it before).
1883 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1884 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1885 const ASTRecordLayout &MostDerivedClassLayout =
1886 Context.getASTRecordLayout(MostDerivedClass);
1887 CharUnits BaseOffset =
1888 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1889
1890 const ASTRecordLayout &LayoutClassLayout =
1891 Context.getASTRecordLayout(LayoutClass);
1892 CharUnits BaseOffsetInLayoutClass =
1893 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1894
1895 LayoutPrimaryAndSecondaryVTables(
1896 BaseSubobject(BaseDecl, BaseOffset),
1897 /*BaseIsMorallyVirtual=*/true,
1898 /*BaseIsVirtualInLayoutClass=*/true,
1899 BaseOffsetInLayoutClass);
1900 }
1901
1902 // We only need to check the base for virtual base vtables if it actually
1903 // has virtual bases.
1904 if (BaseDecl->getNumVBases())
1905 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1906 }
1907}
1908
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00001909struct ItaniumThunkInfoComparator {
1910 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
1911 assert(LHS.Method == 0);
1912 assert(RHS.Method == 0);
1913
1914 if (LHS.This != RHS.This)
1915 return LHS.This < RHS.This;
1916
1917 if (LHS.Return != RHS.Return)
1918 return LHS.Return < RHS.Return;
1919
1920 return false;
1921 }
1922};
1923
Peter Collingbournecfd23562011-09-26 01:57:12 +00001924/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001925void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001926 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001927 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001928
1929 if (isBuildingConstructorVTable()) {
1930 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001931 MostDerivedClass->printQualifiedName(Out);
1932 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001933 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001934 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001935 } else {
1936 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001937 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001938 }
1939 Out << "' (" << Components.size() << " entries).\n";
1940
1941 // Iterate through the address points and insert them into a new map where
1942 // they are keyed by the index and not the base object.
1943 // Since an address point can be shared by multiple subobjects, we use an
1944 // STL multimap.
1945 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1946 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1947 E = AddressPoints.end(); I != E; ++I) {
1948 const BaseSubobject& Base = I->first;
1949 uint64_t Index = I->second;
1950
1951 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1952 }
1953
1954 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1955 uint64_t Index = I;
1956
1957 Out << llvm::format("%4d | ", I);
1958
1959 const VTableComponent &Component = Components[I];
1960
1961 // Dump the component.
1962 switch (Component.getKind()) {
1963
1964 case VTableComponent::CK_VCallOffset:
1965 Out << "vcall_offset ("
1966 << Component.getVCallOffset().getQuantity()
1967 << ")";
1968 break;
1969
1970 case VTableComponent::CK_VBaseOffset:
1971 Out << "vbase_offset ("
1972 << Component.getVBaseOffset().getQuantity()
1973 << ")";
1974 break;
1975
1976 case VTableComponent::CK_OffsetToTop:
1977 Out << "offset_to_top ("
1978 << Component.getOffsetToTop().getQuantity()
1979 << ")";
1980 break;
1981
1982 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001983 Component.getRTTIDecl()->printQualifiedName(Out);
1984 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001985 break;
1986
1987 case VTableComponent::CK_FunctionPointer: {
1988 const CXXMethodDecl *MD = Component.getFunctionDecl();
1989
1990 std::string Str =
1991 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1992 MD);
1993 Out << Str;
1994 if (MD->isPure())
1995 Out << " [pure]";
1996
David Blaikie596d2ca2012-10-16 20:25:33 +00001997 if (MD->isDeleted())
1998 Out << " [deleted]";
1999
Peter Collingbournecfd23562011-09-26 01:57:12 +00002000 ThunkInfo Thunk = VTableThunks.lookup(I);
2001 if (!Thunk.isEmpty()) {
2002 // If this function pointer has a return adjustment, dump it.
2003 if (!Thunk.Return.isEmpty()) {
2004 Out << "\n [return adjustment: ";
2005 Out << Thunk.Return.NonVirtual << " non-virtual";
2006
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002007 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2008 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002009 Out << " vbase offset offset";
2010 }
2011
2012 Out << ']';
2013 }
2014
2015 // If this function pointer has a 'this' pointer adjustment, dump it.
2016 if (!Thunk.This.isEmpty()) {
2017 Out << "\n [this adjustment: ";
2018 Out << Thunk.This.NonVirtual << " non-virtual";
2019
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002020 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2021 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002022 Out << " vcall offset offset";
2023 }
2024
2025 Out << ']';
2026 }
2027 }
2028
2029 break;
2030 }
2031
2032 case VTableComponent::CK_CompleteDtorPointer:
2033 case VTableComponent::CK_DeletingDtorPointer: {
2034 bool IsComplete =
2035 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2036
2037 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2038
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002039 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002040 if (IsComplete)
2041 Out << "() [complete]";
2042 else
2043 Out << "() [deleting]";
2044
2045 if (DD->isPure())
2046 Out << " [pure]";
2047
2048 ThunkInfo Thunk = VTableThunks.lookup(I);
2049 if (!Thunk.isEmpty()) {
2050 // If this destructor has a 'this' pointer adjustment, dump it.
2051 if (!Thunk.This.isEmpty()) {
2052 Out << "\n [this adjustment: ";
2053 Out << Thunk.This.NonVirtual << " non-virtual";
2054
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002055 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2056 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002057 Out << " vcall offset offset";
2058 }
2059
2060 Out << ']';
2061 }
2062 }
2063
2064 break;
2065 }
2066
2067 case VTableComponent::CK_UnusedFunctionPointer: {
2068 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2069
2070 std::string Str =
2071 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2072 MD);
2073 Out << "[unused] " << Str;
2074 if (MD->isPure())
2075 Out << " [pure]";
2076 }
2077
2078 }
2079
2080 Out << '\n';
2081
2082 // Dump the next address point.
2083 uint64_t NextIndex = Index + 1;
2084 if (AddressPointsByIndex.count(NextIndex)) {
2085 if (AddressPointsByIndex.count(NextIndex) == 1) {
2086 const BaseSubobject &Base =
2087 AddressPointsByIndex.find(NextIndex)->second;
2088
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002089 Out << " -- (";
2090 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002091 Out << ", " << Base.getBaseOffset().getQuantity();
2092 Out << ") vtable address --\n";
2093 } else {
2094 CharUnits BaseOffset =
2095 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2096
2097 // We store the class names in a set to get a stable order.
2098 std::set<std::string> ClassNames;
2099 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2100 AddressPointsByIndex.lower_bound(NextIndex), E =
2101 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2102 assert(I->second.getBaseOffset() == BaseOffset &&
2103 "Invalid base offset!");
2104 const CXXRecordDecl *RD = I->second.getBase();
2105 ClassNames.insert(RD->getQualifiedNameAsString());
2106 }
2107
2108 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2109 E = ClassNames.end(); I != E; ++I) {
2110 Out << " -- (" << *I;
2111 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2112 }
2113 }
2114 }
2115 }
2116
2117 Out << '\n';
2118
2119 if (isBuildingConstructorVTable())
2120 return;
2121
2122 if (MostDerivedClass->getNumVBases()) {
2123 // We store the virtual base class names and their offsets in a map to get
2124 // a stable order.
2125
2126 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2127 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2128 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2129 std::string ClassName = I->first->getQualifiedNameAsString();
2130 CharUnits OffsetOffset = I->second;
2131 ClassNamesAndOffsets.insert(
2132 std::make_pair(ClassName, OffsetOffset));
2133 }
2134
2135 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002136 MostDerivedClass->printQualifiedName(Out);
2137 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002138 Out << ClassNamesAndOffsets.size();
2139 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2140
2141 for (std::map<std::string, CharUnits>::const_iterator I =
2142 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2143 I != E; ++I)
2144 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2145
2146 Out << "\n";
2147 }
2148
2149 if (!Thunks.empty()) {
2150 // We store the method names in a map to get a stable order.
2151 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2152
2153 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2154 I != E; ++I) {
2155 const CXXMethodDecl *MD = I->first;
2156 std::string MethodName =
2157 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2158 MD);
2159
2160 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2161 }
2162
2163 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2164 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2165 I != E; ++I) {
2166 const std::string &MethodName = I->first;
2167 const CXXMethodDecl *MD = I->second;
2168
2169 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002170 std::sort(ThunksVector.begin(), ThunksVector.end(),
2171 ItaniumThunkInfoComparator());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002172
2173 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2174 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2175
2176 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2177 const ThunkInfo &Thunk = ThunksVector[I];
2178
2179 Out << llvm::format("%4d | ", I);
2180
2181 // If this function pointer has a return pointer adjustment, dump it.
2182 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002183 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002184 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002185 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2186 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002187 Out << " vbase offset offset";
2188 }
2189
2190 if (!Thunk.This.isEmpty())
2191 Out << "\n ";
2192 }
2193
2194 // If this function pointer has a 'this' pointer adjustment, dump it.
2195 if (!Thunk.This.isEmpty()) {
2196 Out << "this adjustment: ";
2197 Out << Thunk.This.NonVirtual << " non-virtual";
2198
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002199 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2200 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002201 Out << " vcall offset offset";
2202 }
2203 }
2204
2205 Out << '\n';
2206 }
2207
2208 Out << '\n';
2209 }
2210 }
2211
2212 // Compute the vtable indices for all the member functions.
2213 // Store them in a map keyed by the index so we'll get a sorted table.
2214 std::map<uint64_t, std::string> IndicesMap;
2215
2216 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2217 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002218 const CXXMethodDecl *MD = *i;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002219
2220 // We only want virtual member functions.
2221 if (!MD->isVirtual())
2222 continue;
2223
2224 std::string MethodName =
2225 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2226 MD);
2227
2228 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002229 GlobalDecl GD(DD, Dtor_Complete);
2230 assert(MethodVTableIndices.count(GD));
2231 uint64_t VTableIndex = MethodVTableIndices[GD];
2232 IndicesMap[VTableIndex] = MethodName + " [complete]";
2233 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002234 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002235 assert(MethodVTableIndices.count(MD));
2236 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002237 }
2238 }
2239
2240 // Print the vtable indices for all the member functions.
2241 if (!IndicesMap.empty()) {
2242 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002243 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002244 Out << "' (" << IndicesMap.size() << " entries).\n";
2245
2246 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2247 E = IndicesMap.end(); I != E; ++I) {
2248 uint64_t VTableIndex = I->first;
2249 const std::string &MethodName = I->second;
2250
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002251 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002252 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002253 }
2254 }
2255
2256 Out << '\n';
2257}
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002258
2259struct VTableThunksComparator {
2260 bool operator()(const VTableLayout::VTableThunkTy &LHS,
2261 const VTableLayout::VTableThunkTy &RHS) {
2262 if (LHS.first == RHS.first) {
2263 assert(LHS.second == RHS.second &&
2264 "Different thunks should have unique indices!");
2265 }
2266 return LHS.first < RHS.first;
2267 }
2268};
Peter Collingbournecfd23562011-09-26 01:57:12 +00002269}
2270
2271VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2272 const VTableComponent *VTableComponents,
2273 uint64_t NumVTableThunks,
2274 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002275 const AddressPointsMapTy &AddressPoints,
2276 bool IsMicrosoftABI)
Peter Collingbournecfd23562011-09-26 01:57:12 +00002277 : NumVTableComponents(NumVTableComponents),
2278 VTableComponents(new VTableComponent[NumVTableComponents]),
2279 NumVTableThunks(NumVTableThunks),
2280 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002281 AddressPoints(AddressPoints),
2282 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002283 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramere2980632012-04-14 14:13:43 +00002284 this->VTableComponents.get());
2285 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2286 this->VTableThunks.get());
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002287 std::sort(this->VTableThunks.get(),
2288 this->VTableThunks.get() + NumVTableThunks,
2289 VTableThunksComparator());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002290}
2291
Benjamin Kramere2980632012-04-14 14:13:43 +00002292VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002293
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002294ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002295 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002296
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002297ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002298 llvm::DeleteContainerSeconds(VTableLayouts);
2299}
2300
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002301uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002302 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2303 if (I != MethodVTableIndices.end())
2304 return I->second;
2305
2306 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2307
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002308 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002309
2310 I = MethodVTableIndices.find(GD);
2311 assert(I != MethodVTableIndices.end() && "Did not find index!");
2312 return I->second;
2313}
2314
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002315CharUnits
2316ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2317 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002318 ClassPairTy ClassPair(RD, VBase);
2319
2320 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2321 VirtualBaseClassOffsetOffsets.find(ClassPair);
2322 if (I != VirtualBaseClassOffsetOffsets.end())
2323 return I->second;
2324
2325 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2326 BaseSubobject(RD, CharUnits::Zero()),
2327 /*BaseIsVirtual=*/false,
2328 /*OffsetInLayoutClass=*/CharUnits::Zero());
2329
2330 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2331 Builder.getVBaseOffsetOffsets().begin(),
2332 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2333 // Insert all types.
2334 ClassPairTy ClassPair(RD, I->first);
2335
2336 VirtualBaseClassOffsetOffsets.insert(
2337 std::make_pair(ClassPair, I->second));
2338 }
2339
2340 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2341 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2342
2343 return I->second;
2344}
2345
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002346static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002347 SmallVector<VTableLayout::VTableThunkTy, 1>
2348 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002349
2350 return new VTableLayout(Builder.getNumVTableComponents(),
2351 Builder.vtable_component_begin(),
2352 VTableThunks.size(),
2353 VTableThunks.data(),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002354 Builder.getAddressPoints(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002355 /*IsMicrosoftABI=*/false);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002356}
2357
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002358void
2359ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002360 const VTableLayout *&Entry = VTableLayouts[RD];
2361
2362 // Check if we've computed this information before.
2363 if (Entry)
2364 return;
2365
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002366 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2367 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002368 Entry = CreateVTableLayout(Builder);
2369
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002370 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2371 Builder.vtable_indices_end());
2372
Peter Collingbournecfd23562011-09-26 01:57:12 +00002373 // Add the known thunks.
2374 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2375
2376 // If we don't have the vbase information for this class, insert it.
2377 // getVirtualBaseOffsetOffset will compute it separately without computing
2378 // the rest of the vtable related information.
2379 if (!RD->getNumVBases())
2380 return;
2381
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002382 const CXXRecordDecl *VBase =
2383 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002384
2385 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2386 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002387
2388 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2389 I = Builder.getVBaseOffsetOffsets().begin(),
2390 E = Builder.getVBaseOffsetOffsets().end();
2391 I != E; ++I) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002392 // Insert all types.
2393 ClassPairTy ClassPair(RD, I->first);
2394
2395 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2396 }
2397}
2398
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002399VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2400 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2401 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2402 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2403 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002404 return CreateVTableLayout(Builder);
2405}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002406
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002407namespace {
2408
2409// Vtables in the Microsoft ABI are different from the Itanium ABI.
2410//
2411// The main differences are:
2412// 1. Separate vftable and vbtable.
2413//
2414// 2. Each subobject with a vfptr gets its own vftable rather than an address
2415// point in a single vtable shared between all the subobjects.
2416// Each vftable is represented by a separate section and virtual calls
2417// must be done using the vftable which has a slot for the function to be
2418// called.
2419//
2420// 3. Virtual method definitions expect their 'this' parameter to point to the
2421// first vfptr whose table provides a compatible overridden method. In many
2422// cases, this permits the original vf-table entry to directly call
2423// the method instead of passing through a thunk.
2424//
2425// A compatible overridden method is one which does not have a non-trivial
2426// covariant-return adjustment.
2427//
2428// The first vfptr is the one with the lowest offset in the complete-object
2429// layout of the defining class, and the method definition will subtract
2430// that constant offset from the parameter value to get the real 'this'
2431// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2432// function defined in a virtual base is overridden in a more derived
2433// virtual base and these bases have a reverse order in the complete
2434// object), the vf-table may require a this-adjustment thunk.
2435//
2436// 4. vftables do not contain new entries for overrides that merely require
2437// this-adjustment. Together with #3, this keeps vf-tables smaller and
2438// eliminates the need for this-adjustment thunks in many cases, at the cost
2439// of often requiring redundant work to adjust the "this" pointer.
2440//
2441// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2442// Vtordisps are emitted into the class layout if a class has
2443// a) a user-defined ctor/dtor
2444// and
2445// b) a method overriding a method in a virtual base.
2446
2447class VFTableBuilder {
2448public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002449 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002450
2451 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2452 MethodVFTableLocationsTy;
2453
2454private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002455 /// VTables - Global vtable information.
2456 MicrosoftVTableContext &VTables;
2457
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002458 /// Context - The ASTContext which we will use for layout information.
2459 ASTContext &Context;
2460
2461 /// MostDerivedClass - The most derived class for which we're building this
2462 /// vtable.
2463 const CXXRecordDecl *MostDerivedClass;
2464
2465 const ASTRecordLayout &MostDerivedClassLayout;
2466
2467 VFPtrInfo WhichVFPtr;
2468
2469 /// FinalOverriders - The final overriders of the most derived class.
2470 const FinalOverriders Overriders;
2471
2472 /// Components - The components of the vftable being built.
2473 SmallVector<VTableComponent, 64> Components;
2474
2475 MethodVFTableLocationsTy MethodVFTableLocations;
2476
2477 /// MethodInfo - Contains information about a method in a vtable.
2478 /// (Used for computing 'this' pointer adjustment thunks.
2479 struct MethodInfo {
2480 /// VBTableIndex - The nonzero index in the vbtable that
2481 /// this method's base has, or zero.
2482 const uint64_t VBTableIndex;
2483
2484 /// VFTableIndex - The index in the vftable that this method has.
2485 const uint64_t VFTableIndex;
2486
2487 /// Shadowed - Indicates if this vftable slot is shadowed by
2488 /// a slot for a covariant-return override. If so, it shouldn't be printed
2489 /// or used for vcalls in the most derived class.
2490 bool Shadowed;
2491
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002492 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2493 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002494 Shadowed(false) {}
2495
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002496 MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002497 };
2498
2499 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2500
2501 /// MethodInfoMap - The information for all methods in the vftable we're
2502 /// currently building.
2503 MethodInfoMapTy MethodInfoMap;
2504
2505 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2506
2507 /// VTableThunks - The thunks by vftable index in the vftable currently being
2508 /// built.
2509 VTableThunksMapTy VTableThunks;
2510
2511 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2512 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2513
2514 /// Thunks - A map that contains all the thunks needed for all methods in the
2515 /// most derived class for which the vftable is currently being built.
2516 ThunksMapTy Thunks;
2517
2518 /// AddThunk - Add a thunk for the given method.
2519 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2520 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2521
2522 // Check if we have this thunk already.
2523 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2524 ThunksVector.end())
2525 return;
2526
2527 ThunksVector.push_back(Thunk);
2528 }
2529
2530 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2531 /// method in the given subobject, relative to the beginning of the
2532 /// MostDerivedClass.
2533 CharUnits ComputeThisOffset(const CXXMethodDecl *MD,
2534 BaseSubobject Base,
2535 FinalOverriders::OverriderInfo Overrider);
2536
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002537 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2538 CharUnits ThisOffset, ThisAdjustment &TA);
2539
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002540 /// AddMethod - Add a single virtual member function to the vftable
2541 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002542 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002543 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002544 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002545 "Destructor can't have return adjustment!");
2546 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2547 } else {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002548 if (!TI.isEmpty())
2549 VTableThunks[Components.size()] = TI;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002550 Components.push_back(VTableComponent::MakeFunction(MD));
2551 }
2552 }
2553
Reid Kleckner558cab22013-12-27 19:45:53 +00002554 bool NeedsReturnAdjustingThunk(const CXXMethodDecl *MD);
Reid Kleckner604c8b42013-12-27 19:43:59 +00002555
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002556 /// AddMethods - Add the methods of this base subobject and the relevant
2557 /// subbases to the vftable we're currently laying out.
2558 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2559 const CXXRecordDecl *LastVBase,
2560 BasesSetVectorTy &VisitedBases);
2561
2562 void LayoutVFTable() {
2563 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2564 // pointing to the middle of a section.
2565
2566 BasesSetVectorTy VisitedBases;
2567 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2568 VisitedBases);
2569
2570 assert(MethodVFTableLocations.empty());
2571 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2572 E = MethodInfoMap.end(); I != E; ++I) {
2573 const CXXMethodDecl *MD = I->first;
2574 const MethodInfo &MI = I->second;
2575 // Skip the methods that the MostDerivedClass didn't override
2576 // and the entries shadowed by return adjusting thunks.
2577 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2578 continue;
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002579 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.LastVBase,
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002580 WhichVFPtr.VFPtrOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002581 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2582 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2583 } else {
2584 MethodVFTableLocations[MD] = Loc;
2585 }
2586 }
2587 }
2588
2589 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2590 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2591 unsigned DiagID = Diags.getCustomDiagID(
2592 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2593 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2594 }
2595
2596public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002597 VFTableBuilder(MicrosoftVTableContext &VTables,
2598 const CXXRecordDecl *MostDerivedClass, VFPtrInfo Which)
2599 : VTables(VTables),
2600 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002601 MostDerivedClass(MostDerivedClass),
2602 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2603 WhichVFPtr(Which),
2604 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2605 LayoutVFTable();
2606
2607 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002608 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002609 }
2610
2611 uint64_t getNumThunks() const { return Thunks.size(); }
2612
2613 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2614
2615 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2616
2617 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2618 return MethodVFTableLocations.begin();
2619 }
2620
2621 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2622 return MethodVFTableLocations.end();
2623 }
2624
2625 uint64_t getNumVTableComponents() const { return Components.size(); }
2626
2627 const VTableComponent *vtable_component_begin() const {
2628 return Components.begin();
2629 }
2630
2631 const VTableComponent *vtable_component_end() const {
2632 return Components.end();
2633 }
2634
2635 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2636 return VTableThunks.begin();
2637 }
2638
2639 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2640 return VTableThunks.end();
2641 }
2642
2643 void dumpLayout(raw_ostream &);
2644};
2645
Reid Klecknerb40a27d2014-01-03 00:14:35 +00002646} // end namespace
2647
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002648/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2649/// that define the given method.
2650struct InitialOverriddenDefinitionCollector {
2651 BasesSetVectorTy Bases;
2652 OverriddenMethodsSetTy VisitedOverriddenMethods;
2653
2654 bool visit(const CXXMethodDecl *OverriddenMD) {
2655 if (OverriddenMD->size_overridden_methods() == 0)
2656 Bases.insert(OverriddenMD->getParent());
2657 // Don't recurse on this method if we've already collected it.
2658 return VisitedOverriddenMethods.insert(OverriddenMD);
2659 }
2660};
2661
2662static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2663 CXXBasePath &Path, void *BasesSet) {
2664 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2665 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2666}
2667
2668CharUnits
2669VFTableBuilder::ComputeThisOffset(const CXXMethodDecl *MD,
2670 BaseSubobject Base,
2671 FinalOverriders::OverriderInfo Overrider) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002672 InitialOverriddenDefinitionCollector Collector;
2673 visitAllOverriddenMethods(MD, Collector);
2674
2675 CXXBasePaths Paths;
2676 Base.getBase()->lookupInBases(BaseInSet, &Collector.Bases, Paths);
2677
2678 // This will hold the smallest this offset among overridees of MD.
2679 // This implies that an offset of a non-virtual base will dominate an offset
2680 // of a virtual base to potentially reduce the number of thunks required
2681 // in the derived classes that inherit this method.
2682 CharUnits Ret;
2683 bool First = true;
2684
2685 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2686 I != E; ++I) {
2687 const CXXBasePath &Path = (*I);
2688 CharUnits ThisOffset = Base.getBaseOffset();
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002689 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002690
2691 // For each path from the overrider to the parents of the overridden methods,
2692 // traverse the path, calculating the this offset in the most derived class.
2693 for (int J = 0, F = Path.size(); J != F; ++J) {
2694 const CXXBasePathElement &Element = Path[J];
2695 QualType CurTy = Element.Base->getType();
2696 const CXXRecordDecl *PrevRD = Element.Class,
2697 *CurRD = CurTy->getAsCXXRecordDecl();
2698 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2699
2700 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002701 LastVBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002702 if (Overrider.Method->getParent() == PrevRD) {
2703 // This one's interesting. If the final overrider is in a vbase B of the
2704 // most derived class and it overrides a method of the B's own vbase A,
2705 // it uses A* as "this". In its prologue, it can cast A* to B* with
2706 // a static offset. This offset is used regardless of the actual
2707 // offset of A from B in the most derived class, requiring an
2708 // this-adjusting thunk in the vftable if A and B are laid out
2709 // differently in the most derived class.
2710 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2711 } else {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002712 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002713 }
2714 } else {
2715 ThisOffset += Layout.getBaseClassOffset(CurRD);
2716 }
2717 }
2718
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002719 if (isa<CXXDestructorDecl>(MD)) {
2720 if (LastVBaseOffset.isZero()) {
2721 // If a "Base" class has at least one non-virtual base with a virtual
2722 // destructor, the "Base" virtual destructor will take the address
2723 // of the "Base" subobject as the "this" argument.
2724 return Base.getBaseOffset();
2725 } else {
2726 // A virtual destructor of a virtual base takes the address of the
2727 // virtual base subobject as the "this" argument.
2728 return LastVBaseOffset;
2729 }
2730 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002731
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002732 if (Ret > ThisOffset || First) {
2733 First = false;
2734 Ret = ThisOffset;
2735 }
2736 }
2737
2738 assert(!First && "Method not found in the given subobject?");
2739 return Ret;
2740}
2741
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002742void VFTableBuilder::CalculateVtordispAdjustment(
2743 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2744 ThisAdjustment &TA) {
2745 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2746 MostDerivedClassLayout.getVBaseOffsetsMap();
2747 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
2748 VBaseMap.find(WhichVFPtr.LastVBase);
2749 assert(VBaseMapEntry != VBaseMap.end());
2750
2751 // Check if we need a vtordisp adjustment at all.
2752 if (!VBaseMapEntry->second.hasVtorDisp())
2753 return;
2754
2755 CharUnits VFPtrVBaseOffset = VBaseMapEntry->second.VBaseOffset;
2756 // The implicit vtordisp field is located right before the vbase.
2757 TA.Virtual.Microsoft.VtordispOffset =
2758 (VFPtrVBaseOffset - WhichVFPtr.VFPtrFullOffset).getQuantity() - 4;
2759
2760 // If the final overrider is defined in either:
2761 // - the most derived class or its non-virtual base or
2762 // - the same vbase as the initial declaration,
2763 // a simple vtordisp thunk will suffice.
2764 const CXXRecordDecl *OverriderRD = Overrider.Method->getParent();
2765 if (OverriderRD == MostDerivedClass)
2766 return;
2767
2768 const CXXRecordDecl *OverriderVBase =
2769 ComputeBaseOffset(Context, OverriderRD, MostDerivedClass).VirtualBase;
2770 if (!OverriderVBase || OverriderVBase == WhichVFPtr.LastVBase)
2771 return;
2772
2773 // Otherwise, we need to do use the dynamic offset of the final overrider
2774 // in order to get "this" adjustment right.
2775 TA.Virtual.Microsoft.VBPtrOffset =
2776 (VFPtrVBaseOffset + WhichVFPtr.VFPtrOffset -
2777 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2778 TA.Virtual.Microsoft.VBOffsetOffset =
2779 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2780 VTables.getVBTableIndex(MostDerivedClass, OverriderVBase);
2781
2782 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2783}
2784
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002785static void GroupNewVirtualOverloads(
2786 const CXXRecordDecl *RD,
2787 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2788 // Put the virtual methods into VirtualMethods in the proper order:
2789 // 1) Group overloads by declaration name. New groups are added to the
2790 // vftable in the order of their first declarations in this class
2791 // (including overrides).
2792 // 2) In each group, new overloads appear in the reverse order of declaration.
2793 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2794 SmallVector<MethodGroup, 10> Groups;
2795 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2796 VisitedGroupIndicesTy VisitedGroupIndices;
2797 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2798 E = RD->method_end(); I != E; ++I) {
2799 const CXXMethodDecl *MD = *I;
2800 if (!MD->isVirtual())
2801 continue;
2802
2803 VisitedGroupIndicesTy::iterator J;
2804 bool Inserted;
2805 llvm::tie(J, Inserted) = VisitedGroupIndices.insert(
2806 std::make_pair(MD->getDeclName(), Groups.size()));
2807 if (Inserted)
2808 Groups.push_back(MethodGroup(1, MD));
2809 else
2810 Groups[J->second].push_back(MD);
2811 }
2812
2813 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2814 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2815}
2816
Reid Kleckner604c8b42013-12-27 19:43:59 +00002817/// We need a return adjusting thunk for this method if its return type is
2818/// not trivially convertible to the return type of any of its overridden
2819/// methods.
2820bool VFTableBuilder::NeedsReturnAdjustingThunk(const CXXMethodDecl *MD) {
2821 OverriddenMethodsSetTy OverriddenMethods;
2822 ComputeAllOverriddenMethods(MD, OverriddenMethods);
2823 for (OverriddenMethodsSetTy::iterator I = OverriddenMethods.begin(),
2824 E = OverriddenMethods.end();
2825 I != E; ++I) {
2826 const CXXMethodDecl *OverriddenMD = *I;
2827 BaseOffset Adjustment =
2828 ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD);
2829 if (!Adjustment.isEmpty())
2830 return true;
2831 }
2832 return false;
2833}
2834
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002835void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2836 const CXXRecordDecl *LastVBase,
2837 BasesSetVectorTy &VisitedBases) {
2838 const CXXRecordDecl *RD = Base.getBase();
2839 if (!RD->isPolymorphic())
2840 return;
2841
2842 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2843
2844 // See if this class expands a vftable of the base we look at, which is either
2845 // the one defined by the vfptr base path or the primary base of the current class.
2846 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2847 CharUnits NextBaseOffset;
2848 if (BaseDepth < WhichVFPtr.PathToBaseWithVFPtr.size()) {
2849 NextBase = WhichVFPtr.PathToBaseWithVFPtr[BaseDepth];
2850 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2851 NextLastVBase = NextBase;
2852 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2853 } else {
2854 NextBaseOffset =
2855 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2856 }
2857 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2858 assert(!Layout.isPrimaryBaseVirtual() &&
2859 "No primary virtual bases in this ABI");
2860 NextBase = PrimaryBase;
2861 NextBaseOffset = Base.getBaseOffset();
2862 }
2863
2864 if (NextBase) {
2865 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2866 NextLastVBase, VisitedBases);
2867 if (!VisitedBases.insert(NextBase))
2868 llvm_unreachable("Found a duplicate primary base!");
2869 }
2870
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002871 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2872 // Put virtual methods in the proper order.
2873 GroupNewVirtualOverloads(RD, VirtualMethods);
2874
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002875 // Now go through all virtual member functions and add them to the current
2876 // vftable. This is done by
2877 // - replacing overridden methods in their existing slots, as long as they
2878 // don't require return adjustment; calculating This adjustment if needed.
2879 // - adding new slots for methods of the current base not present in any
2880 // sub-bases;
2881 // - adding new slots for methods that require Return adjustment.
2882 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002883 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2884 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002885
2886 FinalOverriders::OverriderInfo Overrider =
2887 Overriders.getOverrider(MD, Base.getBaseOffset());
2888 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002889 bool ForceThunk = false;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002890
2891 // Check if this virtual member function overrides
2892 // a method in one of the visited bases.
2893 if (const CXXMethodDecl *OverriddenMD =
Timur Iskhodzhanov66f43812013-10-29 14:13:45 +00002894 FindNearestOverriddenMethod(MD, VisitedBases)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002895 MethodInfoMapTy::iterator OverriddenMDIterator =
2896 MethodInfoMap.find(OverriddenMD);
2897
2898 // If the overridden method went to a different vftable, skip it.
2899 if (OverriddenMDIterator == MethodInfoMap.end())
2900 continue;
2901
2902 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2903
2904 // Create a this-adjusting thunk if needed.
2905 CharUnits TI = ComputeThisOffset(MD, Base, Overrider);
2906 if (TI != WhichVFPtr.VFPtrFullOffset) {
2907 ThisAdjustmentOffset.NonVirtual =
2908 (TI - WhichVFPtr.VFPtrFullOffset).getQuantity();
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002909 }
2910
2911 if (WhichVFPtr.LastVBase)
2912 CalculateVtordispAdjustment(Overrider, TI, ThisAdjustmentOffset);
2913
2914 if (!ThisAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002915 VTableThunks[OverriddenMethodInfo.VFTableIndex].This =
2916 ThisAdjustmentOffset;
2917 AddThunk(MD, VTableThunks[OverriddenMethodInfo.VFTableIndex]);
2918 }
2919
Reid Kleckner604c8b42013-12-27 19:43:59 +00002920 if (!NeedsReturnAdjustingThunk(MD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002921 // No return adjustment needed - just replace the overridden method info
2922 // with the current info.
2923 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2924 OverriddenMethodInfo.VFTableIndex);
2925 MethodInfoMap.erase(OverriddenMDIterator);
2926
2927 assert(!MethodInfoMap.count(MD) &&
2928 "Should not have method info for this method yet!");
2929 MethodInfoMap.insert(std::make_pair(MD, MI));
2930 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002931 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002932
Reid Kleckner31a9f742013-12-27 20:29:16 +00002933 // In case we need a return adjustment, we'll add a new slot for
2934 // the overrider and put a return-adjusting thunk where the overridden
2935 // method was in the vftable.
2936 // For now, just mark the overriden method as shadowed by a new slot.
2937 OverriddenMethodInfo.Shadowed = true;
2938 ForceThunk = true;
2939
2940 // Also apply this adjustment to the shadowed slots.
2941 if (!ThisAdjustmentOffset.isEmpty()) {
2942 // FIXME: this is O(N^2), can be O(N).
2943 const CXXMethodDecl *SubOverride = OverriddenMD;
2944 while ((SubOverride =
2945 FindNearestOverriddenMethod(SubOverride, VisitedBases))) {
2946 MethodInfoMapTy::iterator SubOverrideIterator =
2947 MethodInfoMap.find(SubOverride);
2948 if (SubOverrideIterator == MethodInfoMap.end())
2949 break;
2950 MethodInfo &SubOverrideMI = SubOverrideIterator->second;
2951 assert(SubOverrideMI.Shadowed);
2952 VTableThunks[SubOverrideMI.VFTableIndex].This =
2953 ThisAdjustmentOffset;
2954 AddThunk(MD, VTableThunks[SubOverrideMI.VFTableIndex]);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002955 }
2956 }
2957 } else if (Base.getBaseOffset() != WhichVFPtr.VFPtrFullOffset ||
2958 MD->size_overridden_methods()) {
2959 // Skip methods that don't belong to the vftable of the current class,
2960 // e.g. each method that wasn't seen in any of the visited sub-bases
2961 // but overrides multiple methods of other sub-bases.
2962 continue;
2963 }
2964
2965 // If we got here, MD is a method not seen in any of the sub-bases or
2966 // it requires return adjustment. Insert the method info for this method.
2967 unsigned VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002968 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002969 MethodInfo MI(VBIndex, Components.size());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002970
2971 assert(!MethodInfoMap.count(MD) &&
2972 "Should not have method info for this method yet!");
2973 MethodInfoMap.insert(std::make_pair(MD, MI));
2974
2975 const CXXMethodDecl *OverriderMD = Overrider.Method;
2976
2977 // Check if this overrider needs a return adjustment.
2978 // We don't want to do this for pure virtual member functions.
2979 BaseOffset ReturnAdjustmentOffset;
2980 ReturnAdjustment ReturnAdjustment;
2981 if (!OverriderMD->isPure()) {
2982 ReturnAdjustmentOffset =
2983 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2984 }
2985 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002986 ForceThunk = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002987 ReturnAdjustment.NonVirtual =
2988 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2989 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002990 const ASTRecordLayout &DerivedLayout =
2991 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
2992 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
2993 DerivedLayout.getVBPtrOffset().getQuantity();
2994 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002995 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2996 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002997 }
2998 }
2999
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003000 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3001 ForceThunk ? MD : 0));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003002 }
3003}
3004
3005void PrintBasePath(const VFPtrInfo::BasePath &Path, raw_ostream &Out) {
3006 for (VFPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
3007 E = Path.rend(); I != E; ++I) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003008 Out << "'";
3009 (*I)->printQualifiedName(Out);
3010 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003011 }
3012}
3013
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003014namespace {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003015struct MicrosoftThunkInfoStableSortComparator {
3016 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
3017 if (LHS.This != RHS.This)
3018 return LHS.This < RHS.This;
3019
3020 if (LHS.Return != RHS.Return)
3021 return LHS.Return < RHS.Return;
3022
3023 // Keep different thunks with the same adjustments in the order they
3024 // were put into the vector.
3025 return false;
3026 }
3027};
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003028}
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003029
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003030static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3031 bool ContinueFirstLine) {
3032 const ReturnAdjustment &R = TI.Return;
3033 bool Multiline = false;
3034 const char *LinePrefix = "\n ";
3035 if (!R.isEmpty()) {
3036 if (!ContinueFirstLine)
3037 Out << LinePrefix;
3038 Out << "[return adjustment: ";
3039 if (R.Virtual.Microsoft.VBPtrOffset)
3040 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3041 if (R.Virtual.Microsoft.VBIndex)
3042 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3043 Out << R.NonVirtual << " non-virtual]";
3044 Multiline = true;
3045 }
3046
3047 const ThisAdjustment &T = TI.This;
3048 if (!T.isEmpty()) {
3049 if (Multiline || !ContinueFirstLine)
3050 Out << LinePrefix;
3051 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003052 if (!TI.This.Virtual.isEmpty()) {
3053 assert(T.Virtual.Microsoft.VtordispOffset < 0);
3054 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3055 if (T.Virtual.Microsoft.VBPtrOffset) {
3056 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
3057 << " to the left, ";
3058 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3059 Out << LinePrefix << " vboffset at "
3060 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3061 }
3062 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003063 Out << T.NonVirtual << " non-virtual]";
3064 }
3065}
3066
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003067void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3068 Out << "VFTable for ";
3069 PrintBasePath(WhichVFPtr.PathToBaseWithVFPtr, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003070 Out << "'";
3071 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003072 Out << "' (" << Components.size() << " entries).\n";
3073
3074 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3075 Out << llvm::format("%4d | ", I);
3076
3077 const VTableComponent &Component = Components[I];
3078
3079 // Dump the component.
3080 switch (Component.getKind()) {
3081 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003082 Component.getRTTIDecl()->printQualifiedName(Out);
3083 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003084 break;
3085
3086 case VTableComponent::CK_FunctionPointer: {
3087 const CXXMethodDecl *MD = Component.getFunctionDecl();
3088
Reid Kleckner604c8b42013-12-27 19:43:59 +00003089 // FIXME: Figure out how to print the real thunk type, since they can
3090 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003091 std::string Str = PredefinedExpr::ComputeName(
3092 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3093 Out << Str;
3094 if (MD->isPure())
3095 Out << " [pure]";
3096
3097 if (MD->isDeleted()) {
3098 ErrorUnsupported("deleted methods", MD->getLocation());
3099 Out << " [deleted]";
3100 }
3101
3102 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003103 if (!Thunk.isEmpty())
3104 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003105
3106 break;
3107 }
3108
3109 case VTableComponent::CK_DeletingDtorPointer: {
3110 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3111
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003112 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003113 Out << "() [scalar deleting]";
3114
3115 if (DD->isPure())
3116 Out << " [pure]";
3117
3118 ThunkInfo Thunk = VTableThunks.lookup(I);
3119 if (!Thunk.isEmpty()) {
3120 assert(Thunk.Return.isEmpty() &&
3121 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003122 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003123 }
3124
3125 break;
3126 }
3127
3128 default:
3129 DiagnosticsEngine &Diags = Context.getDiagnostics();
3130 unsigned DiagID = Diags.getCustomDiagID(
3131 DiagnosticsEngine::Error,
3132 "Unexpected vftable component type %0 for component number %1");
3133 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3134 << I << Component.getKind();
3135 }
3136
3137 Out << '\n';
3138 }
3139
3140 Out << '\n';
3141
3142 if (!Thunks.empty()) {
3143 // We store the method names in a map to get a stable order.
3144 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3145
3146 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3147 I != E; ++I) {
3148 const CXXMethodDecl *MD = I->first;
3149 std::string MethodName = PredefinedExpr::ComputeName(
3150 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3151
3152 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3153 }
3154
3155 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3156 I = MethodNamesAndDecls.begin(),
3157 E = MethodNamesAndDecls.end();
3158 I != E; ++I) {
3159 const std::string &MethodName = I->first;
3160 const CXXMethodDecl *MD = I->second;
3161
3162 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003163 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
3164 MicrosoftThunkInfoStableSortComparator());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003165
3166 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3167 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3168
3169 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3170 const ThunkInfo &Thunk = ThunksVector[I];
3171
3172 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003173 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003174 Out << '\n';
3175 }
3176
3177 Out << '\n';
3178 }
3179 }
3180}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003181
3182namespace {
3183
3184struct VBTablePath;
3185typedef llvm::SmallVector<VBTablePath *, 6> VBTablePathVector;
3186
3187/// Produces MSVC-compatible vbtable data. The symbols produced by this builder
3188/// match those produced by MSVC 2012, which is different from MSVC 2010.
3189///
3190/// Unlike Itanium, which uses only one vtable per class, MSVC uses a different
3191/// symbol for every "address point" installed in base subobjects. As a result,
3192/// we have to compute unique symbols for every table. Since there can be
3193/// multiple non-virtual base subobjects of the same class, combining the most
3194/// derived class with the base containing the vtable is insufficient. The most
3195/// trivial algorithm would be to mangle in the entire path from base to most
3196/// derived, but that would be too easy and would create unnecessarily large
3197/// symbols. ;)
3198///
3199/// MSVC 2012 appears to minimize the vbtable names using the following
3200/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3201/// left to right, to find all of the subobjects which contain a vbptr field.
3202/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3203/// record with a vbptr creates an initially empty path.
3204///
3205/// To combine paths from child nodes, the paths are compared to check for
3206/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3207/// components in the same order. Each group of ambiguous paths is extended by
3208/// appending the class of the base from which it came. If the current class
3209/// node produced an ambiguous path, its path is extended with the current class.
3210/// After extending paths, MSVC again checks for ambiguity, and extends any
3211/// ambiguous path which wasn't already extended. Because each node yields an
3212/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3213/// to produce an unambiguous set of paths.
3214///
3215/// The VBTableBuilder class attempts to implement this algorithm by repeatedly
3216/// bucketing paths together by sorting them.
3217///
3218/// TODO: Presumably vftables use the same algorithm.
3219///
3220/// TODO: Implement the MSVC 2010 name mangling scheme to avoid emitting
3221/// duplicate vbtables with different symbols.
3222
3223class VBTableBuilder {
3224public:
3225 VBTableBuilder(ASTContext &Context, const CXXRecordDecl *MostDerived);
3226
3227 void enumerateVBTables(VBTableVector &VBTables);
3228
3229private:
3230 bool hasVBPtr(const CXXRecordDecl *RD);
3231
3232 /// Enumerates paths to bases with vbptrs. The paths elements are compressed
3233 /// to contain only the classes necessary to form an unambiguous path.
3234 void findUnambiguousPaths(const CXXRecordDecl *ReusingBase,
3235 BaseSubobject CurSubobject,
3236 VBTablePathVector &Paths);
3237
3238 void extendPath(VBTablePath *Info, bool SecondPass);
3239
3240 bool rebucketPaths(VBTablePathVector &Paths, size_t PathsStart,
3241 bool SecondPass = false);
3242
3243 ASTContext &Context;
3244
3245 const CXXRecordDecl *MostDerived;
3246
3247 /// Caches the layout of the most derived class.
3248 const ASTRecordLayout &DerivedLayout;
3249
3250 /// Set of vbases to avoid re-visiting the same vbases.
3251 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
3252};
3253
3254/// Holds intermediate data about a path to a vbptr inside a base subobject.
3255struct VBTablePath {
3256 VBTablePath(const VBTableInfo &VBInfo)
3257 : VBInfo(VBInfo), NextBase(VBInfo.VBPtrSubobject.getBase()) { }
3258
3259 /// All the data needed to build a vbtable, minus the GlobalVariable whose
3260 /// name we haven't computed yet.
3261 VBTableInfo VBInfo;
3262
3263 /// Next base to use for disambiguation. Can be null if we've already
3264 /// disambiguated this path once.
3265 const CXXRecordDecl *NextBase;
3266};
3267
3268} // end namespace
3269
3270VBTableBuilder::VBTableBuilder(ASTContext &Context,
3271 const CXXRecordDecl *MostDerived)
3272 : Context(Context), MostDerived(MostDerived),
3273 DerivedLayout(Context.getASTRecordLayout(MostDerived)) {}
3274
3275void VBTableBuilder::enumerateVBTables(VBTableVector &VBTables) {
3276 VBTablePathVector Paths;
3277 findUnambiguousPaths(MostDerived, BaseSubobject(MostDerived,
3278 CharUnits::Zero()), Paths);
3279 for (VBTablePathVector::iterator I = Paths.begin(), E = Paths.end();
3280 I != E; ++I) {
3281 VBTablePath *P = *I;
3282 VBTables.push_back(P->VBInfo);
3283 }
3284}
3285
3286
3287void VBTableBuilder::findUnambiguousPaths(const CXXRecordDecl *ReusingBase,
3288 BaseSubobject CurSubobject,
3289 VBTablePathVector &Paths) {
3290 size_t PathsStart = Paths.size();
3291 bool ReuseVBPtrFromBase = true;
3292 const CXXRecordDecl *CurBase = CurSubobject.getBase();
3293 const ASTRecordLayout &Layout = Context.getASTRecordLayout(CurBase);
3294
3295 // If this base has a vbptr, then we've found a path. These are not full
3296 // paths, so we don't use CXXBasePath.
3297 if (Layout.hasOwnVBPtr()) {
3298 ReuseVBPtrFromBase = false;
3299 VBTablePath *Info = new VBTablePath(VBTableInfo(ReusingBase, CurSubobject));
3300 Paths.push_back(Info);
3301 }
3302
3303 // Recurse onto any bases which themselves have virtual bases.
3304 for (CXXRecordDecl::base_class_const_iterator I = CurBase->bases_begin(),
3305 E = CurBase->bases_end(); I != E; ++I) {
3306 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3307 if (!Base->getNumVBases())
3308 continue; // Bases without virtual bases have no vbptrs.
3309 CharUnits NextOffset;
3310 const CXXRecordDecl *NextReusingBase = Base;
3311 if (I->isVirtual()) {
3312 if (!VBasesSeen.insert(Base))
3313 continue; // Don't visit virtual bases twice.
3314 NextOffset = DerivedLayout.getVBaseClassOffset(Base);
3315 } else {
3316 NextOffset = (CurSubobject.getBaseOffset() +
3317 Layout.getBaseClassOffset(Base));
3318
3319 // If CurBase didn't have a vbptr, then ReusingBase will reuse the vbptr
3320 // from the first non-virtual base with vbases for its vbptr.
3321 if (ReuseVBPtrFromBase) {
3322 NextReusingBase = ReusingBase;
3323 ReuseVBPtrFromBase = false;
3324 }
3325 }
3326
3327 size_t NumPaths = Paths.size();
3328 findUnambiguousPaths(NextReusingBase, BaseSubobject(Base, NextOffset),
3329 Paths);
3330
3331 // Tag paths through this base with the base itself. We might use it to
3332 // disambiguate.
3333 for (size_t I = NumPaths, E = Paths.size(); I != E; ++I)
3334 Paths[I]->NextBase = Base;
3335 }
3336
3337 bool AmbiguousPaths = rebucketPaths(Paths, PathsStart);
3338 if (AmbiguousPaths)
3339 rebucketPaths(Paths, PathsStart, /*SecondPass=*/true);
3340
3341#ifndef NDEBUG
3342 // Check that the paths are in fact unique.
3343 for (size_t I = PathsStart + 1, E = Paths.size(); I != E; ++I) {
3344 assert(Paths[I]->VBInfo.MangledPath != Paths[I - 1]->VBInfo.MangledPath &&
3345 "vbtable paths are not unique");
3346 }
3347#endif
3348}
3349
3350static bool pathCompare(VBTablePath *LHS, VBTablePath *RHS) {
3351 return LHS->VBInfo.MangledPath < RHS->VBInfo.MangledPath;
3352}
3353
3354void VBTableBuilder::extendPath(VBTablePath *P, bool SecondPass) {
3355 assert(P->NextBase || SecondPass);
3356 if (P->NextBase) {
3357 P->VBInfo.MangledPath.push_back(P->NextBase);
3358 P->NextBase = 0; // Prevent the path from being extended twice.
3359 }
3360}
3361
3362bool VBTableBuilder::rebucketPaths(VBTablePathVector &Paths, size_t PathsStart,
3363 bool SecondPass) {
3364 // What we're essentially doing here is bucketing together ambiguous paths.
3365 // Any bucket with more than one path in it gets extended by NextBase, which
3366 // is usually the direct base of the inherited the vbptr. This code uses a
3367 // sorted vector to implement a multiset to form the buckets. Note that the
3368 // ordering is based on pointers, but it doesn't change our output order. The
3369 // current algorithm is designed to match MSVC 2012's names.
3370 // TODO: Implement MSVC 2010 or earlier names to avoid extra vbtable cruft.
3371 VBTablePathVector PathsSorted(&Paths[PathsStart], &Paths.back() + 1);
3372 std::sort(PathsSorted.begin(), PathsSorted.end(), pathCompare);
3373 bool AmbiguousPaths = false;
3374 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3375 // Scan forward to find the end of the bucket.
3376 size_t BucketStart = I;
3377 do {
3378 ++I;
3379 } while (I != E && PathsSorted[BucketStart]->VBInfo.MangledPath ==
3380 PathsSorted[I]->VBInfo.MangledPath);
3381
3382 // If this bucket has multiple paths, extend them all.
3383 if (I - BucketStart > 1) {
3384 AmbiguousPaths = true;
3385 for (size_t II = BucketStart; II != I; ++II)
3386 extendPath(PathsSorted[II], SecondPass);
3387 }
3388 }
3389 return AmbiguousPaths;
3390}
3391
3392MicrosoftVTableContext::~MicrosoftVTableContext() {
3393 llvm::DeleteContainerSeconds(VFTableLayouts);
3394 llvm::DeleteContainerSeconds(VBaseInfo);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003395}
3396
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003397void MicrosoftVTableContext::enumerateVFPtrs(
3398 const CXXRecordDecl *MostDerivedClass,
3399 const ASTRecordLayout &MostDerivedClassLayout, BaseSubobject Base,
3400 const CXXRecordDecl *LastVBase,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003401 const VFPtrInfo::BasePath &PathFromCompleteClass,
3402 BasesSetVectorTy &VisitedVBases,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003403 VFPtrListTy &Result) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003404 const CXXRecordDecl *CurrentClass = Base.getBase();
3405 CharUnits OffsetInCompleteClass = Base.getBaseOffset();
3406 const ASTRecordLayout &CurrentClassLayout =
3407 Context.getASTRecordLayout(CurrentClass);
3408
3409 if (CurrentClassLayout.hasOwnVFPtr()) {
3410 if (LastVBase) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003411 uint64_t VBIndex = getVBTableIndex(MostDerivedClass, LastVBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003412 assert(VBIndex > 0 && "vbases must have vbindex!");
3413 CharUnits VFPtrOffset =
3414 OffsetInCompleteClass -
3415 MostDerivedClassLayout.getVBaseClassOffset(LastVBase);
3416 Result.push_back(VFPtrInfo(VBIndex, LastVBase, VFPtrOffset,
3417 PathFromCompleteClass, OffsetInCompleteClass));
3418 } else {
3419 Result.push_back(VFPtrInfo(OffsetInCompleteClass, PathFromCompleteClass));
3420 }
3421 }
3422
3423 for (CXXRecordDecl::base_class_const_iterator I = CurrentClass->bases_begin(),
3424 E = CurrentClass->bases_end(); I != E; ++I) {
3425 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
3426
3427 CharUnits NextBaseOffset;
3428 const CXXRecordDecl *NextLastVBase;
3429 if (I->isVirtual()) {
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00003430 if (!VisitedVBases.insert(BaseDecl))
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003431 continue;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003432 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
3433 NextLastVBase = BaseDecl;
3434 } else {
3435 NextBaseOffset = OffsetInCompleteClass +
3436 CurrentClassLayout.getBaseClassOffset(BaseDecl);
3437 NextLastVBase = LastVBase;
3438 }
3439
3440 VFPtrInfo::BasePath NewPath = PathFromCompleteClass;
3441 NewPath.push_back(BaseDecl);
3442 BaseSubobject NextBase(BaseDecl, NextBaseOffset);
3443
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003444 enumerateVFPtrs(MostDerivedClass, MostDerivedClassLayout, NextBase,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003445 NextLastVBase, NewPath, VisitedVBases, Result);
3446 }
3447}
3448
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00003449/// CalculatePathToMangle - Calculate the subset of records that should be used
3450/// to mangle the vftable for the given vfptr.
3451/// Should only be called if a class has multiple vftables.
3452static void
3453CalculatePathToMangle(const CXXRecordDecl *RD, VFPtrInfo &VFPtr) {
3454 // FIXME: In some rare cases this code produces a slightly incorrect mangling.
3455 // It's very likely that the vbtable mangling code can be adjusted to mangle
3456 // both vftables and vbtables correctly.
3457
3458 VFPtrInfo::BasePath &FullPath = VFPtr.PathToBaseWithVFPtr;
3459 if (FullPath.empty()) {
3460 // Mangle the class's own vftable.
3461 assert(RD->getNumVBases() &&
3462 "Something's wrong: if the most derived "
3463 "class has more than one vftable, it can only have its own "
3464 "vftable if it has vbases");
3465 VFPtr.PathToMangle.push_back(RD);
3466 return;
3467 }
3468
3469 unsigned Begin = 0;
3470
3471 // First, skip all the bases before the vbase.
3472 if (VFPtr.LastVBase) {
3473 while (FullPath[Begin] != VFPtr.LastVBase) {
3474 Begin++;
3475 assert(Begin < FullPath.size());
3476 }
3477 }
3478
3479 // Then, put the rest of the base path in the reverse order.
3480 for (unsigned I = FullPath.size(); I != Begin; --I) {
3481 const CXXRecordDecl *CurBase = FullPath[I - 1],
3482 *ItsBase = (I == 1) ? RD : FullPath[I - 2];
3483 bool BaseIsVirtual = false;
3484 for (CXXRecordDecl::base_class_const_iterator J = ItsBase->bases_begin(),
3485 F = ItsBase->bases_end(); J != F; ++J) {
3486 if (J->getType()->getAsCXXRecordDecl() == CurBase) {
3487 BaseIsVirtual = J->isVirtual();
3488 break;
3489 }
3490 }
3491
3492 // Should skip the current base if it is a non-virtual base with no siblings.
3493 if (BaseIsVirtual || ItsBase->getNumBases() != 1)
3494 VFPtr.PathToMangle.push_back(CurBase);
3495 }
3496}
3497
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003498void MicrosoftVTableContext::enumerateVFPtrs(
3499 const CXXRecordDecl *ForClass,
3500 MicrosoftVTableContext::VFPtrListTy &Result) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003501 Result.clear();
3502 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(ForClass);
3503 BasesSetVectorTy VisitedVBases;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003504 enumerateVFPtrs(ForClass, ClassLayout,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003505 BaseSubobject(ForClass, CharUnits::Zero()), 0,
3506 VFPtrInfo::BasePath(), VisitedVBases, Result);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00003507 if (Result.size() > 1) {
3508 for (unsigned I = 0, E = Result.size(); I != E; ++I)
3509 CalculatePathToMangle(ForClass, Result[I]);
3510 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003511}
3512
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003513void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003514 const CXXRecordDecl *RD) {
3515 assert(RD->isDynamicClass());
3516
3517 // Check if we've computed this information before.
3518 if (VFPtrLocations.count(RD))
3519 return;
3520
3521 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3522
3523 VFPtrListTy &VFPtrs = VFPtrLocations[RD];
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003524 enumerateVFPtrs(RD, VFPtrs);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003525
3526 MethodVFTableLocationsTy NewMethodLocations;
3527 for (VFPtrListTy::iterator I = VFPtrs.begin(), E = VFPtrs.end();
3528 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003529 VFTableBuilder Builder(*this, RD, *I);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003530
3531 VFTableIdTy id(RD, I->VFPtrFullOffset);
3532 assert(VFTableLayouts.count(id) == 0);
3533 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3534 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003535 VFTableLayouts[id] = new VTableLayout(
3536 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3537 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3538 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3539 Builder.vtable_indices_end());
3540 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3541 }
3542
3543 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3544 NewMethodLocations.end());
3545 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003546 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003547}
3548
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003549void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003550 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3551 raw_ostream &Out) {
3552 // Compute the vtable indices for all the member functions.
3553 // Store them in a map keyed by the location so we'll get a sorted table.
3554 std::map<MethodVFTableLocation, std::string> IndicesMap;
3555 bool HasNonzeroOffset = false;
3556
3557 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3558 E = NewMethods.end(); I != E; ++I) {
3559 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3560 assert(MD->isVirtual());
3561
3562 std::string MethodName = PredefinedExpr::ComputeName(
3563 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3564
3565 if (isa<CXXDestructorDecl>(MD)) {
3566 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3567 } else {
3568 IndicesMap[I->second] = MethodName;
3569 }
3570
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003571 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003572 HasNonzeroOffset = true;
3573 }
3574
3575 // Print the vtable indices for all the member functions.
3576 if (!IndicesMap.empty()) {
3577 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003578 Out << "'";
3579 RD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003580 Out << "' (" << IndicesMap.size() << " entries).\n";
3581
3582 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3583 uint64_t LastVBIndex = 0;
3584 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3585 I = IndicesMap.begin(),
3586 E = IndicesMap.end();
3587 I != E; ++I) {
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003588 CharUnits VFPtrOffset = I->first.VFPtrOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003589 uint64_t VBIndex = I->first.VBTableIndex;
3590 if (HasNonzeroOffset &&
3591 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3592 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3593 Out << " -- accessible via ";
3594 if (VBIndex)
3595 Out << "vbtable index " << VBIndex << ", ";
3596 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3597 LastVFPtrOffset = VFPtrOffset;
3598 LastVBIndex = VBIndex;
3599 }
3600
3601 uint64_t VTableIndex = I->first.Index;
3602 const std::string &MethodName = I->second;
3603 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3604 }
3605 Out << '\n';
3606 }
3607}
3608
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003609const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003610 const CXXRecordDecl *RD) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003611 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3612 if (Entry)
3613 return Entry;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003614
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003615 Entry = new VirtualBaseInfo();
3616
3617 VBTableBuilder(Context, RD).enumerateVBTables(Entry->VBTables);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003618
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003619 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003620 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003621 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003622 // If the Derived class shares the vbptr with a non-virtual base, the shared
3623 // virtual bases come first so that the layout is the same.
3624 const VirtualBaseInfo *BaseInfo =
3625 computeVBTableRelatedInformation(VBPtrBase);
3626 Entry->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3627 BaseInfo->VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003628 }
3629
3630 // New vbases are added to the end of the vbtable.
3631 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003632 unsigned VBTableIndex = 1 + Entry->VBTableIndices.size();
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003633 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003634 E = RD->vbases_end();
3635 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003636 const CXXRecordDecl *CurVBase = I->getType()->getAsCXXRecordDecl();
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003637 if (!Entry->VBTableIndices.count(CurVBase))
3638 Entry->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003639 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003640
3641 return Entry;
3642}
3643
3644unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3645 const CXXRecordDecl *VBase) {
3646 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3647 assert(VBInfo->VBTableIndices.count(VBase));
3648 return VBInfo->VBTableIndices.find(VBase)->second;
3649}
3650
3651const VBTableVector &
3652MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
3653 return computeVBTableRelatedInformation(RD)->VBTables;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003654}
3655
3656const MicrosoftVTableContext::VFPtrListTy &
3657MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003658 computeVTableRelatedInformation(RD);
3659
3660 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3661 return VFPtrLocations[RD];
3662}
3663
3664const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003665MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3666 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003667 computeVTableRelatedInformation(RD);
3668
3669 VFTableIdTy id(RD, VFPtrOffset);
3670 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3671 return *VFTableLayouts[id];
3672}
3673
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003674const MicrosoftVTableContext::MethodVFTableLocation &
3675MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003676 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3677 "Only use this method for virtual methods or dtors");
3678 if (isa<CXXDestructorDecl>(GD.getDecl()))
3679 assert(GD.getDtorType() == Dtor_Deleting);
3680
3681 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3682 if (I != MethodVFTableLocations.end())
3683 return I->second;
3684
3685 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3686
3687 computeVTableRelatedInformation(RD);
3688
3689 I = MethodVFTableLocations.find(GD);
3690 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3691 return I->second;
3692}