blob: 1ab22c12f30b5cb2e5b930e4c37119890990af04 [file] [log] [blame]
Anders Carlssondbd920c2009-10-11 22:13:54 +00001//===--- CGVtable.cpp - Emit LLVM Code for C++ vtables --------------------===//
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 C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000019#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000020#include "llvm/Support/Format.h"
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000021#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000022
23using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson27f69d02009-11-27 22:21:51 +000026namespace {
Anders Carlsson824d7ea2010-02-11 08:02:13 +000027
Anders Carlsson2fca9be2010-02-23 01:34:28 +000028/// BaseOffset - Represents an offset from a derived class to a direct or
29/// indirect base class.
30struct BaseOffset {
31 /// DerivedClass - The derived class.
32 const CXXRecordDecl *DerivedClass;
33
34 /// VirtualBase - If the path from the derived class to the base class
35 /// involves a virtual base class, this holds its declaration.
36 const CXXRecordDecl *VirtualBase;
37
38 /// NonVirtualOffset - The offset from the derived class to the base class.
39 /// (Or the offset from the virtual base class to the base class, if the
40 /// path from the derived class to the base class involves a virtual base
41 /// class.
42 int64_t NonVirtualOffset;
43
44 BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { }
45 BaseOffset(const CXXRecordDecl *DerivedClass,
46 const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset)
47 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
48 NonVirtualOffset(NonVirtualOffset) { }
49
50 bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; }
51};
52
Anders Carlssonbdf73d82010-02-11 21:24:32 +000053/// FinalOverriders - Contains the final overrider member functions for all
54/// member functions in the base subobjects of a class.
55class FinalOverriders {
Anders Carlssona7575822010-02-12 16:55:34 +000056public:
57 /// OverriderInfo - Information about a final overrider.
58 struct OverriderInfo {
59 /// Method - The method decl of the overrider.
60 const CXXMethodDecl *Method;
Anders Carlsson96309c42010-02-18 16:29:24 +000061
62 /// BaseOffset - the base offset of the overrider.
63 uint64_t BaseOffset;
Anders Carlssona7575822010-02-12 16:55:34 +000064
Anders Carlsson96309c42010-02-18 16:29:24 +000065 OverriderInfo() : Method(0), BaseOffset(0) { }
Anders Carlssona7575822010-02-12 16:55:34 +000066 };
67
68private:
Anders Carlssonbdf73d82010-02-11 21:24:32 +000069 /// MostDerivedClass - The most derived class for which the final overriders
70 /// are stored.
71 const CXXRecordDecl *MostDerivedClass;
72
73 ASTContext &Context;
74
75 /// MostDerivedClassLayout - the AST record layout of the most derived class.
76 const ASTRecordLayout &MostDerivedClassLayout;
77
Anders Carlsson0c0eeb22010-02-13 02:02:03 +000078 /// BaseSubobjectMethodPairTy - Uniquely identifies a member function
79 /// in a base subobject.
80 typedef std::pair<BaseSubobject, const CXXMethodDecl *>
81 BaseSubobjectMethodPairTy;
82
83 typedef llvm::DenseMap<BaseSubobjectMethodPairTy,
Anders Carlssona7575822010-02-12 16:55:34 +000084 OverriderInfo> OverridersMapTy;
Anders Carlssonbdf73d82010-02-11 21:24:32 +000085
86 /// OverridersMap - The final overriders for all virtual member functions of
87 /// all the base subobjects of the most derived class.
88 OverridersMapTy OverridersMap;
89
Anders Carlsson9d6f0d52010-02-14 00:37:35 +000090 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
91 /// avoid visiting virtual bases more than once.
92 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
93
Anders Carlsson0c0eeb22010-02-13 02:02:03 +000094 typedef llvm::DenseMap<BaseSubobjectMethodPairTy, BaseOffset>
95 AdjustmentOffsetsMapTy;
96
97 /// ReturnAdjustments - Holds return adjustments for all the overriders that
98 /// need to perform return value adjustments.
99 AdjustmentOffsetsMapTy ReturnAdjustments;
Anders Carlssondf31af12010-02-13 23:17:31 +0000100
Anders Carlssonb8358d82010-02-12 01:40:03 +0000101 typedef llvm::SmallVector<uint64_t, 1> OffsetVectorTy;
102
103 /// SubobjectOffsetsMapTy - This map is used for keeping track of all the
104 /// base subobject offsets that a single class declaration might refer to.
105 ///
106 /// For example, in:
107 ///
108 /// struct A { virtual void f(); };
109 /// struct B1 : A { };
110 /// struct B2 : A { };
111 /// struct C : B1, B2 { virtual void f(); };
112 ///
113 /// when we determine that C::f() overrides A::f(), we need to update the
114 /// overriders map for both A-in-B1 and A-in-B2 and the subobject offsets map
115 /// will have the subobject offsets for both A copies.
116 typedef llvm::DenseMap<const CXXRecordDecl *, OffsetVectorTy>
117 SubobjectOffsetsMapTy;
118
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000119 /// ComputeFinalOverriders - Compute the final overriders for a given base
120 /// subobject (and all its direct and indirect bases).
Anders Carlssonb8358d82010-02-12 01:40:03 +0000121 void ComputeFinalOverriders(BaseSubobject Base,
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000122 bool BaseSubobjectIsVisitedVBase,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000123 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000124
125 /// AddOverriders - Add the final overriders for this base subobject to the
126 /// map of final overriders.
Anders Carlssonb8358d82010-02-12 01:40:03 +0000127 void AddOverriders(BaseSubobject Base, SubobjectOffsetsMapTy &Offsets);
128
129 /// PropagateOverrider - Propagate the NewMD overrider to all the functions
130 /// that OldMD overrides. For example, if we have:
131 ///
132 /// struct A { virtual void f(); };
133 /// struct B : A { virtual void f(); };
134 /// struct C : B { virtual void f(); };
135 ///
136 /// and we want to override B::f with C::f, we also need to override A::f with
137 /// C::f.
138 void PropagateOverrider(const CXXMethodDecl *OldMD,
Anders Carlsson74c364e2010-02-13 22:23:31 +0000139 BaseSubobject NewBase,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000140 const CXXMethodDecl *NewMD,
141 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000142
Anders Carlssonb8358d82010-02-12 01:40:03 +0000143 static void MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
144 SubobjectOffsetsMapTy &Offsets);
145
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000146public:
147 explicit FinalOverriders(const CXXRecordDecl *MostDerivedClass);
Anders Carlsson2157d302010-02-24 22:18:01 +0000148
149 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
150 /// the 'this' pointer from the base subobject to the derived subobject.
151 /// FIXME: This should move to VtableBuilder.
152 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
153 BaseSubobject Derived) const;
154
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000155 /// getOverrider - Get the final overrider for the given method declaration in
156 /// the given base subobject.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +0000157 OverriderInfo getOverrider(BaseSubobject Base,
158 const CXXMethodDecl *MD) const {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000159 assert(OverridersMap.count(std::make_pair(Base, MD)) &&
160 "Did not find overrider!");
161
162 return OverridersMap.lookup(std::make_pair(Base, MD));
163 }
164
Anders Carlsson49bac9a2010-02-13 23:40:17 +0000165 /// getReturnAdjustmentOffset - Get the return adjustment offset for the
166 /// method decl in the given base subobject. Returns an empty base offset if
167 /// no adjustment is needed.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +0000168 BaseOffset getReturnAdjustmentOffset(BaseSubobject Base,
169 const CXXMethodDecl *MD) const {
170 return ReturnAdjustments.lookup(std::make_pair(Base, MD));
171 }
172
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000173 /// dump - dump the final overriders.
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000174 void dump() {
175 assert(VisitedVirtualBases.empty() &&
176 "Visited virtual bases aren't empty!");
177 dump(llvm::errs(), BaseSubobject(MostDerivedClass, 0));
178 VisitedVirtualBases.clear();
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000179 }
180
181 /// dump - dump the final overriders for a base subobject, and all its direct
182 /// and indirect base subobjects.
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000183 void dump(llvm::raw_ostream &Out, BaseSubobject Base);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000184};
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000185
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000186FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass)
187 : MostDerivedClass(MostDerivedClass),
188 Context(MostDerivedClass->getASTContext()),
189 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
190
191 // Compute the final overriders.
Anders Carlssonb8358d82010-02-12 01:40:03 +0000192 SubobjectOffsetsMapTy Offsets;
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000193 ComputeFinalOverriders(BaseSubobject(MostDerivedClass, 0),
194 /*BaseSubobjectIsVisitedVBase=*/false, Offsets);
195 VisitedVirtualBases.clear();
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000196
197 // And dump them (for now).
198 dump();
Anders Carlssona4699882010-02-13 21:33:22 +0000199
200 // Also dump the base offsets (for now).
201 for (SubobjectOffsetsMapTy::const_iterator I = Offsets.begin(),
202 E = Offsets.end(); I != E; ++I) {
203 const OffsetVectorTy& OffsetVector = I->second;
204
205 llvm::errs() << "Base offsets for ";
206 llvm::errs() << I->first->getQualifiedNameAsString() << '\n';
207
208 for (unsigned I = 0, E = OffsetVector.size(); I != E; ++I)
209 llvm::errs() << " " << I << " - " << OffsetVector[I] << '\n';
210 }
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000211}
212
Anders Carlssonb8358d82010-02-12 01:40:03 +0000213void FinalOverriders::AddOverriders(BaseSubobject Base,
214 SubobjectOffsetsMapTy &Offsets) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000215 const CXXRecordDecl *RD = Base.getBase();
216
217 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
218 E = RD->method_end(); I != E; ++I) {
219 const CXXMethodDecl *MD = *I;
220
221 if (!MD->isVirtual())
222 continue;
223
Anders Carlssonb8358d82010-02-12 01:40:03 +0000224 // First, propagate the overrider.
Anders Carlsson74c364e2010-02-13 22:23:31 +0000225 PropagateOverrider(MD, Base, MD, Offsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000226
227 // Add the overrider as the final overrider of itself.
Anders Carlssona7575822010-02-12 16:55:34 +0000228 OverriderInfo& Overrider = OverridersMap[std::make_pair(Base, MD)];
229 assert(!Overrider.Method && "Overrider should not exist yet!");
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000230
Anders Carlsson96309c42010-02-18 16:29:24 +0000231 Overrider.BaseOffset = Base.getBaseOffset();
Anders Carlssona7575822010-02-12 16:55:34 +0000232 Overrider.Method = MD;
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000233 }
234}
235
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000236static BaseOffset ComputeBaseOffset(ASTContext &Context,
237 const CXXRecordDecl *DerivedRD,
238 const CXXBasePath &Path) {
Anders Carlssondf31af12010-02-13 23:17:31 +0000239 int64_t NonVirtualOffset = 0;
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000240
Anders Carlssona4a54172010-02-13 20:41:15 +0000241 unsigned NonVirtualStart = 0;
242 const CXXRecordDecl *VirtualBase = 0;
243
244 // First, look for the virtual base class.
245 for (unsigned I = 0, E = Path.size(); I != E; ++I) {
246 const CXXBasePathElement &Element = Path[I];
247
248 if (Element.Base->isVirtual()) {
249 // FIXME: Can we break when we find the first virtual base?
250 // (If we can't, can't we just iterate over the path in reverse order?)
251 NonVirtualStart = I + 1;
252 QualType VBaseType = Element.Base->getType();
253 VirtualBase =
254 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
255 }
256 }
257
258 // Now compute the non-virtual offset.
259 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
260 const CXXBasePathElement &Element = Path[I];
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000261
262 // Check the base class offset.
263 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
264
265 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
266 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
267
268 NonVirtualOffset += Layout.getBaseClassOffset(Base);
269 }
270
271 // FIXME: This should probably use CharUnits or something. Maybe we should
272 // even change the base offsets in ASTRecordLayout to be specified in
273 // CharUnits.
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000274 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8);
Anders Carlssone67dc302010-02-14 00:16:19 +0000275
276}
277
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000278static BaseOffset ComputeBaseOffset(ASTContext &Context,
279 const CXXRecordDecl *BaseRD,
280 const CXXRecordDecl *DerivedRD) {
Anders Carlssone67dc302010-02-14 00:16:19 +0000281 CXXBasePaths Paths(/*FindAmbiguities=*/false,
282 /*RecordPaths=*/true, /*DetectVirtual=*/false);
283
284 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
285 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
286 assert(false && "Class must be derived from the passed in base class!");
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000287 return BaseOffset();
Anders Carlssone67dc302010-02-14 00:16:19 +0000288 }
289
290 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000291}
292
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000293static BaseOffset
Anders Carlssondf31af12010-02-13 23:17:31 +0000294ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
295 const CXXMethodDecl *DerivedMD,
296 const CXXMethodDecl *BaseMD) {
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000297 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
298 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
299
300 // Canonicalize the return types.
301 CanQualType CanDerivedReturnType =
302 Context.getCanonicalType(DerivedFT->getResultType());
303 CanQualType CanBaseReturnType =
304 Context.getCanonicalType(BaseFT->getResultType());
305
306 assert(CanDerivedReturnType->getTypeClass() ==
307 CanBaseReturnType->getTypeClass() &&
308 "Types must have same type class!");
309
310 if (CanDerivedReturnType == CanBaseReturnType) {
311 // No adjustment needed.
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000312 return BaseOffset();
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000313 }
314
315 if (isa<ReferenceType>(CanDerivedReturnType)) {
316 CanDerivedReturnType =
317 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
318 CanBaseReturnType =
319 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
320 } else if (isa<PointerType>(CanDerivedReturnType)) {
321 CanDerivedReturnType =
322 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
323 CanBaseReturnType =
324 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
325 } else {
326 assert(false && "Unexpected return type!");
327 }
328
329 // We need to compare unqualified types here; consider
330 // const T *Base::foo();
331 // T *Derived::foo();
332 if (CanDerivedReturnType.getUnqualifiedType() ==
333 CanBaseReturnType.getUnqualifiedType()) {
334 // No adjustment needed.
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000335 return BaseOffset();
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000336 }
337
338 const CXXRecordDecl *DerivedRD =
339 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
340
341 const CXXRecordDecl *BaseRD =
342 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
343
Anders Carlssondf31af12010-02-13 23:17:31 +0000344 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000345}
346
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000347BaseOffset
Anders Carlssone67dc302010-02-14 00:16:19 +0000348FinalOverriders::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
Anders Carlsson2157d302010-02-24 22:18:01 +0000349 BaseSubobject Derived) const {
Anders Carlssone67dc302010-02-14 00:16:19 +0000350 const CXXRecordDecl *BaseRD = Base.getBase();
351 const CXXRecordDecl *DerivedRD = Derived.getBase();
352
353 CXXBasePaths Paths(/*FindAmbiguities=*/true,
Anders Carlssondf31af12010-02-13 23:17:31 +0000354 /*RecordPaths=*/true, /*DetectVirtual=*/true);
355
356 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
357 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
358 assert(false && "Class must be derived from the passed in base class!");
Anders Carlsson6362fe62010-02-17 02:05:23 +0000359 return BaseOffset();
Anders Carlssondf31af12010-02-13 23:17:31 +0000360 }
361
Anders Carlsson6362fe62010-02-17 02:05:23 +0000362 // We have to go through all the paths, and see which one leads us to the
363 // right base subobject.
364 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
365 I != E; ++I) {
366 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
367
368 // FIXME: Should not use * 8 here.
369 uint64_t OffsetToBaseSubobject = Offset.NonVirtualOffset * 8;
370
371 if (Offset.VirtualBase) {
372 // If we have a virtual base class, the non-virtual offset is relative
373 // to the virtual base class offset.
374 const ASTRecordLayout &MostDerivedClassLayout =
375 Context.getASTRecordLayout(MostDerivedClass);
376
377 /// Get the virtual base offset, relative to the most derived class
378 /// layout.
379 OffsetToBaseSubobject +=
380 MostDerivedClassLayout.getVBaseClassOffset(Offset.VirtualBase);
381 } else {
382 // Otherwise, the non-virtual offset is relative to the derived class
383 // offset.
384 OffsetToBaseSubobject += Derived.getBaseOffset();
385 }
386
387 // Check if this path gives us the right base subobject.
388 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
389 // Since we're going from the base class _to_ the derived class, we'll
390 // invert the non-virtual offset here.
391 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
392 return Offset;
393 }
394 }
395
396 return BaseOffset();
Anders Carlssondf31af12010-02-13 23:17:31 +0000397}
398
Anders Carlssonb8358d82010-02-12 01:40:03 +0000399void FinalOverriders::PropagateOverrider(const CXXMethodDecl *OldMD,
Anders Carlsson74c364e2010-02-13 22:23:31 +0000400 BaseSubobject NewBase,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000401 const CXXMethodDecl *NewMD,
402 SubobjectOffsetsMapTy &Offsets) {
403 for (CXXMethodDecl::method_iterator I = OldMD->begin_overridden_methods(),
404 E = OldMD->end_overridden_methods(); I != E; ++I) {
405 const CXXMethodDecl *OverriddenMD = *I;
406 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
407
408 // We want to override OverriddenMD in all subobjects, for example:
409 //
410 /// struct A { virtual void f(); };
411 /// struct B1 : A { };
412 /// struct B2 : A { };
413 /// struct C : B1, B2 { virtual void f(); };
414 ///
415 /// When overriding A::f with C::f we need to do so in both A subobjects.
416 const OffsetVectorTy &OffsetVector = Offsets[OverriddenRD];
417
418 // Go through all the subobjects.
419 for (unsigned I = 0, E = OffsetVector.size(); I != E; ++I) {
420 uint64_t Offset = OffsetVector[I];
421
Anders Carlssone67dc302010-02-14 00:16:19 +0000422 BaseSubobject OverriddenSubobject = BaseSubobject(OverriddenRD, Offset);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000423 BaseSubobjectMethodPairTy SubobjectAndMethod =
Anders Carlssone67dc302010-02-14 00:16:19 +0000424 std::make_pair(OverriddenSubobject, OverriddenMD);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000425
426 OverriderInfo &Overrider = OverridersMap[SubobjectAndMethod];
427
Anders Carlssona7575822010-02-12 16:55:34 +0000428 assert(Overrider.Method && "Did not find existing overrider!");
Anders Carlssonb8358d82010-02-12 01:40:03 +0000429
Anders Carlssondf31af12010-02-13 23:17:31 +0000430 // Check if we need return adjustments or base adjustments.
Anders Carlsson1d05be52010-02-13 21:16:54 +0000431 // (We don't want to do this for pure virtual member functions).
432 if (!NewMD->isPure()) {
Anders Carlssondf31af12010-02-13 23:17:31 +0000433 // Get the return adjustment base offset.
Anders Carlsson1d05be52010-02-13 21:16:54 +0000434 BaseOffset ReturnBaseOffset =
Anders Carlssondf31af12010-02-13 23:17:31 +0000435 ComputeReturnAdjustmentBaseOffset(Context, NewMD, OverriddenMD);
436
Anders Carlsson1d05be52010-02-13 21:16:54 +0000437 if (!ReturnBaseOffset.isEmpty()) {
438 // Store the return adjustment base offset.
439 ReturnAdjustments[SubobjectAndMethod] = ReturnBaseOffset;
440 }
Anders Carlsson16b73122010-02-12 17:13:23 +0000441 }
442
Anders Carlssonb8358d82010-02-12 01:40:03 +0000443 // Set the new overrider.
Anders Carlsson96309c42010-02-18 16:29:24 +0000444 Overrider.BaseOffset = NewBase.getBaseOffset();
Anders Carlssona7575822010-02-12 16:55:34 +0000445 Overrider.Method = NewMD;
Anders Carlssonb8358d82010-02-12 01:40:03 +0000446
447 // And propagate it further.
Anders Carlsson74c364e2010-02-13 22:23:31 +0000448 PropagateOverrider(OverriddenMD, NewBase, NewMD, Offsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000449 }
450 }
451}
452
453void
454FinalOverriders::MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
455 SubobjectOffsetsMapTy &Offsets) {
456 // Iterate over the new offsets.
457 for (SubobjectOffsetsMapTy::const_iterator I = NewOffsets.begin(),
458 E = NewOffsets.end(); I != E; ++I) {
459 const CXXRecordDecl *NewRD = I->first;
Anders Carlssona4699882010-02-13 21:33:22 +0000460 const OffsetVectorTy& NewOffsetVector = I->second;
Anders Carlssonb8358d82010-02-12 01:40:03 +0000461
Anders Carlssona4699882010-02-13 21:33:22 +0000462 OffsetVectorTy &OffsetVector = Offsets[NewRD];
463 if (OffsetVector.empty()) {
Anders Carlssonb8358d82010-02-12 01:40:03 +0000464 // There were no previous offsets in this vector, just insert all entries
Anders Carlssona4699882010-02-13 21:33:22 +0000465 // from the new offset vector.
466 OffsetVector.append(NewOffsetVector.begin(), NewOffsetVector.end());
Anders Carlssonb8358d82010-02-12 01:40:03 +0000467 continue;
468 }
469
Anders Carlssona4699882010-02-13 21:33:22 +0000470 // We need to merge the new offsets vector into the old, but we don't want
471 // to have duplicate entries. Do this by inserting the old offsets in a set
472 // so they'll be unique. After this, we iterate over the new offset vector
473 // and only append elements that aren't in the set.
474
475 // First, add the existing offsets to the set.
476 llvm::SmallSet<uint64_t, 4> OffsetSet;
477 for (unsigned I = 0, E = OffsetVector.size(); I != E; ++I) {
478 bool Inserted = OffsetSet.insert(OffsetVector[I]);
479 if (!Inserted)
480 assert(false && "Set of offsets should be unique!");
481 }
482
483 // Next, only add the new offsets if they are not already in the set.
484 for (unsigned I = 0, E = NewOffsetVector.size(); I != E; ++I) {
485 uint64_t Offset = NewOffsetVector[I];
486
487 if (OffsetSet.count(Offset)) {
488 // Ignore the offset.
489 continue;
490 }
491
492 // Otherwise, add it to the offsets vector.
493 OffsetVector.push_back(Offset);
494 }
Anders Carlssonb8358d82010-02-12 01:40:03 +0000495 }
496}
497
498void FinalOverriders::ComputeFinalOverriders(BaseSubobject Base,
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000499 bool BaseSubobjectIsVisitedVBase,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000500 SubobjectOffsetsMapTy &Offsets) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000501 const CXXRecordDecl *RD = Base.getBase();
Anders Carlssonb8358d82010-02-12 01:40:03 +0000502 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000503
Anders Carlssonb8358d82010-02-12 01:40:03 +0000504 SubobjectOffsetsMapTy NewOffsets;
505
506 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
507 E = RD->bases_end(); I != E; ++I) {
508 const CXXRecordDecl *BaseDecl =
509 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
510
Anders Carlssonb828afa2010-02-14 17:05:59 +0000511 // Ignore bases that don't have any virtual member functions.
512 if (!BaseDecl->isPolymorphic())
513 continue;
514
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000515 bool IsVisitedVirtualBase = false;
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000516 uint64_t BaseOffset;
517 if (I->isVirtual()) {
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000518 if (!VisitedVirtualBases.insert(BaseDecl))
519 IsVisitedVirtualBase = true;
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000520 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
521 } else {
522 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
523 }
524
Anders Carlssonb8358d82010-02-12 01:40:03 +0000525 // Compute the final overriders for this base.
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000526 // We always want to compute the final overriders, even if the base is a
527 // visited virtual base. Consider:
528 //
529 // struct A {
530 // virtual void f();
531 // virtual void g();
532 // };
533 //
534 // struct B : virtual A {
535 // void f();
536 // };
537 //
538 // struct C : virtual A {
539 // void g ();
540 // };
541 //
542 // struct D : B, C { };
543 //
544 // Here, we still want to compute the overriders for A as a base of C,
545 // because otherwise we'll miss that C::g overrides A::f.
546 ComputeFinalOverriders(BaseSubobject(BaseDecl, BaseOffset),
547 IsVisitedVirtualBase, NewOffsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000548 }
549
550 /// Now add the overriders for this particular subobject.
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000551 /// (We don't want to do this more than once for a virtual base).
552 if (!BaseSubobjectIsVisitedVBase)
553 AddOverriders(Base, NewOffsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000554
555 // And merge the newly discovered subobject offsets.
556 MergeSubobjectOffsets(NewOffsets, Offsets);
557
558 /// Finally, add the offset for our own subobject.
559 Offsets[RD].push_back(Base.getBaseOffset());
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000560}
561
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000562void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000563 const CXXRecordDecl *RD = Base.getBase();
564 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
565
566 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
567 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000568 const CXXRecordDecl *BaseDecl =
569 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
570
Anders Carlssonb828afa2010-02-14 17:05:59 +0000571 // Ignore bases that don't have any virtual member functions.
572 if (!BaseDecl->isPolymorphic())
573 continue;
574
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000575 uint64_t BaseOffset;
576 if (I->isVirtual()) {
577 if (!VisitedVirtualBases.insert(BaseDecl)) {
578 // We've visited this base before.
579 continue;
580 }
581
582 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
583 } else {
584 BaseOffset = Layout.getBaseClassOffset(BaseDecl) +
585 Base.getBaseOffset();
586 }
587
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000588 dump(Out, BaseSubobject(BaseDecl, BaseOffset));
589 }
590
591 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
592 Out << Base.getBaseOffset() << ")\n";
593
594 // Now dump the overriders for this base subobject.
595 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
596 E = RD->method_end(); I != E; ++I) {
597 const CXXMethodDecl *MD = *I;
598
599 if (!MD->isVirtual())
600 continue;
601
Anders Carlssona7575822010-02-12 16:55:34 +0000602 OverriderInfo Overrider = getOverrider(Base, MD);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000603
604 Out << " " << MD->getQualifiedNameAsString() << " - ";
Anders Carlsson16b73122010-02-12 17:13:23 +0000605 Out << Overrider.Method->getQualifiedNameAsString();
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000606
Benjamin Kramere3d0b1c2010-02-13 09:11:28 +0000607 AdjustmentOffsetsMapTy::const_iterator AI =
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000608 ReturnAdjustments.find(std::make_pair(Base, MD));
Benjamin Kramere3d0b1c2010-02-13 09:11:28 +0000609 if (AI != ReturnAdjustments.end()) {
610 const BaseOffset &Offset = AI->second;
Anders Carlssona4a54172010-02-13 20:41:15 +0000611
612 Out << " [ret-adj: ";
613 if (Offset.VirtualBase)
614 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000615
Anders Carlssona4a54172010-02-13 20:41:15 +0000616 Out << Offset.NonVirtualOffset << " nv]";
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000617 }
Anders Carlssondf31af12010-02-13 23:17:31 +0000618
Anders Carlsson16b73122010-02-12 17:13:23 +0000619 Out << "\n";
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000620 }
621}
622
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000623/// VtableComponent - Represents a single component in a vtable.
624class VtableComponent {
625public:
626 enum Kind {
627 CK_VCallOffset,
628 CK_VBaseOffset,
629 CK_OffsetToTop,
630 CK_RTTI,
Anders Carlsson848fa642010-02-11 18:20:28 +0000631 CK_FunctionPointer,
632
633 /// CK_CompleteDtorPointer - A pointer to the complete destructor.
634 CK_CompleteDtorPointer,
635
636 /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
Anders Carlsson1f464662010-02-19 20:08:13 +0000637 CK_DeletingDtorPointer,
638
639 /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
640 /// will end up never being called. Such vtable function pointers are
641 /// represented as a CK_UnusedFunctionPointer.
642 CK_UnusedFunctionPointer
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000643 };
644
Anders Carlssond9a67042010-02-17 06:07:19 +0000645 static VtableComponent MakeVCallOffset(int64_t Offset) {
646 return VtableComponent(CK_VCallOffset, Offset);
647 }
648
Anders Carlssona661a542010-02-16 04:49:44 +0000649 static VtableComponent MakeVBaseOffset(int64_t Offset) {
650 return VtableComponent(CK_VBaseOffset, Offset);
651 }
652
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000653 static VtableComponent MakeOffsetToTop(int64_t Offset) {
654 return VtableComponent(CK_OffsetToTop, Offset);
655 }
656
657 static VtableComponent MakeRTTI(const CXXRecordDecl *RD) {
658 return VtableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
659 }
660
661 static VtableComponent MakeFunction(const CXXMethodDecl *MD) {
662 assert(!isa<CXXDestructorDecl>(MD) &&
Anders Carlsson848fa642010-02-11 18:20:28 +0000663 "Don't use MakeFunction with destructors!");
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000664
Anders Carlsson848fa642010-02-11 18:20:28 +0000665 return VtableComponent(CK_FunctionPointer,
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000666 reinterpret_cast<uintptr_t>(MD));
667 }
668
Anders Carlsson848fa642010-02-11 18:20:28 +0000669 static VtableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
670 return VtableComponent(CK_CompleteDtorPointer,
671 reinterpret_cast<uintptr_t>(DD));
672 }
673
674 static VtableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
675 return VtableComponent(CK_DeletingDtorPointer,
676 reinterpret_cast<uintptr_t>(DD));
677 }
678
Anders Carlsson1f464662010-02-19 20:08:13 +0000679 static VtableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
680 assert(!isa<CXXDestructorDecl>(MD) &&
681 "Don't use MakeUnusedFunction with destructors!");
682 return VtableComponent(CK_UnusedFunctionPointer,
683 reinterpret_cast<uintptr_t>(MD));
684 }
685
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000686 /// getKind - Get the kind of this vtable component.
687 Kind getKind() const {
688 return (Kind)(Value & 0x7);
689 }
690
Anders Carlssond9a67042010-02-17 06:07:19 +0000691 int64_t getVCallOffset() const {
692 assert(getKind() == CK_VCallOffset && "Invalid component kind!");
693
694 return getOffset();
695 }
696
Anders Carlssona661a542010-02-16 04:49:44 +0000697 int64_t getVBaseOffset() const {
698 assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
699
700 return getOffset();
701 }
702
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000703 int64_t getOffsetToTop() const {
704 assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
705
706 return getOffset();
707 }
708
709 const CXXRecordDecl *getRTTIDecl() const {
710 assert(getKind() == CK_RTTI && "Invalid component kind!");
711
712 return reinterpret_cast<CXXRecordDecl *>(getPointer());
713 }
714
715 const CXXMethodDecl *getFunctionDecl() const {
Anders Carlsson848fa642010-02-11 18:20:28 +0000716 assert(getKind() == CK_FunctionPointer);
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000717
718 return reinterpret_cast<CXXMethodDecl *>(getPointer());
719 }
Anders Carlsson848fa642010-02-11 18:20:28 +0000720
721 const CXXDestructorDecl *getDestructorDecl() const {
722 assert((getKind() == CK_CompleteDtorPointer ||
723 getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
724
725 return reinterpret_cast<CXXDestructorDecl *>(getPointer());
726 }
727
Anders Carlsson1f464662010-02-19 20:08:13 +0000728 const CXXMethodDecl *getUnusedFunctionDecl() const {
729 assert(getKind() == CK_UnusedFunctionPointer);
730
731 return reinterpret_cast<CXXMethodDecl *>(getPointer());
732 }
733
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000734private:
735 VtableComponent(Kind ComponentKind, int64_t Offset) {
736 assert((ComponentKind == CK_VCallOffset ||
737 ComponentKind == CK_VBaseOffset ||
738 ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
739 assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
740
741 Value = ((Offset << 3) | ComponentKind);
742 }
743
744 VtableComponent(Kind ComponentKind, uintptr_t Ptr) {
745 assert((ComponentKind == CK_RTTI ||
Anders Carlsson848fa642010-02-11 18:20:28 +0000746 ComponentKind == CK_FunctionPointer ||
747 ComponentKind == CK_CompleteDtorPointer ||
Anders Carlsson1f464662010-02-19 20:08:13 +0000748 ComponentKind == CK_DeletingDtorPointer ||
749 ComponentKind == CK_UnusedFunctionPointer) &&
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000750 "Invalid component kind!");
751
752 assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
753
754 Value = Ptr | ComponentKind;
755 }
756
757 int64_t getOffset() const {
758 assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
759 getKind() == CK_OffsetToTop) && "Invalid component kind!");
760
761 return Value >> 3;
762 }
763
764 uintptr_t getPointer() const {
Anders Carlsson848fa642010-02-11 18:20:28 +0000765 assert((getKind() == CK_RTTI ||
766 getKind() == CK_FunctionPointer ||
767 getKind() == CK_CompleteDtorPointer ||
Anders Carlsson1f464662010-02-19 20:08:13 +0000768 getKind() == CK_DeletingDtorPointer ||
769 getKind() == CK_UnusedFunctionPointer) &&
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000770 "Invalid component kind!");
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000771
772 return static_cast<uintptr_t>(Value & ~7ULL);
773 }
774
775 /// The kind is stored in the lower 3 bits of the value. For offsets, we
776 /// make use of the facts that classes can't be larger than 2^55 bytes,
777 /// so we store the offset in the lower part of the 61 bytes that remain.
778 /// (The reason that we're not simply using a PointerIntPair here is that we
779 /// need the offsets to be 64-bit, even when on a 32-bit machine).
780 int64_t Value;
781};
782
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000783/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
784struct VCallOffsetMap {
785
786 typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy;
787
788 /// Offsets - Keeps track of methods and their offsets.
789 // FIXME: This should be a real map and not a vector.
790 llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets;
791
Anders Carlssoneb577d02010-02-18 17:26:40 +0000792 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
793 /// can share the same vcall offset.
794 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
795 const CXXMethodDecl *RHS);
796
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000797public:
798 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
799 /// add was successful, or false if there was already a member function with
800 /// the same signature in the map.
801 bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset);
802
803 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
804 /// vtable address point) for the given virtual member function.
805 int64_t getVCallOffsetOffset(const CXXMethodDecl *MD);
806
807 /// clear - Clear the offset map.
808 void clear() { Offsets.clear(); }
809};
810
Anders Carlssoneb577d02010-02-18 17:26:40 +0000811bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
812 const CXXMethodDecl *RHS) {
813 assert(LHS->isVirtual() && "LHS must be virtual!");
814 assert(RHS->isVirtual() && "LHS must be virtual!");
815
816 // FIXME: We need to check more things here.
817
818 DeclarationName LHSName = LHS->getDeclName();
819 DeclarationName RHSName = RHS->getDeclName();
820 if (LHSName.getNameKind() != LHSName.getNameKind())
821 return false;
822
823 switch (LHSName.getNameKind()) {
824 default:
825 assert(false && "Unhandled name kind!");
826 case DeclarationName::Identifier:
827 if (LHSName.getAsIdentifierInfo() != RHSName.getAsIdentifierInfo())
828 return false;
829 }
830
831 return true;
832}
833
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000834bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
835 int64_t OffsetOffset) {
Anders Carlssoneb577d02010-02-18 17:26:40 +0000836 // Check if we can reuse an offset.
837 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
838 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
839 return false;
840 }
841
842 // Add the offset.
843 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000844 return true;
845}
846
847int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
Anders Carlssoneb577d02010-02-18 17:26:40 +0000848 // Look for an offset.
849 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
850 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
851 return Offsets[I].second;
852 }
853
854 assert(false && "Should always find a vcall offset offset!");
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000855 return 0;
856}
857
Anders Carlssond68c0832010-02-25 03:45:56 +0000858/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
859class VCallAndVBaseOffsetBuilder {
860 /// MostDerivedClass - The most derived class for which we're building this
861 /// vtable.
862 const CXXRecordDecl *MostDerivedClass;
863
864 /// Context - The ASTContext which we will use for layout information.
865 ASTContext &Context;
866
867 /// Components - vcall and vbase offset components
868 typedef llvm::SmallVector<VtableComponent, 64> VtableComponentVectorTy;
869 VtableComponentVectorTy Components;
870
871 /// VisitedVirtualBases - Visited virtual bases.
872 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
873
874 /// VCallOffsets - Keeps track of vcall offsets.
875 VCallOffsetMap VCallOffsets;
876
877 /// FinalOverriders - The final overriders of the most derived class.
878 /// (Can be null when we're not building a vtable of the most derived class).
879 const FinalOverriders *Overriders;
880
881 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
882 /// given base subobject.
883 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
884 uint64_t RealBaseOffset);
885
886 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
887 void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
888
889 /// AddVBaseOffsets - Add vbase offsets for the given class.
890 void AddVBaseOffsets(const CXXRecordDecl *Base, int64_t OffsetToTop);
891
892public:
893 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
894 const FinalOverriders *Overriders,
895 BaseSubobject Base, bool BaseIsVirtual)
896 : MostDerivedClass(MostDerivedClass),
897 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
898
899 // Add vcall and vbase offsets.
900 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, Base.getBaseOffset());
901 }
902
903 /// Methods for iterating over the components.
904 typedef VtableComponentVectorTy::const_reverse_iterator const_iterator;
905 const_iterator components_begin() const { return Components.rbegin(); }
906 const_iterator components_end() const { return Components.rend(); }
907
908 /// FIXME: Get rid of this getter.
909 const VCallOffsetMap& getVCallOffsets() const { return VCallOffsets; }
910};
911
912void
913VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
914 bool BaseIsVirtual,
915 uint64_t RealBaseOffset) {
916 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
917
918 // Itanium C++ ABI 2.5.2:
919 // ..in classes sharing a virtual table with a primary base class, the vcall
920 // and vbase offsets added by the derived class all come before the vcall
921 // and vbase offsets required by the base class, so that the latter may be
922 // laid out as required by the base class without regard to additions from
923 // the derived class(es).
924
925 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
926 // emit them for the primary base first).
927 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
928 bool PrimaryBaseIsVirtual = Layout.getPrimaryBaseWasVirtual();
929
930 uint64_t PrimaryBaseOffset;
931
932 // Get the base offset of the primary base.
933 if (PrimaryBaseIsVirtual) {
934 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
935 "Primary vbase should have a zero offset!");
936
937 const ASTRecordLayout &MostDerivedClassLayout =
938 Context.getASTRecordLayout(MostDerivedClass);
939
940 PrimaryBaseOffset =
941 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
942 } else {
943 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
944 "Primary base should have a zero offset!");
945
946 PrimaryBaseOffset = Base.getBaseOffset();
947 }
948
949 AddVCallAndVBaseOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
950 PrimaryBaseIsVirtual, RealBaseOffset);
951 }
952
953 // FIXME: Don't use /8 here.
954 int64_t OffsetToTop = -(int64_t)Base.getBaseOffset() / 8;
955 AddVBaseOffsets(Base.getBase(), OffsetToTop);
956
957 // We only want to add vcall offsets for virtual bases.
958 if (BaseIsVirtual)
959 AddVCallOffsets(Base, RealBaseOffset);
960}
961
962void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
963 uint64_t VBaseOffset) {
964 const CXXRecordDecl *RD = Base.getBase();
965 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
966
967 // Handle the primary base first.
968 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
969 uint64_t PrimaryBaseOffset;
970
971 // Get the base offset of the primary base.
972 if (Layout.getPrimaryBaseWasVirtual()) {
973 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
974 "Primary vbase should have a zero offset!");
975
976 const ASTRecordLayout &MostDerivedClassLayout =
977 Context.getASTRecordLayout(MostDerivedClass);
978
979 PrimaryBaseOffset =
980 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
981 } else {
982 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
983 "Primary base should have a zero offset!");
984
985 PrimaryBaseOffset = Base.getBaseOffset();
986 }
987
988 AddVCallOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
989 VBaseOffset);
990 }
991
992 // Add the vcall offsets.
993 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
994 E = RD->method_end(); I != E; ++I) {
995 const CXXMethodDecl *MD = *I;
996
997 if (!MD->isVirtual())
998 continue;
999
1000 // OffsetIndex is the index of this vcall offset, relative to the vtable
1001 // address point. (We subtract 3 to account for the information just
1002 // above the address point, the RTTI info, the offset to top, and the
1003 // vcall offset itself).
1004 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
1005
1006 // FIXME: We shouldn't use / 8 here.
1007 int64_t OffsetOffset = OffsetIndex *
1008 (int64_t)Context.Target.getPointerWidth(0) / 8;
1009
1010 // Don't add a vcall offset if we already have one for this member function
1011 // signature.
1012 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
1013 continue;
1014
1015 int64_t Offset = 0;
1016
1017 if (Overriders) {
1018 // Get the final overrider.
1019 FinalOverriders::OverriderInfo Overrider =
1020 Overriders->getOverrider(Base, MD);
1021
1022 /// The vcall offset is the offset from the virtual base to the object where
1023 /// the function was overridden.
1024 // FIXME: We should not use / 8 here.
1025 Offset = (int64_t)(Overrider.BaseOffset - VBaseOffset) / 8;
1026 }
1027
1028 Components.push_back(VtableComponent::MakeVCallOffset(Offset));
1029 }
1030
1031 // And iterate over all non-virtual bases (ignoring the primary base).
1032 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1033 E = RD->bases_end(); I != E; ++I) {
1034
1035 if (I->isVirtual())
1036 continue;
1037
1038 const CXXRecordDecl *BaseDecl =
1039 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1040
1041 // Get the base offset of this base.
1042 uint64_t BaseOffset = Base.getBaseOffset() +
1043 Layout.getBaseClassOffset(BaseDecl);
1044
1045 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset);
1046 }
1047}
1048
1049
1050void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
1051 int64_t OffsetToTop) {
1052 const ASTRecordLayout &MostDerivedClassLayout =
1053 Context.getASTRecordLayout(MostDerivedClass);
1054
1055 // Add vbase offsets.
1056 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1057 E = RD->bases_end(); I != E; ++I) {
1058 const CXXRecordDecl *BaseDecl =
1059 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1060
1061 // Check if this is a virtual base that we haven't visited before.
1062 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
1063 // FIXME: We shouldn't use / 8 here.
1064 uint64_t Offset =
1065 OffsetToTop + MostDerivedClassLayout.getVBaseClassOffset(BaseDecl) / 8;
1066
1067 Components.push_back(VtableComponent::MakeVBaseOffset(Offset));
1068 }
1069
1070 // Check the base class looking for more vbase offsets.
1071 AddVBaseOffsets(BaseDecl, OffsetToTop);
1072 }
1073}
1074
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001075/// VtableBuilder - Class for building vtable layout information.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001076class VtableBuilder {
Anders Carlsson57071e22010-02-12 05:25:12 +00001077public:
1078 /// PrimaryBasesSetTy - A set of direct and indirect primary bases.
1079 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> PrimaryBasesSetTy;
1080
1081private:
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001082 /// VtableInfo - Global vtable information.
1083 CGVtableInfo &VtableInfo;
1084
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001085 /// MostDerivedClass - The most derived class for which we're building this
1086 /// vtable.
1087 const CXXRecordDecl *MostDerivedClass;
1088
1089 /// Context - The ASTContext which we will use for layout information.
Anders Carlsson57071e22010-02-12 05:25:12 +00001090 ASTContext &Context;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001091
Anders Carlssonbdf73d82010-02-11 21:24:32 +00001092 /// FinalOverriders - The final overriders of the most derived class.
Anders Carlssond68c0832010-02-25 03:45:56 +00001093 const FinalOverriders Overriders;
Anders Carlssonbdf73d82010-02-11 21:24:32 +00001094
Anders Carlssona661a542010-02-16 04:49:44 +00001095 /// VCallAndVBaseOffsets - The vcall and vbase offset, of the vtable we're
1096 // building (in reverse order).
1097 llvm::SmallVector<VtableComponent, 64> VCallAndVBaseOffsets;
1098
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001099 /// VCallOffsets - Keeps track of vcall offsets for the current vtable.
1100 VCallOffsetMap VCallOffsets;
1101
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001102 /// Components - The components of the vtable being built.
1103 llvm::SmallVector<VtableComponent, 64> Components;
1104
Anders Carlsson822307b2010-02-11 17:18:51 +00001105 /// AddressPoints - Address points for the vtable being built.
1106 CGVtableInfo::AddressPointsMapTy AddressPoints;
1107
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001108 /// ReturnAdjustment - A return adjustment.
Anders Carlsson104f45c2010-02-12 17:37:14 +00001109 struct ReturnAdjustment {
1110 /// NonVirtual - The non-virtual adjustment from the derived object to its
1111 /// nearest virtual base.
1112 int64_t NonVirtual;
1113
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001114 /// VBaseOffsetOffset - The offset (in bytes), relative to the address point
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001115 /// of the virtual base class offset.
1116 int64_t VBaseOffsetOffset;
Anders Carlsson104f45c2010-02-12 17:37:14 +00001117
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001118 ReturnAdjustment() : NonVirtual(0), VBaseOffsetOffset(0) { }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001119
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001120 bool isEmpty() const { return !NonVirtual && !VBaseOffsetOffset; }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001121 };
1122
1123 /// ReturnAdjustments - The return adjustments needed in this vtable.
1124 llvm::SmallVector<std::pair<uint64_t, ReturnAdjustment>, 16>
1125 ReturnAdjustments;
1126
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001127 /// ThisAdjustment - A 'this' pointer adjustment thunk.
1128 struct ThisAdjustment {
1129 /// NonVirtual - The non-virtual adjustment from the derived object to its
1130 /// nearest virtual base.
1131 int64_t NonVirtual;
1132
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001133 /// VCallOffsetOffset - The offset (in bytes), relative to the address point
1134 /// of the virtual call offset.
1135 int64_t VCallOffsetOffset;
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001136
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001137 ThisAdjustment() : NonVirtual(0), VCallOffsetOffset(0) { }
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001138
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001139 bool isEmpty() const { return !NonVirtual && !VCallOffsetOffset; }
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001140 };
1141
1142 /// ThisAdjustments - The 'this' pointer adjustments needed in this vtable.
1143 llvm::SmallVector<std::pair<uint64_t, ThisAdjustment>, 16>
1144 ThisAdjustments;
1145
Anders Carlssona661a542010-02-16 04:49:44 +00001146 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1147
Anders Carlssonaf280c02010-02-23 03:48:14 +00001148 /// PrimaryVirtualBases - All known virtual bases who is a primary base of
1149 /// some other base.
1150 VisitedVirtualBasesSetTy PrimaryVirtualBases;
1151
Anders Carlssona661a542010-02-16 04:49:44 +00001152 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
Anders Carlsson340963f2010-02-17 03:11:55 +00001153 /// given base subobject.
1154 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
Anders Carlsson5edcc372010-02-24 16:43:12 +00001155 uint64_t RealBaseOffset,
Anders Carlssona661a542010-02-16 04:49:44 +00001156 VisitedVirtualBasesSetTy &VBases);
1157
Anders Carlssond9a67042010-02-17 06:07:19 +00001158 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
Anders Carlssoncc6bcbb2010-02-23 03:14:49 +00001159 void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
Anders Carlssond9a67042010-02-17 06:07:19 +00001160
Anders Carlssona661a542010-02-16 04:49:44 +00001161 /// AddVBaseOffsets - Add vbase offsets for the given class.
Anders Carlsson340963f2010-02-17 03:11:55 +00001162 void AddVBaseOffsets(const CXXRecordDecl *Base, int64_t OffsetToTop,
Anders Carlssona661a542010-02-16 04:49:44 +00001163 VisitedVirtualBasesSetTy &VBases);
1164
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001165 /// ComputeReturnAdjustment - Compute the return adjustment given a return
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001166 /// adjustment base offset.
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001167 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001168
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001169 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
1170 /// given virtual member function and the 'this' pointer adjustment base
1171 /// offset.
1172 ThisAdjustment ComputeThisAdjustment(const CXXMethodDecl *MD,
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001173 BaseOffset Offset);
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001174
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001175 /// AddMethod - Add a single virtual member function to the vtable
1176 /// components vector.
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001177 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment,
1178 ThisAdjustment ThisAdjustment);
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001179
Anders Carlsson464c8f12010-02-23 04:26:39 +00001180 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
1181 /// part of the vtable.
1182 ///
1183 /// Itanium C++ ABI 2.5.2:
1184 ///
1185 /// struct A { virtual void f(); };
1186 /// struct B : virtual public A { int i; };
1187 /// struct C : virtual public A { int j; };
1188 /// struct D : public B, public C {};
1189 ///
1190 /// When B and C are declared, A is a primary base in each case, so although
1191 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
1192 /// adjustment is required and no thunk is generated. However, inside D
1193 /// objects, A is no longer a primary base of C, so if we allowed calls to
1194 /// C::f() to use the copy of A's vtable in the C subobject, we would need
1195 /// to adjust this from C* to B::A*, which would require a third-party
1196 /// thunk. Since we require that a call to C::f() first convert to A*,
1197 /// C-in-D's copy of A's vtable is never referenced, so this is not
1198 /// necessary.
1199 bool IsOverriderUsed(BaseSubobject Base,
1200 BaseSubobject FirstBaseInPrimaryBaseChain,
1201 FinalOverriders::OverriderInfo Overrider) const;
1202
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001203 /// AddMethods - Add the methods of this base subobject and all its
1204 /// primary bases to the vtable components vector.
Anders Carlsson464c8f12010-02-23 04:26:39 +00001205 void AddMethods(BaseSubobject Base, BaseSubobject FirstBaseInPrimaryBaseChain,
1206 PrimaryBasesSetTy &PrimaryBases);
Anders Carlsson89ad4212010-02-16 16:26:28 +00001207
1208 // LayoutVtable - Layout the vtable for the most derived class, including its
1209 // secondary vtables and any vtables for virtual bases.
1210 void LayoutVtable();
1211
1212 /// LayoutPrimaryAndAndSecondaryVtables - Layout the primary vtable for the
1213 /// given base subobject, as well as all its secondary vtables.
Anders Carlsson340963f2010-02-17 03:11:55 +00001214 void LayoutPrimaryAndAndSecondaryVtables(BaseSubobject Base,
1215 bool BaseIsVirtual);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001216
Anders Carlssonc7b63162010-02-16 16:02:57 +00001217 /// LayoutSecondaryVtables - Layout the secondary vtables for the given base
1218 /// subobject.
1219 void LayoutSecondaryVtables(BaseSubobject Base);
1220
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001221 /// LayoutVtablesForVirtualBases - Layout vtables for all virtual bases of the
1222 /// given base (excluding any primary bases).
1223 void LayoutVtablesForVirtualBases(const CXXRecordDecl *RD,
1224 VisitedVirtualBasesSetTy &VBases);
1225
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001226public:
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001227 VtableBuilder(CGVtableInfo &VtableInfo, const CXXRecordDecl *MostDerivedClass)
1228 : VtableInfo(VtableInfo), MostDerivedClass(MostDerivedClass),
Anders Carlssonbdf73d82010-02-11 21:24:32 +00001229 Context(MostDerivedClass->getASTContext()), Overriders(MostDerivedClass) {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001230
Anders Carlsson89ad4212010-02-16 16:26:28 +00001231 LayoutVtable();
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001232 }
1233
1234 /// dumpLayout - Dump the vtable layout.
1235 void dumpLayout(llvm::raw_ostream&);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001236};
1237
Anders Carlsson57071e22010-02-12 05:25:12 +00001238/// OverridesMethodInPrimaryBase - Checks whether whether this virtual member
1239/// function overrides a member function in a direct or indirect primary base.
1240/// Returns the overridden member function, or null if none was found.
1241static const CXXMethodDecl *
1242OverridesMethodInPrimaryBase(const CXXMethodDecl *MD,
1243 VtableBuilder::PrimaryBasesSetTy &PrimaryBases) {
1244 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1245 E = MD->end_overridden_methods(); I != E; ++I) {
1246 const CXXMethodDecl *OverriddenMD = *I;
1247 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
1248 assert(OverriddenMD->isCanonicalDecl() &&
1249 "Should have the canonical decl of the overridden RD!");
1250
1251 if (PrimaryBases.count(OverriddenRD))
1252 return OverriddenMD;
1253 }
1254
1255 return 0;
1256}
1257
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001258VtableBuilder::ReturnAdjustment
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001259VtableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001260 ReturnAdjustment Adjustment;
1261
1262 if (!Offset.isEmpty()) {
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001263 if (Offset.VirtualBase) {
1264 // Get the virtual base offset offset.
1265 Adjustment.VBaseOffsetOffset =
1266 VtableInfo.getVirtualBaseOffsetIndex(Offset.DerivedClass,
1267 Offset.VirtualBase);
1268 // FIXME: Once the assert in getVirtualBaseOffsetIndex is back again,
1269 // we can get rid of this assert.
1270 assert(Adjustment.VBaseOffsetOffset != 0 &&
1271 "Invalid base offset offset!");
1272 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001273
1274 Adjustment.NonVirtual = Offset.NonVirtualOffset;
1275 }
1276
1277 return Adjustment;
1278}
1279
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001280VtableBuilder::ThisAdjustment
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001281VtableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001282 BaseOffset Offset) {
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001283 ThisAdjustment Adjustment;
1284
1285 if (!Offset.isEmpty()) {
Anders Carlssoneb577d02010-02-18 17:26:40 +00001286 if (Offset.VirtualBase) {
1287 // Get the vcall offset offset.
1288 Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
1289 }
1290
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001291 Adjustment.NonVirtual = Offset.NonVirtualOffset;
1292 }
1293
1294 return Adjustment;
1295}
1296
Anders Carlsson57071e22010-02-12 05:25:12 +00001297void
Anders Carlsson340963f2010-02-17 03:11:55 +00001298VtableBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
1299 bool BaseIsVirtual,
Anders Carlsson5edcc372010-02-24 16:43:12 +00001300 uint64_t RealBaseOffset,
Anders Carlssona661a542010-02-16 04:49:44 +00001301 VisitedVirtualBasesSetTy &VBases) {
Anders Carlsson340963f2010-02-17 03:11:55 +00001302 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
Anders Carlssona661a542010-02-16 04:49:44 +00001303
1304 // Itanium C++ ABI 2.5.2:
1305 // ..in classes sharing a virtual table with a primary base class, the vcall
1306 // and vbase offsets added by the derived class all come before the vcall
1307 // and vbase offsets required by the base class, so that the latter may be
1308 // laid out as required by the base class without regard to additions from
1309 // the derived class(es).
1310
1311 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
1312 // emit them for the primary base first).
Anders Carlsson340963f2010-02-17 03:11:55 +00001313 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1314 bool PrimaryBaseIsVirtual = Layout.getPrimaryBaseWasVirtual();
Anders Carlsson5edcc372010-02-24 16:43:12 +00001315
1316 uint64_t PrimaryBaseOffset;
1317
1318 // Get the base offset of the primary base.
1319 if (PrimaryBaseIsVirtual) {
1320 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
1321 "Primary vbase should have a zero offset!");
1322
1323 const ASTRecordLayout &MostDerivedClassLayout =
1324 Context.getASTRecordLayout(MostDerivedClass);
1325
1326 PrimaryBaseOffset =
1327 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1328 } else {
1329 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
1330 "Primary base should have a zero offset!");
1331
1332 PrimaryBaseOffset = Base.getBaseOffset();
1333 }
1334
1335 AddVCallAndVBaseOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1336 PrimaryBaseIsVirtual, RealBaseOffset, VBases);
Anders Carlsson340963f2010-02-17 03:11:55 +00001337 }
Anders Carlssona661a542010-02-16 04:49:44 +00001338
Anders Carlsson340963f2010-02-17 03:11:55 +00001339 // FIXME: Don't use /8 here.
1340 int64_t OffsetToTop = -(int64_t)Base.getBaseOffset() / 8;
1341 AddVBaseOffsets(Base.getBase(), OffsetToTop, VBases);
Anders Carlssond9a67042010-02-17 06:07:19 +00001342
Anders Carlssona455c802010-02-23 02:47:31 +00001343 // We only want to add vcall offsets for virtual bases.
Anders Carlssonaf280c02010-02-23 03:48:14 +00001344 if (BaseIsVirtual)
Anders Carlsson5edcc372010-02-24 16:43:12 +00001345 AddVCallOffsets(Base, RealBaseOffset);
Anders Carlssond9a67042010-02-17 06:07:19 +00001346}
1347
Anders Carlssoncc6bcbb2010-02-23 03:14:49 +00001348void VtableBuilder::AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset) {
Anders Carlssond9a67042010-02-17 06:07:19 +00001349 const CXXRecordDecl *RD = Base.getBase();
Anders Carlssond9a67042010-02-17 06:07:19 +00001350 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonc84a8bf2010-02-17 06:30:02 +00001351
1352 // Handle the primary base first.
Anders Carlsson92f54322010-02-23 03:26:17 +00001353 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
Anders Carlssonaf280c02010-02-23 03:48:14 +00001354 uint64_t PrimaryBaseOffset;
1355
Anders Carlssonc84a8bf2010-02-17 06:30:02 +00001356 // Get the base offset of the primary base.
Anders Carlssonaf280c02010-02-23 03:48:14 +00001357 if (Layout.getPrimaryBaseWasVirtual()) {
1358 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
1359 "Primary vbase should have a zero offset!");
1360
1361 const ASTRecordLayout &MostDerivedClassLayout =
1362 Context.getASTRecordLayout(MostDerivedClass);
1363
1364 PrimaryBaseOffset =
1365 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1366 } else {
1367 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
1368 "Primary base should have a zero offset!");
1369
1370 PrimaryBaseOffset = Base.getBaseOffset();
1371 }
Anders Carlssonc84a8bf2010-02-17 06:30:02 +00001372
Anders Carlssoncc6bcbb2010-02-23 03:14:49 +00001373 AddVCallOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1374 VBaseOffset);
Anders Carlssonc84a8bf2010-02-17 06:30:02 +00001375 }
Anders Carlssond9a67042010-02-17 06:07:19 +00001376
1377 // Add the vcall offsets.
1378 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1379 E = RD->method_end(); I != E; ++I) {
1380 const CXXMethodDecl *MD = *I;
1381
1382 if (!MD->isVirtual())
1383 continue;
1384
Anders Carlssoneb577d02010-02-18 17:26:40 +00001385 // OffsetIndex is the index of this vcall offset, relative to the vtable
1386 // address point. (We subtract 3 to account for the information just
1387 // above the address point, the RTTI info, the offset to top, and the
1388 // vcall offset itself).
Anders Carlsson71b202e2010-02-18 18:20:49 +00001389 int64_t OffsetIndex = -(int64_t)(3 + VCallAndVBaseOffsets.size());
Anders Carlssoneb577d02010-02-18 17:26:40 +00001390
1391 // FIXME: We shouldn't use / 8 here.
1392 int64_t OffsetOffset = OffsetIndex *
1393 (int64_t)Context.Target.getPointerWidth(0) / 8;
1394
1395 // Don't add a vcall offset if we already have one for this member function
Anders Carlssond9a67042010-02-17 06:07:19 +00001396 // signature.
Anders Carlssoneb577d02010-02-18 17:26:40 +00001397 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
1398 continue;
Anders Carlsson8b6765f2010-02-18 17:32:33 +00001399
Anders Carlssoncc6bcbb2010-02-23 03:14:49 +00001400 // Get the final overrider.
1401 FinalOverriders::OverriderInfo Overrider =
1402 Overriders.getOverrider(Base, MD);
1403
1404 /// The vcall offset is the offset from the virtual base to the object where
1405 /// the function was overridden.
1406 // FIXME: We should not use / 8 here.
1407 int64_t Offset = (int64_t)(Overrider.BaseOffset - VBaseOffset) / 8;
Anders Carlssond9a67042010-02-17 06:07:19 +00001408
1409 VCallAndVBaseOffsets.push_back(VtableComponent::MakeVCallOffset(Offset));
1410 }
1411
1412 // And iterate over all non-virtual bases (ignoring the primary base).
1413 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1414 E = RD->bases_end(); I != E; ++I) {
1415
1416 if (I->isVirtual())
1417 continue;
1418
1419 const CXXRecordDecl *BaseDecl =
1420 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1421
Anders Carlssond9a67042010-02-17 06:07:19 +00001422 // Get the base offset of this base.
1423 uint64_t BaseOffset = Base.getBaseOffset() +
1424 Layout.getBaseClassOffset(BaseDecl);
1425
Anders Carlssoncc6bcbb2010-02-23 03:14:49 +00001426 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset);
Anders Carlssond9a67042010-02-17 06:07:19 +00001427 }
Anders Carlssona661a542010-02-16 04:49:44 +00001428}
1429
1430void VtableBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
1431 int64_t OffsetToTop,
1432 VisitedVirtualBasesSetTy &VBases) {
Anders Carlsson852213e2010-02-16 04:59:55 +00001433 const ASTRecordLayout &MostDerivedClassLayout =
1434 Context.getASTRecordLayout(MostDerivedClass);
1435
1436 // Add vbase offsets.
1437 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1438 E = RD->bases_end(); I != E; ++I) {
1439 const CXXRecordDecl *BaseDecl =
1440 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1441
1442 // Check if this is a virtual base that we haven't visited before.
1443 if (I->isVirtual() && VBases.insert(BaseDecl)) {
1444 // FIXME: We shouldn't use / 8 here.
1445 uint64_t Offset =
1446 OffsetToTop + MostDerivedClassLayout.getVBaseClassOffset(BaseDecl) / 8;
1447
1448 VCallAndVBaseOffsets.push_back(VtableComponent::MakeVBaseOffset(Offset));
1449 }
1450
1451 // Check the base class looking for more vbase offsets.
1452 AddVBaseOffsets(BaseDecl, OffsetToTop, VBases);
1453 }
Anders Carlssona661a542010-02-16 04:49:44 +00001454}
1455
1456void
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001457VtableBuilder::AddMethod(const CXXMethodDecl *MD,
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001458 ReturnAdjustment ReturnAdjustment,
1459 ThisAdjustment ThisAdjustment) {
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001460 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1461 assert(ReturnAdjustment.isEmpty() &&
1462 "Destructor can't have return adjustment!");
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001463 // Add the 'this' pointer adjustments if necessary.
1464 if (!ThisAdjustment.isEmpty()) {
1465 ThisAdjustments.push_back(std::make_pair(Components.size(),
1466 ThisAdjustment));
1467 ThisAdjustments.push_back(std::make_pair(Components.size() + 1,
1468 ThisAdjustment));
1469 }
1470
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001471 // Add both the complete destructor and the deleting destructor.
1472 Components.push_back(VtableComponent::MakeCompleteDtor(DD));
1473 Components.push_back(VtableComponent::MakeDeletingDtor(DD));
1474 } else {
1475 // Add the return adjustment if necessary.
1476 if (!ReturnAdjustment.isEmpty())
1477 ReturnAdjustments.push_back(std::make_pair(Components.size(),
1478 ReturnAdjustment));
1479
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001480 // Add the 'this' pointer adjustment if necessary.
1481 if (!ThisAdjustment.isEmpty())
1482 ThisAdjustments.push_back(std::make_pair(Components.size(),
1483 ThisAdjustment));
1484
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001485 // Add the function.
1486 Components.push_back(VtableComponent::MakeFunction(MD));
1487 }
1488}
1489
Anders Carlsson464c8f12010-02-23 04:26:39 +00001490bool
1491VtableBuilder::IsOverriderUsed(BaseSubobject Base,
1492 BaseSubobject FirstBaseInPrimaryBaseChain,
1493 FinalOverriders::OverriderInfo Overrider) const {
1494 // If the base and the first base in the primary base chain have the same
1495 // offsets, then this overrider will be used.
1496 if (Base.getBaseOffset() == FirstBaseInPrimaryBaseChain.getBaseOffset())
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001497 return true;
1498
1499 // We know now that Base (or a direct or indirect base of it) is a primary
1500 // base in part of the class hierarchy, but not a primary base in the most
1501 // derived class.
1502
1503 // If the overrider is the first base in the primary base chain, we know
1504 // that the overrider will be used.
1505 if (Overrider.Method->getParent() == FirstBaseInPrimaryBaseChain.getBase())
Anders Carlsson464c8f12010-02-23 04:26:39 +00001506 return true;
1507
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001508 VtableBuilder::PrimaryBasesSetTy PrimaryBases;
1509
1510 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain.getBase();
1511 PrimaryBases.insert(RD);
1512
1513 // Now traverse the base chain, starting with the first base, until we find
1514 // the base that is no longer a primary base.
1515 while (true) {
1516 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1517 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1518
1519 if (!PrimaryBase)
1520 break;
1521
1522 if (Layout.getPrimaryBaseWasVirtual()) {
1523 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
1524 "Primary base should always be at offset 0!");
1525
1526 const ASTRecordLayout &MostDerivedClassLayout =
1527 Context.getASTRecordLayout(MostDerivedClass);
1528
1529 // Now check if this is the primary base that is not a primary base in the
1530 // most derived class.
1531 if (MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase) !=
1532 FirstBaseInPrimaryBaseChain.getBaseOffset()) {
1533 // We found it, stop walking the chain.
1534 break;
1535 }
1536 } else {
1537 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
1538 "Primary base should always be at offset 0!");
1539 }
1540 }
1541
1542 // If the final overrider is an override of one of the primary bases,
1543 // then we know that it will be used.
1544 return OverridesMethodInPrimaryBase(Overrider.Method, PrimaryBases);
Anders Carlsson464c8f12010-02-23 04:26:39 +00001545}
1546
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001547void
Anders Carlsson464c8f12010-02-23 04:26:39 +00001548VtableBuilder::AddMethods(BaseSubobject Base,
1549 BaseSubobject FirstBaseInPrimaryBaseChain,
1550 PrimaryBasesSetTy &PrimaryBases) {
Anders Carlsson57071e22010-02-12 05:25:12 +00001551 const CXXRecordDecl *RD = Base.getBase();
1552
1553 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1554
1555 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
Anders Carlssonaf280c02010-02-23 03:48:14 +00001556 uint64_t BaseOffset;
1557 if (Layout.getPrimaryBaseWasVirtual()) {
1558 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
1559 "Primary vbase should have a zero offset!");
1560
1561 const ASTRecordLayout &MostDerivedClassLayout =
1562 Context.getASTRecordLayout(MostDerivedClass);
1563
1564 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1565
1566 // Keep track of this primary virtual base.
1567 PrimaryVirtualBases.insert(PrimaryBase);
1568 } else {
Anders Carlsson57071e22010-02-12 05:25:12 +00001569 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
1570 "Primary base should have a zero offset!");
Anders Carlssonaf280c02010-02-23 03:48:14 +00001571
1572 BaseOffset = Base.getBaseOffset();
1573 }
Anders Carlsson57071e22010-02-12 05:25:12 +00001574
Anders Carlsson464c8f12010-02-23 04:26:39 +00001575 AddMethods(BaseSubobject(PrimaryBase, BaseOffset),
1576 FirstBaseInPrimaryBaseChain, PrimaryBases);
Anders Carlsson57071e22010-02-12 05:25:12 +00001577
1578 if (!PrimaryBases.insert(PrimaryBase))
1579 assert(false && "Found a duplicate primary base!");
1580 }
Anders Carlsson822307b2010-02-11 17:18:51 +00001581
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001582 // Now go through all virtual member functions and add them.
1583 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1584 E = RD->method_end(); I != E; ++I) {
1585 const CXXMethodDecl *MD = *I;
Anders Carlsson57071e22010-02-12 05:25:12 +00001586
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001587 if (!MD->isVirtual())
1588 continue;
Anders Carlsson57071e22010-02-12 05:25:12 +00001589
1590 // Get the final overrider.
Anders Carlssona7575822010-02-12 16:55:34 +00001591 FinalOverriders::OverriderInfo Overrider =
1592 Overriders.getOverrider(Base, MD);
Anders Carlsson57071e22010-02-12 05:25:12 +00001593
1594 // Check if this virtual member function overrides a method in a primary
1595 // base. If this is the case, and the return type doesn't require adjustment
1596 // then we can just use the member function from the primary base.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001597 if (const CXXMethodDecl *OverriddenMD =
1598 OverridesMethodInPrimaryBase(MD, PrimaryBases)) {
Anders Carlssondf31af12010-02-13 23:17:31 +00001599 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1600 OverriddenMD).isEmpty())
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001601 continue;
1602 }
Anders Carlsson0c0eeb22010-02-13 02:02:03 +00001603
Anders Carlsson464c8f12010-02-23 04:26:39 +00001604 // Check if this overrider is going to be used.
1605 if (!IsOverriderUsed(Base, FirstBaseInPrimaryBaseChain, Overrider)) {
1606 const CXXMethodDecl *OverriderMD = Overrider.Method;
1607 Components.push_back(VtableComponent::MakeUnusedFunction(OverriderMD));
1608 continue;
1609 }
1610
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001611 // Check if this overrider needs a return adjustment.
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001612 BaseOffset ReturnAdjustmentOffset =
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001613 Overriders.getReturnAdjustmentOffset(Base, MD);
1614
1615 ReturnAdjustment ReturnAdjustment =
1616 ComputeReturnAdjustment(ReturnAdjustmentOffset);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001617
Anders Carlssond91e7332010-02-24 22:27:12 +00001618 ThisAdjustment ThisAdjustment;
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001619
Anders Carlssond91e7332010-02-24 22:27:12 +00001620 // Check if this overrider needs a 'this' pointer adjustment.
1621 // (We use the base offset of the first base in the primary base chain here,
1622 // because Base will not have the right offset if it is a primary virtual
1623 // base that is not a primary base in the complete class.
1624 if (FirstBaseInPrimaryBaseChain.getBaseOffset() != Overrider.BaseOffset) {
1625 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1626 Overrider.BaseOffset);
1627
1628 BaseOffset ThisAdjustmentOffset =
1629 Overriders.ComputeThisAdjustmentBaseOffset(FirstBaseInPrimaryBaseChain,
1630 OverriderBaseSubobject);
1631
1632 ThisAdjustment = ComputeThisAdjustment(Overrider.Method,
1633 ThisAdjustmentOffset);
1634 }
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001635
1636 AddMethod(Overrider.Method, ReturnAdjustment, ThisAdjustment);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001637 }
1638}
1639
Anders Carlsson89ad4212010-02-16 16:26:28 +00001640void VtableBuilder::LayoutVtable() {
Anders Carlsson340963f2010-02-17 03:11:55 +00001641 LayoutPrimaryAndAndSecondaryVtables(BaseSubobject(MostDerivedClass, 0),
1642 /*BaseIsVirtual=*/false);
Anders Carlsson89ad4212010-02-16 16:26:28 +00001643
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001644 VisitedVirtualBasesSetTy VBases;
1645 LayoutVtablesForVirtualBases(MostDerivedClass, VBases);
Anders Carlsson89ad4212010-02-16 16:26:28 +00001646}
1647
Anders Carlsson340963f2010-02-17 03:11:55 +00001648void VtableBuilder::LayoutPrimaryAndAndSecondaryVtables(BaseSubobject Base,
1649 bool BaseIsVirtual) {
Chris Lattner04a23112010-02-17 21:42:34 +00001650 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
Anders Carlssonb828afa2010-02-14 17:05:59 +00001651
Anders Carlsson852213e2010-02-16 04:59:55 +00001652 // Add vcall and vbase offsets for this vtable.
Anders Carlssond68c0832010-02-25 03:45:56 +00001653 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, &Overriders,
1654 Base, BaseIsVirtual);
1655 Components.append(Builder.components_begin(), Builder.components_end());
1656
1657 // FIXME: This is not how we should do vcall offsets.
1658 VCallOffsets = Builder.getVCallOffsets();
Anders Carlsson852213e2010-02-16 04:59:55 +00001659
1660 // Add the offset to top.
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001661 // FIXME: This is not going to be right for construction vtables.
Anders Carlssone67dc302010-02-14 00:16:19 +00001662 // FIXME: We should not use / 8 here.
Anders Carlsson340963f2010-02-17 03:11:55 +00001663 int64_t OffsetToTop = -(int64_t)Base.getBaseOffset() / 8;
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001664 Components.push_back(VtableComponent::MakeOffsetToTop(OffsetToTop));
Anders Carlsson57071e22010-02-12 05:25:12 +00001665
1666 // Next, add the RTTI.
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001667 Components.push_back(VtableComponent::MakeRTTI(MostDerivedClass));
Anders Carlsson57071e22010-02-12 05:25:12 +00001668
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001669 uint64_t AddressPoint = Components.size();
Anders Carlsson57071e22010-02-12 05:25:12 +00001670
1671 // Now go through all virtual member functions and add them.
1672 PrimaryBasesSetTy PrimaryBases;
Anders Carlsson464c8f12010-02-23 04:26:39 +00001673 AddMethods(Base, Base, PrimaryBases);
Anders Carlsson57071e22010-02-12 05:25:12 +00001674
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001675 // Record the address point.
1676 AddressPoints.insert(std::make_pair(Base, AddressPoint));
1677
1678 // Record the address points for all primary bases.
1679 for (PrimaryBasesSetTy::const_iterator I = PrimaryBases.begin(),
1680 E = PrimaryBases.end(); I != E; ++I) {
1681 const CXXRecordDecl *BaseDecl = *I;
1682
1683 // We know that all the primary bases have the same offset as the base
1684 // subobject.
1685 BaseSubobject PrimaryBase(BaseDecl, Base.getBaseOffset());
1686 AddressPoints.insert(std::make_pair(PrimaryBase, AddressPoint));
1687 }
1688
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001689 // Clear the vcall offsets.
1690 VCallOffsets.clear();
Anders Carlsson5edcc372010-02-24 16:43:12 +00001691
1692 // Layout secondary vtables.
1693 LayoutSecondaryVtables(Base);
Anders Carlssonc7b63162010-02-16 16:02:57 +00001694}
1695
1696void VtableBuilder::LayoutSecondaryVtables(BaseSubobject Base) {
1697 // Itanium C++ ABI 2.5.2:
1698 // Following the primary virtual table of a derived class are secondary
1699 // virtual tables for each of its proper base classes, except any primary
1700 // base(s) with which it shares its primary virtual table.
1701
1702 const CXXRecordDecl *RD = Base.getBase();
Anders Carlsson57071e22010-02-12 05:25:12 +00001703 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1704 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Anders Carlssonc7b63162010-02-16 16:02:57 +00001705
Anders Carlsson57071e22010-02-12 05:25:12 +00001706 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1707 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonc7b63162010-02-16 16:02:57 +00001708 // Ignore virtual bases, we'll emit them later.
1709 if (I->isVirtual())
1710 continue;
1711
Anders Carlsson57071e22010-02-12 05:25:12 +00001712 const CXXRecordDecl *BaseDecl =
1713 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb828afa2010-02-14 17:05:59 +00001714
Anders Carlssona661a542010-02-16 04:49:44 +00001715 // Ignore bases that don't have a vtable.
1716 if (!BaseDecl->isDynamicClass())
1717 continue;
Anders Carlssonb828afa2010-02-14 17:05:59 +00001718
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001719 // Get the base offset of this base.
1720 uint64_t BaseOffset = Base.getBaseOffset() +
1721 Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc7b63162010-02-16 16:02:57 +00001722
1723 // Don't emit a secondary vtable for a primary base. We might however want
1724 // to emit secondary vtables for other bases of this base.
1725 if (BaseDecl == PrimaryBase) {
1726 LayoutSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset));
1727 continue;
1728 }
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001729
Anders Carlsson89ad4212010-02-16 16:26:28 +00001730 // Layout the primary vtable (and any secondary vtables) for this base.
Anders Carlsson340963f2010-02-17 03:11:55 +00001731 LayoutPrimaryAndAndSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
1732 /*BaseIsVirtual=*/false);
Anders Carlsson57071e22010-02-12 05:25:12 +00001733 }
1734}
1735
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001736void
1737VtableBuilder::LayoutVtablesForVirtualBases(const CXXRecordDecl *RD,
1738 VisitedVirtualBasesSetTy &VBases) {
1739 // Itanium C++ ABI 2.5.2:
1740 // Then come the virtual base virtual tables, also in inheritance graph
1741 // order, and again excluding primary bases (which share virtual tables with
1742 // the classes for which they are primary).
1743 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1744 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1745
1746 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1747 E = RD->bases_end(); I != E; ++I) {
1748 const CXXRecordDecl *BaseDecl =
1749 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1750
Anders Carlssonaf280c02010-02-23 03:48:14 +00001751 // Check if this base needs a vtable. (If it's virtual, not a primary base
1752 // of some other class, and we haven't visited it before).
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001753 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
Anders Carlssonaf280c02010-02-23 03:48:14 +00001754 BaseDecl != PrimaryBase && !PrimaryVirtualBases.count(BaseDecl) &&
1755 VBases.insert(BaseDecl)) {
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001756 const ASTRecordLayout &MostDerivedClassLayout =
1757 Context.getASTRecordLayout(MostDerivedClass);
1758 uint64_t BaseOffset =
1759 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1760
Anders Carlsson340963f2010-02-17 03:11:55 +00001761 LayoutPrimaryAndAndSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
1762 /*BaseIsVirtual=*/true);
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001763 }
1764
1765 // We only need to check the base for virtual base vtables if it actually
1766 // has virtual bases.
1767 if (BaseDecl->getNumVBases())
1768 LayoutVtablesForVirtualBases(BaseDecl, VBases);
1769 }
1770}
1771
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001772/// dumpLayout - Dump the vtable layout.
1773void VtableBuilder::dumpLayout(llvm::raw_ostream& Out) {
1774
1775 Out << "Vtable for '" << MostDerivedClass->getQualifiedNameAsString();
1776 Out << "' (" << Components.size() << " entries).\n";
1777
Anders Carlsson822307b2010-02-11 17:18:51 +00001778 // Iterate through the address points and insert them into a new map where
1779 // they are keyed by the index and not the base object.
1780 // Since an address point can be shared by multiple subobjects, we use an
1781 // STL multimap.
1782 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1783 for (CGVtableInfo::AddressPointsMapTy::const_iterator I =
1784 AddressPoints.begin(), E = AddressPoints.end(); I != E; ++I) {
1785 const BaseSubobject& Base = I->first;
1786 uint64_t Index = I->second;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001787
Anders Carlsson822307b2010-02-11 17:18:51 +00001788 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1789 }
1790
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001791 unsigned NextReturnAdjustmentIndex = 0;
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001792 unsigned NextThisAdjustmentIndex = 0;
Anders Carlsson822307b2010-02-11 17:18:51 +00001793 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001794 uint64_t Index = I;
1795
Anders Carlsson822307b2010-02-11 17:18:51 +00001796 if (AddressPointsByIndex.count(I)) {
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001797 if (AddressPointsByIndex.count(Index) == 1) {
1798 const BaseSubobject &Base = AddressPointsByIndex.find(Index)->second;
1799
1800 // FIXME: Instead of dividing by 8, we should be using CharUnits.
1801 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
1802 Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
1803 } else {
1804 uint64_t BaseOffset =
1805 AddressPointsByIndex.lower_bound(Index)->second.getBaseOffset();
1806
1807 // We store the class names in a set to get a stable order.
1808 std::set<std::string> ClassNames;
1809 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
1810 AddressPointsByIndex.lower_bound(Index), E =
1811 AddressPointsByIndex.upper_bound(Index); I != E; ++I) {
1812 assert(I->second.getBaseOffset() == BaseOffset &&
1813 "Invalid base offset!");
1814 const CXXRecordDecl *RD = I->second.getBase();
1815 ClassNames.insert(RD->getQualifiedNameAsString());
1816 }
1817
1818 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
1819 E = ClassNames.end(); I != E; ++I) {
1820 // FIXME: Instead of dividing by 8, we should be using CharUnits.
1821 Out << " -- (" << *I;
1822 Out << ", " << BaseOffset / 8 << ") vtable address --\n";
1823 }
1824 }
Anders Carlsson822307b2010-02-11 17:18:51 +00001825 }
1826
1827 Out << llvm::format("%4d | ", I);
1828
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001829 const VtableComponent &Component = Components[I];
1830
1831 // Dump the component.
1832 switch (Component.getKind()) {
Anders Carlssond9a67042010-02-17 06:07:19 +00001833
1834 case VtableComponent::CK_VCallOffset:
1835 Out << "vcall_offset (" << Component.getVCallOffset() << ")";
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001836 break;
Anders Carlsson852213e2010-02-16 04:59:55 +00001837
1838 case VtableComponent::CK_VBaseOffset:
1839 Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
1840 break;
1841
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001842 case VtableComponent::CK_OffsetToTop:
1843 Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
1844 break;
1845
1846 case VtableComponent::CK_RTTI:
1847 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1848 break;
1849
Anders Carlsson848fa642010-02-11 18:20:28 +00001850 case VtableComponent::CK_FunctionPointer: {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001851 const CXXMethodDecl *MD = Component.getFunctionDecl();
1852
Anders Carlsson848fa642010-02-11 18:20:28 +00001853 std::string Str =
1854 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1855 MD);
1856 Out << Str;
Anders Carlsson98241422010-02-12 02:38:13 +00001857 if (MD->isPure())
1858 Out << " [pure]";
1859
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001860 // If this function pointer has a return adjustment, dump it.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001861 if (NextReturnAdjustmentIndex < ReturnAdjustments.size() &&
1862 ReturnAdjustments[NextReturnAdjustmentIndex].first == I) {
1863 const ReturnAdjustment Adjustment =
1864 ReturnAdjustments[NextReturnAdjustmentIndex].second;
1865
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001866 Out << "\n [return adjustment: ";
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001867 Out << Adjustment.NonVirtual << " non-virtual";
1868
1869 if (Adjustment.VBaseOffsetOffset)
1870 Out << ", " << Adjustment.VBaseOffsetOffset << " vbase offset offset";
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001871
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001872 Out << ']';
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001873
1874 NextReturnAdjustmentIndex++;
1875 }
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001876
1877 // If this function pointer has a 'this' pointer adjustment, dump it.
1878 if (NextThisAdjustmentIndex < ThisAdjustments.size() &&
1879 ThisAdjustments[NextThisAdjustmentIndex].first == I) {
1880 const ThisAdjustment Adjustment =
1881 ThisAdjustments[NextThisAdjustmentIndex].second;
1882
1883 Out << "\n [this adjustment: ";
1884 Out << Adjustment.NonVirtual << " non-virtual";
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001885
1886 if (Adjustment.VCallOffsetOffset)
1887 Out << ", " << Adjustment.VCallOffsetOffset << " vcall offset offset";
1888
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001889 Out << ']';
1890
1891 NextThisAdjustmentIndex++;
1892 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001893
Anders Carlsson848fa642010-02-11 18:20:28 +00001894 break;
1895 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001896
Anders Carlsson6065e022010-02-19 06:03:53 +00001897 case VtableComponent::CK_CompleteDtorPointer:
Anders Carlsson848fa642010-02-11 18:20:28 +00001898 case VtableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6065e022010-02-19 06:03:53 +00001899 bool IsComplete =
1900 Component.getKind() == VtableComponent::CK_CompleteDtorPointer;
1901
Anders Carlsson848fa642010-02-11 18:20:28 +00001902 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1903
Anders Carlsson6065e022010-02-19 06:03:53 +00001904 Out << DD->getQualifiedNameAsString();
1905 if (IsComplete)
1906 Out << "() [complete]";
1907 else
1908 Out << "() [deleting]";
1909
Anders Carlsson98241422010-02-12 02:38:13 +00001910 if (DD->isPure())
1911 Out << " [pure]";
1912
Anders Carlsson6065e022010-02-19 06:03:53 +00001913 // If this destructor has a 'this' pointer adjustment, dump it.
1914 if (NextThisAdjustmentIndex < ThisAdjustments.size() &&
1915 ThisAdjustments[NextThisAdjustmentIndex].first == I) {
1916 const ThisAdjustment Adjustment =
1917 ThisAdjustments[NextThisAdjustmentIndex].second;
1918
1919 Out << "\n [this adjustment: ";
1920 Out << Adjustment.NonVirtual << " non-virtual";
1921
1922 if (Adjustment.VCallOffsetOffset)
1923 Out << ", " << Adjustment.VCallOffsetOffset << " vcall offset offset";
1924
1925 Out << ']';
1926
1927 NextThisAdjustmentIndex++;
1928 }
1929
1930
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001931 break;
1932 }
1933
Anders Carlsson1f464662010-02-19 20:08:13 +00001934 case VtableComponent::CK_UnusedFunctionPointer: {
1935 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1936
1937 std::string Str =
1938 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1939 MD);
1940 Out << "[unused] " << Str;
1941 if (MD->isPure())
1942 Out << " [pure]";
1943 }
1944
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001945 }
Anders Carlsson822307b2010-02-11 17:18:51 +00001946
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001947 Out << '\n';
1948 }
1949
1950}
1951
1952}
1953
1954namespace {
1955class OldVtableBuilder {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001956public:
1957 /// Index_t - Vtable index type.
1958 typedef uint64_t Index_t;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001959 typedef std::vector<std::pair<GlobalDecl,
1960 std::pair<GlobalDecl, ThunkAdjustment> > >
1961 SavedAdjustmentsVectorTy;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001962private:
Anders Carlsson15318f42009-12-04 16:19:30 +00001963
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001964 // VtableComponents - The components of the vtable being built.
1965 typedef llvm::SmallVector<llvm::Constant *, 64> VtableComponentsVectorTy;
1966 VtableComponentsVectorTy VtableComponents;
1967
Eli Friedman152b5b12009-12-05 01:05:03 +00001968 const bool BuildVtable;
1969
Anders Carlssondbd920c2009-10-11 22:13:54 +00001970 llvm::Type *Ptr8Ty;
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00001971
1972 /// MostDerivedClass - The most derived class that this vtable is being
1973 /// built for.
1974 const CXXRecordDecl *MostDerivedClass;
1975
Mike Stumpacfd1e52009-11-13 01:54:23 +00001976 /// LayoutClass - The most derived class used for virtual base layout
1977 /// information.
1978 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +00001979 /// LayoutOffset - The offset for Class in LayoutClass.
1980 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001981 /// BLayout - Layout for the most derived class that this vtable is being
1982 /// built for.
1983 const ASTRecordLayout &BLayout;
1984 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
1985 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
1986 llvm::Constant *rtti;
1987 llvm::LLVMContext &VMContext;
1988 CodeGenModule &CGM; // Per-module state.
Anders Carlsson0e881162009-12-04 03:46:21 +00001989
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001990 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
Anders Carlssona0fdd912009-11-13 17:08:56 +00001991 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpd99a4d22010-01-26 03:42:22 +00001992 llvm::DenseMap<GlobalDecl, Index_t> VCallOffsetForVCall;
Mike Stump9e7e3c62009-11-06 23:27:42 +00001993 // This is the offset to the nearest virtual base
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001994 llvm::DenseMap<const CXXMethodDecl *, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001995 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +00001996
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00001997 /// PureVirtualFunction - Points to __cxa_pure_virtual.
1998 llvm::Constant *PureVirtualFn;
1999
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002000 /// VtableMethods - A data structure for keeping track of methods in a vtable.
2001 /// Can add methods, override methods and iterate in vtable order.
2002 class VtableMethods {
2003 // MethodToIndexMap - Maps from a global decl to the index it has in the
2004 // Methods vector.
2005 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
2006
2007 /// Methods - The methods, in vtable order.
2008 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
2009 MethodsVectorTy Methods;
Eli Friedman72649ed2009-12-06 22:01:30 +00002010 MethodsVectorTy OrigMethods;
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002011
2012 public:
2013 /// AddMethod - Add a method to the vtable methods.
2014 void AddMethod(GlobalDecl GD) {
2015 assert(!MethodToIndexMap.count(GD) &&
2016 "Method has already been added!");
2017
2018 MethodToIndexMap[GD] = Methods.size();
2019 Methods.push_back(GD);
Eli Friedman72649ed2009-12-06 22:01:30 +00002020 OrigMethods.push_back(GD);
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002021 }
2022
2023 /// OverrideMethod - Replace a method with another.
2024 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
2025 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
2026 = MethodToIndexMap.find(OverriddenGD);
2027 assert(i != MethodToIndexMap.end() && "Did not find entry!");
2028
2029 // Get the index of the old decl.
2030 uint64_t Index = i->second;
2031
2032 // Replace the old decl with the new decl.
2033 Methods[Index] = GD;
2034
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002035 // And add the new.
2036 MethodToIndexMap[GD] = Index;
2037 }
2038
Anders Carlsson77c23e52009-12-04 15:49:02 +00002039 /// getIndex - Gives the index of a passed in GlobalDecl. Returns false if
2040 /// the index couldn't be found.
Benjamin Kramercce9fde2009-12-04 22:45:27 +00002041 bool getIndex(GlobalDecl GD, uint64_t &Index) const {
Anders Carlsson77c23e52009-12-04 15:49:02 +00002042 llvm::DenseMap<GlobalDecl, uint64_t>::const_iterator i
2043 = MethodToIndexMap.find(GD);
Eli Friedman47145832009-12-04 08:34:14 +00002044
Anders Carlsson77c23e52009-12-04 15:49:02 +00002045 if (i == MethodToIndexMap.end())
2046 return false;
Anders Carlssonc0c49932009-12-04 03:41:37 +00002047
Anders Carlsson77c23e52009-12-04 15:49:02 +00002048 Index = i->second;
2049 return true;
Anders Carlssonc0c49932009-12-04 03:41:37 +00002050 }
2051
Eli Friedman72649ed2009-12-06 22:01:30 +00002052 GlobalDecl getOrigMethod(uint64_t Index) const {
2053 return OrigMethods[Index];
2054 }
2055
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002056 MethodsVectorTy::size_type size() const {
2057 return Methods.size();
2058 }
2059
2060 void clear() {
2061 MethodToIndexMap.clear();
2062 Methods.clear();
Eli Friedman72649ed2009-12-06 22:01:30 +00002063 OrigMethods.clear();
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002064 }
2065
Anders Carlssonc0c49932009-12-04 03:41:37 +00002066 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002067 return Methods[Index];
2068 }
2069 };
2070
2071 /// Methods - The vtable methods we're currently building.
2072 VtableMethods Methods;
2073
Anders Carlsson98fdb242009-12-04 02:26:15 +00002074 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
2075 /// pointer adjustment needed for a method.
2076 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
2077 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlsson5dd730a2009-11-26 19:32:45 +00002078
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002079 SavedAdjustmentsVectorTy SavedAdjustments;
Eli Friedman72649ed2009-12-06 22:01:30 +00002080
Anders Carlssona8756702009-12-04 02:22:02 +00002081 /// BaseReturnTypes - Contains the base return types of methods who have been
2082 /// overridden with methods whose return types require adjustment. Used for
2083 /// generating covariant thunk information.
2084 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
2085 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlsson5dd730a2009-11-26 19:32:45 +00002086
Anders Carlssondbd920c2009-10-11 22:13:54 +00002087 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +00002088
2089 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +00002090 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
2091 // vtable for use in computing the initializers for the VTT.
2092 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +00002093
Anders Carlsson1bb60992010-01-14 02:29:07 +00002094 /// AddressPoints - Address points for this vtable.
2095 CGVtableInfo::AddressPointsMapTy& AddressPoints;
2096
Anders Carlssondbd920c2009-10-11 22:13:54 +00002097 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002098 const uint32_t LLVMPointerWidth;
2099 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +00002100 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +00002101 static llvm::DenseMap<CtorVtable_t, int64_t>&
2102 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
2103 const CXXRecordDecl *c) {
Anders Carlsson21431c52010-01-02 18:02:32 +00002104 CGVtableInfo::AddrMap_t *&oref = cgm.getVtableInfo().AddressPoints[l];
Mike Stump23a35422009-11-19 20:52:19 +00002105 if (oref == 0)
Anders Carlsson21431c52010-01-02 18:02:32 +00002106 oref = new CGVtableInfo::AddrMap_t;
Mike Stump23a35422009-11-19 20:52:19 +00002107
2108 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
2109 if (ref == 0)
2110 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
2111 return *ref;
2112 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00002113
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002114 bool DclIsSame(const FunctionDecl *New, const FunctionDecl *Old) {
2115 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
2116 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
2117
2118 // C++ [temp.fct]p2:
2119 // A function template can be overloaded with other function templates
2120 // and with normal (non-template) functions.
2121 if ((OldTemplate == 0) != (NewTemplate == 0))
2122 return false;
2123
2124 // Is the function New an overload of the function Old?
2125 QualType OldQType = CGM.getContext().getCanonicalType(Old->getType());
2126 QualType NewQType = CGM.getContext().getCanonicalType(New->getType());
2127
2128 // Compare the signatures (C++ 1.3.10) of the two functions to
2129 // determine whether they are overloads. If we find any mismatch
2130 // in the signature, they are overloads.
2131
2132 // If either of these functions is a K&R-style function (no
2133 // prototype), then we consider them to have matching signatures.
2134 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
2135 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
2136 return true;
2137
2138 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
2139 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
2140
2141 // The signature of a function includes the types of its
2142 // parameters (C++ 1.3.10), which includes the presence or absence
2143 // of the ellipsis; see C++ DR 357).
2144 if (OldQType != NewQType &&
2145 (OldType->getNumArgs() != NewType->getNumArgs() ||
2146 OldType->isVariadic() != NewType->isVariadic() ||
2147 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2148 NewType->arg_type_begin())))
2149 return false;
2150
2151#if 0
2152 // C++ [temp.over.link]p4:
2153 // The signature of a function template consists of its function
2154 // signature, its return type and its template parameter list. The names
2155 // of the template parameters are significant only for establishing the
2156 // relationship between the template parameters and the rest of the
2157 // signature.
2158 //
2159 // We check the return type and template parameter lists for function
2160 // templates first; the remaining checks follow.
2161 if (NewTemplate &&
2162 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
2163 OldTemplate->getTemplateParameters(),
2164 TPL_TemplateMatch) ||
2165 OldType->getResultType() != NewType->getResultType()))
2166 return false;
2167#endif
2168
2169 // If the function is a class member, its signature includes the
2170 // cv-qualifiers (if any) on the function itself.
2171 //
2172 // As part of this, also check whether one of the member functions
2173 // is static, in which case they are not overloads (C++
2174 // 13.1p2). While not part of the definition of the signature,
2175 // this check is important to determine whether these functions
2176 // can be overloaded.
2177 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2178 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2179 if (OldMethod && NewMethod &&
2180 !OldMethod->isStatic() && !NewMethod->isStatic() &&
2181 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
2182 return false;
2183
2184 // The signatures match; this is not an overload.
2185 return true;
2186 }
2187
2188 typedef llvm::DenseMap<const CXXMethodDecl *, const CXXMethodDecl*>
2189 ForwardUnique_t;
2190 ForwardUnique_t ForwardUnique;
2191 llvm::DenseMap<const CXXMethodDecl*, const CXXMethodDecl*> UniqueOverrider;
2192
2193 void BuildUniqueOverrider(const CXXMethodDecl *U, const CXXMethodDecl *MD) {
2194 const CXXMethodDecl *PrevU = UniqueOverrider[MD];
2195 assert(U && "no unique overrider");
2196 if (PrevU == U)
2197 return;
2198 if (PrevU != U && PrevU != 0) {
2199 // If already set, note the two sets as the same
2200 if (0)
2201 printf("%s::%s same as %s::%s\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002202 PrevU->getParent()->getNameAsString().c_str(),
2203 PrevU->getNameAsString().c_str(),
2204 U->getParent()->getNameAsString().c_str(),
2205 U->getNameAsString().c_str());
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002206 ForwardUnique[PrevU] = U;
2207 return;
2208 }
2209
2210 // Not set, set it now
2211 if (0)
2212 printf("marking %s::%s %p override as %s::%s\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002213 MD->getParent()->getNameAsString().c_str(),
2214 MD->getNameAsString().c_str(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002215 (void*)MD,
Douglas Gregoraef605d2010-02-22 16:44:27 +00002216 U->getParent()->getNameAsString().c_str(),
2217 U->getNameAsString().c_str());
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002218 UniqueOverrider[MD] = U;
2219
2220 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
2221 me = MD->end_overridden_methods(); mi != me; ++mi) {
2222 BuildUniqueOverrider(U, *mi);
2223 }
2224 }
2225
2226 void BuildUniqueOverriders(const CXXRecordDecl *RD) {
2227 if (0) printf("walking %s\n", RD->getNameAsCString());
2228 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2229 e = RD->method_end(); i != e; ++i) {
2230 const CXXMethodDecl *MD = *i;
2231 if (!MD->isVirtual())
2232 continue;
2233
2234 if (UniqueOverrider[MD] == 0) {
2235 // Only set this, if it hasn't been set yet.
2236 BuildUniqueOverrider(MD, MD);
2237 if (0)
2238 printf("top set is %s::%s %p\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002239 MD->getParent()->getNameAsString().c_str(),
2240 MD->getNameAsString().c_str(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002241 (void*)MD);
2242 ForwardUnique[MD] = MD;
2243 }
2244 }
2245 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2246 e = RD->bases_end(); i != e; ++i) {
2247 const CXXRecordDecl *Base =
2248 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2249 BuildUniqueOverriders(Base);
2250 }
2251 }
2252
2253 static int DclCmp(const void *p1, const void *p2) {
John McCall7fe0b9e2010-02-13 01:04:05 +00002254 const CXXMethodDecl *MD1 = *(const CXXMethodDecl *const *)p1;
2255 const CXXMethodDecl *MD2 = *(const CXXMethodDecl *const *)p2;
2256
2257 return (DeclarationName::compare(MD1->getDeclName(), MD2->getDeclName()));
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002258 }
2259
2260 void MergeForwarding() {
2261 typedef llvm::SmallVector<const CXXMethodDecl *, 100> A_t;
2262 A_t A;
2263 for (ForwardUnique_t::iterator I = ForwardUnique.begin(),
2264 E = ForwardUnique.end(); I != E; ++I) {
2265 if (I->first == I->second)
2266 // Only add the roots of all trees
2267 A.push_back(I->first);
2268 }
2269 llvm::array_pod_sort(A.begin(), A.end(), DclCmp);
2270 for (A_t::iterator I = A.begin(),
2271 E = A.end(); I != E; ++I) {
2272 A_t::iterator J = I;
John McCall7fe0b9e2010-02-13 01:04:05 +00002273 while (++J != E && DclCmp(I, J) == 0)
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002274 if (DclIsSame(*I, *J)) {
Douglas Gregoraef605d2010-02-22 16:44:27 +00002275 if (0) printf("connecting %s\n", (*I)->getNameAsString().c_str());
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002276 ForwardUnique[*J] = *I;
2277 }
2278 }
2279 }
2280
2281 const CXXMethodDecl *getUnique(const CXXMethodDecl *MD) {
2282 const CXXMethodDecl *U = UniqueOverrider[MD];
2283 assert(U && "unique overrider not found");
2284 while (ForwardUnique.count(U)) {
2285 const CXXMethodDecl *NU = ForwardUnique[U];
2286 if (NU == U) break;
2287 U = NU;
2288 }
2289 return U;
2290 }
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002291
2292 GlobalDecl getUnique(GlobalDecl GD) {
2293 const CXXMethodDecl *Unique = getUnique(cast<CXXMethodDecl>(GD.getDecl()));
2294
2295 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Unique))
2296 return GlobalDecl(CD, GD.getCtorType());
2297
2298 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Unique))
2299 return GlobalDecl(DD, GD.getDtorType());
2300
2301 return Unique;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002302 }
2303
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00002304 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
2305 llvm::Constant* getPureVirtualFn() {
2306 if (!PureVirtualFn) {
2307 const llvm::FunctionType *Ty =
2308 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
2309 /*isVarArg=*/false);
2310 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
2311 }
2312
2313 return PureVirtualFn;
2314 }
2315
Anders Carlssondbd920c2009-10-11 22:13:54 +00002316public:
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002317 OldVtableBuilder(const CXXRecordDecl *MostDerivedClass,
Eli Friedman152b5b12009-12-05 01:05:03 +00002318 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm,
Anders Carlsson1bb60992010-01-14 02:29:07 +00002319 bool build, CGVtableInfo::AddressPointsMapTy& AddressPoints)
Eli Friedman152b5b12009-12-05 01:05:03 +00002320 : BuildVtable(build), MostDerivedClass(MostDerivedClass), LayoutClass(l),
2321 LayoutOffset(lo), BLayout(cgm.getContext().getASTRecordLayout(l)),
2322 rtti(0), VMContext(cgm.getModule().getContext()),CGM(cgm),
2323 PureVirtualFn(0),
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00002324 subAddressPoints(AllocAddressPoint(cgm, l, MostDerivedClass)),
Anders Carlsson1bb60992010-01-14 02:29:07 +00002325 AddressPoints(AddressPoints),
2326 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0))
2327 {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002328 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00002329 if (BuildVtable) {
2330 QualType ClassType = CGM.getContext().getTagDeclType(MostDerivedClass);
2331 rtti = CGM.GetAddrOfRTTIDescriptor(ClassType);
2332 }
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002333 BuildUniqueOverriders(MostDerivedClass);
2334 MergeForwarding();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002335 }
2336
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002337 // getVtableComponents - Returns a reference to the vtable components.
2338 const VtableComponentsVectorTy &getVtableComponents() const {
2339 return VtableComponents;
Anders Carlsson15318f42009-12-04 16:19:30 +00002340 }
2341
Anders Carlssonc997d422010-01-02 01:01:18 +00002342 llvm::DenseMap<const CXXRecordDecl *, uint64_t> &getVBIndex()
Anders Carlssondbd920c2009-10-11 22:13:54 +00002343 { return VBIndex; }
2344
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002345 SavedAdjustmentsVectorTy &getSavedAdjustments()
2346 { return SavedAdjustments; }
Eli Friedman72649ed2009-12-06 22:01:30 +00002347
Anders Carlssondbd920c2009-10-11 22:13:54 +00002348 llvm::Constant *wrap(Index_t i) {
2349 llvm::Constant *m;
2350 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
2351 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
2352 }
2353
2354 llvm::Constant *wrap(llvm::Constant *m) {
2355 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
2356 }
2357
Mike Stumpd6584902010-01-22 02:51:26 +00002358//#define D1(x)
Douglas Gregor12a91092010-02-22 16:48:26 +00002359#define D1(X) do { if (getenv("CLANG_VTABLE_DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +00002360
2361 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +00002362 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002363 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2364 e = RD->bases_end(); i != e; ++i) {
2365 const CXXRecordDecl *Base =
2366 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +00002367 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002368 if (i->isVirtual() && !SeenVBase.count(Base)) {
2369 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +00002370 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +00002371 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +00002372 - 3*LLVMPointerWidth/8);
2373 VBIndex[Base] = next_vbindex;
2374 }
Mike Stump6a9612f2009-10-31 20:06:59 +00002375 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
2376 VCalls.push_back((0?700:0) + BaseOffset);
2377 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
2378 Base->getNameAsCString(),
2379 (int)-VCalls.size()-3, (int)BaseOffset,
Mike Stumpd6584902010-01-22 02:51:26 +00002380 MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002381 }
Mike Stumpab28c132009-10-13 22:54:56 +00002382 // We also record offsets for non-virtual bases to closest enclosing
2383 // virtual base. We do this so that we don't have to search
2384 // for the nearst virtual base class when generating thunks.
2385 if (updateVBIndex && VBIndex.count(Base) == 0)
2386 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +00002387 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002388 }
2389 }
2390
2391 void StartNewTable() {
2392 SeenVBase.clear();
2393 }
2394
Mike Stump3425b972009-10-15 09:30:16 +00002395 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
2396 Index_t Offset = 0) {
2397
2398 if (B == D)
2399 return Offset;
2400
2401 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
2402 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
2403 e = D->bases_end(); i != e; ++i) {
2404 const CXXRecordDecl *Base =
2405 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2406 int64_t BaseOffset = 0;
2407 if (!i->isVirtual())
2408 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2409 int64_t o = getNVOffset_1(Base, B, BaseOffset);
2410 if (o >= 0)
2411 return o;
2412 }
2413
2414 return -1;
2415 }
2416
2417 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
2418 /// derived class D.
2419 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +00002420 qD = qD->getPointeeType();
2421 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +00002422 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
2423 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
2424 int64_t o = getNVOffset_1(D, B);
2425 if (o >= 0)
2426 return o;
2427
2428 assert(false && "FIXME: non-virtual base not found");
2429 return 0;
2430 }
2431
Anders Carlssondbd920c2009-10-11 22:13:54 +00002432 /// getVbaseOffset - Returns the index into the vtable for the virtual base
2433 /// offset for the given (B) virtual base of the derived class D.
2434 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +00002435 qD = qD->getPointeeType();
2436 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002437 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
2438 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00002439 if (D != MostDerivedClass)
Eli Friedman76ed1f72009-11-30 01:19:33 +00002440 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002441 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
2442 i = VBIndex.find(B);
2443 if (i != VBIndex.end())
2444 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002445
Mike Stumpab28c132009-10-13 22:54:56 +00002446 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +00002447 return 0;
2448 }
2449
Eli Friedman367d1222009-12-04 08:40:51 +00002450 bool OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
2451 Index_t OverrideOffset, Index_t Offset,
2452 int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002453
Anders Carlssonadfa2672009-12-04 02:39:04 +00002454 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonbf540272009-12-04 02:56:03 +00002455 void AppendMethodsToVtable();
Anders Carlssonadfa2672009-12-04 02:39:04 +00002456
Anders Carlssona0fdd912009-11-13 17:08:56 +00002457 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
2458 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2459
Anders Carlssonecf282b2009-11-24 05:08:52 +00002460 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +00002461
Mike Stumpc085a982009-12-03 16:55:20 +00002462 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump1ae31782009-10-27 23:36:26 +00002463 }
2464
Mike Stump9e7e3c62009-11-06 23:27:42 +00002465 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
2466 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +00002467 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +00002468 e = Path->rend(); i != e; ++i) {
2469 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +00002470 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002471 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
2472 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00002473 const CXXMethodDecl *MD = *mi;
2474
2475 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +00002476 continue;
2477
Anders Carlssona0fdd912009-11-13 17:08:56 +00002478 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2479 // Override both the complete and the deleting destructor.
2480 GlobalDecl CompDtor(DD, Dtor_Complete);
Eli Friedman367d1222009-12-04 08:40:51 +00002481 OverrideMethod(CompDtor, MorallyVirtual, OverrideOffset, Offset,
2482 CurrentVBaseOffset);
2483
Anders Carlssona0fdd912009-11-13 17:08:56 +00002484 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
Eli Friedman367d1222009-12-04 08:40:51 +00002485 OverrideMethod(DeletingDtor, MorallyVirtual, OverrideOffset, Offset,
2486 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00002487 } else {
Eli Friedman367d1222009-12-04 08:40:51 +00002488 OverrideMethod(MD, MorallyVirtual, OverrideOffset, Offset,
2489 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00002490 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002491 }
2492 }
2493 }
2494
Anders Carlssona0fdd912009-11-13 17:08:56 +00002495 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002496 int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002497 // If we can find a previously allocated slot for this, reuse it.
Eli Friedman367d1222009-12-04 08:40:51 +00002498 if (OverrideMethod(GD, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002499 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +00002500 return;
2501
Mike Stump372ade22010-01-22 18:48:47 +00002502 D1(printf(" vfn for %s at %d\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002503 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsString().c_str(),
Mike Stump372ade22010-01-22 18:48:47 +00002504 (int)Methods.size()));
2505
Anders Carlssona7f19112009-12-04 02:08:24 +00002506 // We didn't find an entry in the vtable that we could use, add a new
2507 // entry.
2508 Methods.AddMethod(GD);
2509
Mike Stump15189fb2010-01-26 21:35:27 +00002510 VCallOffset[GD] = Offset/8 - CurrentVBaseOffset/8;
2511
Anders Carlssondbd920c2009-10-11 22:13:54 +00002512 if (MorallyVirtual) {
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002513 GlobalDecl UGD = getUnique(GD);
2514 const CXXMethodDecl *UMD = cast<CXXMethodDecl>(UGD.getDecl());
2515
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002516 assert(UMD && "final overrider not found");
2517
2518 Index_t &idx = VCall[UMD];
Anders Carlssondbd920c2009-10-11 22:13:54 +00002519 // Allocate the first one, after that, we reuse the previous one.
2520 if (idx == 0) {
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002521 VCallOffsetForVCall[UGD] = Offset/8;
Mike Stump15189fb2010-01-26 21:35:27 +00002522 NonVirtualOffset[UMD] = Offset/8 - CurrentVBaseOffset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002523 idx = VCalls.size()+1;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002524 VCalls.push_back(Offset/8 - CurrentVBaseOffset/8);
Mike Stump6a9612f2009-10-31 20:06:59 +00002525 D1(printf(" vcall for %s at %d with delta %d\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002526 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsString().c_str(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002527 (int)-VCalls.size()-3, (int)VCalls[idx-1]));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002528 }
2529 }
2530 }
2531
2532 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002533 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002534 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +00002535 ++mi) {
2536 const CXXMethodDecl *MD = *mi;
2537 if (!MD->isVirtual())
2538 continue;
2539
2540 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2541 // For destructors, add both the complete and the deleting destructor
2542 // to the vtable.
2543 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002544 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +00002545 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
2546 CurrentVBaseOffset);
2547 } else
2548 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00002549 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002550 }
2551
2552 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
2553 const CXXRecordDecl *PrimaryBase,
2554 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002555 int64_t Offset, int64_t CurrentVBaseOffset,
2556 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +00002557 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002558 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2559 e = RD->bases_end(); i != e; ++i) {
2560 if (i->isVirtual())
2561 continue;
2562 const CXXRecordDecl *Base =
2563 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002564 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
2565 StartNewTable();
2566 GenerateVtableForBase(Base, o, MorallyVirtual, false,
2567 true, Base == PrimaryBase && !PrimaryBaseWasVirtual,
2568 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002569 }
Mike Stump11dea942009-10-15 02:04:03 +00002570 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002571 }
2572
Mike Stump0ca42792009-10-14 18:14:51 +00002573// #define D(X) do { X; } while (0)
2574#define D(X)
2575
2576 void insertVCalls(int InsertionPoint) {
Mike Stump6a9612f2009-10-31 20:06:59 +00002577 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +00002578 D(VCalls.insert(VCalls.begin(), 673));
2579 D(VCalls.push_back(672));
Eli Friedman152b5b12009-12-05 01:05:03 +00002580
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002581 VtableComponents.insert(VtableComponents.begin() + InsertionPoint,
2582 VCalls.size(), 0);
Eli Friedman152b5b12009-12-05 01:05:03 +00002583 if (BuildVtable) {
2584 // The vcalls come first...
2585 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
2586 e = VCalls.rend();
2587 i != e; ++i)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002588 VtableComponents[InsertionPoint++] = wrap((0?600:0) + *i);
Eli Friedman152b5b12009-12-05 01:05:03 +00002589 }
Mike Stump0ca42792009-10-14 18:14:51 +00002590 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00002591 VCall.clear();
Mike Stump15189fb2010-01-26 21:35:27 +00002592 VCallOffsetForVCall.clear();
2593 VCallOffset.clear();
2594 NonVirtualOffset.clear();
Mike Stump0ca42792009-10-14 18:14:51 +00002595 }
2596
Mike Stump65d0e282009-11-13 23:13:20 +00002597 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
2598 Index_t AddressPoint) {
2599 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002600 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +00002601 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +00002602 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +00002603 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +00002604
2605 // Now also add the address point for all our primary bases.
2606 while (1) {
2607 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2608 RD = Layout.getPrimaryBase();
2609 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
2610 // FIXME: Double check this.
2611 if (RD == 0)
2612 break;
2613 if (PrimaryBaseWasVirtual &&
2614 BLayout.getVBaseClassOffset(RD) != Offset)
2615 break;
2616 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002617 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +00002618 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +00002619 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +00002620 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +00002621 }
2622 }
2623
2624
Mike Stump8cc4f102009-12-24 07:29:41 +00002625 void FinishGenerateVtable(const CXXRecordDecl *RD,
2626 const ASTRecordLayout &Layout,
2627 const CXXRecordDecl *PrimaryBase,
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002628 bool ForNPNVBases, bool WasPrimaryBase,
Mike Stump8cc4f102009-12-24 07:29:41 +00002629 bool PrimaryBaseWasVirtual,
2630 bool MorallyVirtual, int64_t Offset,
2631 bool ForVirtualBase, int64_t CurrentVBaseOffset,
2632 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +00002633 bool alloc = false;
2634 if (Path == 0) {
2635 alloc = true;
2636 Path = new Path_t;
2637 }
2638
Anders Carlssondbd920c2009-10-11 22:13:54 +00002639 StartNewTable();
2640 extra = 0;
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002641 Index_t AddressPoint = 0;
2642 int VCallInsertionPoint = 0;
2643 if (!ForNPNVBases || !WasPrimaryBase) {
2644 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
2645 VCallInsertionPoint = VtableComponents.size();
2646 if (!DeferVCalls) {
2647 insertVCalls(VCallInsertionPoint);
2648 } else
2649 // FIXME: just for extra, or for all uses of VCalls.size post this?
2650 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002651
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002652 // Add the offset to top.
2653 VtableComponents.push_back(BuildVtable ? wrap(-((Offset-LayoutOffset)/8)) : 0);
Anders Carlsson15318f42009-12-04 16:19:30 +00002654
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002655 // Add the RTTI information.
2656 VtableComponents.push_back(rtti);
Anders Carlsson15318f42009-12-04 16:19:30 +00002657
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002658 AddressPoint = VtableComponents.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002659
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002660 AppendMethodsToVtable();
2661 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002662
2663 // and then the non-virtual bases.
2664 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002665 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +00002666
2667 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +00002668 // FIXME: We're adding to VCalls in callers, we need to do the overrides
2669 // in the inner part, so that we know the complete set of vcalls during
2670 // the build and don't have to insert into methods. Saving out the
2671 // AddressPoint here, would need to be fixed, if we didn't do that. Also
2672 // retroactively adding vcalls for overrides later wind up in the wrong
2673 // place, the vcall slot has to be alloted during the walk of the base
2674 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +00002675 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +00002676 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +00002677 }
2678
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002679 if (!ForNPNVBases || !WasPrimaryBase)
2680 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +00002681
Mike Stump11dea942009-10-15 02:04:03 +00002682 if (alloc) {
2683 delete Path;
2684 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002685 }
2686
Mike Stump6a9612f2009-10-31 20:06:59 +00002687 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
2688 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002689 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +00002690 if (!RD->isDynamicClass())
2691 return;
2692
2693 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2694 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2695 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
2696
2697 // vtables are composed from the chain of primaries.
Eli Friedmandfe33bb2009-12-04 08:52:11 +00002698 if (PrimaryBase && !PrimaryBaseWasVirtual) {
Mike Stump6a9612f2009-10-31 20:06:59 +00002699 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002700 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Eli Friedmandfe33bb2009-12-04 08:52:11 +00002701 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
2702 updateVBIndex, current_vbindex, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00002703 }
2704
2705 D1(printf(" doing vcall entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002706 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00002707
2708 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +00002709 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00002710 }
2711
2712 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
2713 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002714 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002715 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002716 if (!RD->isDynamicClass())
2717 return;
2718
2719 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2720 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2721 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
2722
2723 // vtables are composed from the chain of primaries.
2724 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +00002725 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
2726 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002727 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +00002728 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
2729 }
Mike Stump6a9612f2009-10-31 20:06:59 +00002730
2731 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002732 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00002733
2734 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002735 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002736 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002737 }
2738
Mike Stump6a9612f2009-10-31 20:06:59 +00002739 D1(printf(" doing vbase entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002740 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00002741 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
2742
2743 if (RDisVirtualBase || bottom) {
2744 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002745 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00002746 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002747 }
2748
Mike Stump8cc4f102009-12-24 07:29:41 +00002749 void GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
2750 bool MorallyVirtual = false,
2751 bool ForVirtualBase = false,
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002752 bool ForNPNVBases = false,
2753 bool WasPrimaryBase = true,
Mike Stump8cc4f102009-12-24 07:29:41 +00002754 int CurrentVBaseOffset = 0,
2755 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002756 if (!RD->isDynamicClass())
Mike Stump8cc4f102009-12-24 07:29:41 +00002757 return;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002758
Mike Stump92774d12009-11-13 02:35:38 +00002759 // Construction vtable don't need parts that have no virtual bases and
2760 // aren't morally virtual.
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00002761 if ((LayoutClass != MostDerivedClass) &&
2762 RD->getNumVBases() == 0 && !MorallyVirtual)
Mike Stump8cc4f102009-12-24 07:29:41 +00002763 return;
Mike Stump92774d12009-11-13 02:35:38 +00002764
Anders Carlssondbd920c2009-10-11 22:13:54 +00002765 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2766 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2767 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
2768
Anders Carlssondbd920c2009-10-11 22:13:54 +00002769 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +00002770 D1(printf("building entries for base %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002771 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002772
Mike Stump6a9612f2009-10-31 20:06:59 +00002773 if (ForVirtualBase)
2774 extra = VCalls.size();
2775
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002776 if (!ForNPNVBases || !WasPrimaryBase) {
2777 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0,
2778 ForVirtualBase, CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002779
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002780 if (Path)
2781 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
2782 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002783
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002784 FinishGenerateVtable(RD, Layout, PrimaryBase, ForNPNVBases, WasPrimaryBase,
2785 PrimaryBaseWasVirtual, MorallyVirtual, Offset,
2786 ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002787 }
2788
2789 void GenerateVtableForVBases(const CXXRecordDecl *RD,
2790 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +00002791 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002792 bool alloc = false;
2793 if (Path == 0) {
2794 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +00002795 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002796 }
2797 // FIXME: We also need to override using all paths to a virtual base,
2798 // right now, we just process the first path
2799 Path->push_back(std::make_pair(RD, Offset));
2800 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2801 e = RD->bases_end(); i != e; ++i) {
2802 const CXXRecordDecl *Base =
2803 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2804 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
2805 // Mark it so we don't output it twice.
2806 IndirectPrimary.insert(Base);
2807 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +00002808 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002809 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +00002810 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +00002811 D1(printf("vtable %s virtual base %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00002812 MostDerivedClass->getNameAsCString(), Base->getNameAsCString()));
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002813 GenerateVtableForBase(Base, BaseOffset, true, true, false,
2814 true, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002815 }
Mike Stump9840c702009-11-12 20:47:57 +00002816 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002817 if (i->isVirtual())
2818 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +00002819 else {
2820 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2821 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2822 }
2823
Mike Stump11dea942009-10-15 02:04:03 +00002824 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002825 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +00002826 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002827 }
2828 Path->pop_back();
2829 if (alloc)
2830 delete Path;
2831 }
2832};
Anders Carlsson27682a32009-12-03 01:54:02 +00002833} // end anonymous namespace
2834
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002835bool OldVtableBuilder::OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
Eli Friedman367d1222009-12-04 08:40:51 +00002836 Index_t OverrideOffset, Index_t Offset,
2837 int64_t CurrentVBaseOffset) {
Anders Carlsson27682a32009-12-03 01:54:02 +00002838 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2839
2840 const bool isPure = MD->isPure();
Anders Carlsson7ca46432009-12-05 17:04:47 +00002841
Anders Carlsson27682a32009-12-03 01:54:02 +00002842 // FIXME: Should OverrideOffset's be Offset?
2843
Anders Carlsson7ca46432009-12-05 17:04:47 +00002844 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
2845 e = MD->end_overridden_methods(); mi != e; ++mi) {
Anders Carlsson27682a32009-12-03 01:54:02 +00002846 GlobalDecl OGD;
Mike Stump15189fb2010-01-26 21:35:27 +00002847 GlobalDecl OGD2;
Anders Carlsson27682a32009-12-03 01:54:02 +00002848
Anders Carlsson3aaf4862009-12-04 05:51:56 +00002849 const CXXMethodDecl *OMD = *mi;
Anders Carlsson27682a32009-12-03 01:54:02 +00002850 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
2851 OGD = GlobalDecl(DD, GD.getDtorType());
2852 else
2853 OGD = OMD;
Eli Friedman47145832009-12-04 08:34:14 +00002854
Eli Friedman72649ed2009-12-06 22:01:30 +00002855 // Check whether this is the method being overridden in this section of
2856 // the vtable.
Anders Carlsson77c23e52009-12-04 15:49:02 +00002857 uint64_t Index;
2858 if (!Methods.getIndex(OGD, Index))
Eli Friedman47145832009-12-04 08:34:14 +00002859 continue;
2860
Mike Stump15189fb2010-01-26 21:35:27 +00002861 OGD2 = OGD;
2862
Eli Friedman72649ed2009-12-06 22:01:30 +00002863 // Get the original method, which we should be computing thunks, etc,
2864 // against.
2865 OGD = Methods.getOrigMethod(Index);
2866 OMD = cast<CXXMethodDecl>(OGD.getDecl());
2867
Eli Friedman47145832009-12-04 08:34:14 +00002868 QualType ReturnType =
2869 MD->getType()->getAs<FunctionType>()->getResultType();
2870 QualType OverriddenReturnType =
2871 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlsson27682a32009-12-03 01:54:02 +00002872
Eli Friedman47145832009-12-04 08:34:14 +00002873 // Check if we need a return type adjustment.
Anders Carlssondf31af12010-02-13 23:17:31 +00002874 if (!ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
2875 OMD).isEmpty()) {
Eli Friedman47145832009-12-04 08:34:14 +00002876 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlsson27682a32009-12-03 01:54:02 +00002877
Eli Friedman47145832009-12-04 08:34:14 +00002878 // Insert the base return type.
2879 if (BaseReturnType.isNull())
2880 BaseReturnType =
2881 CGM.getContext().getCanonicalType(OverriddenReturnType);
2882 }
Anders Carlssondd454be2009-12-04 03:52:52 +00002883
Eli Friedman47145832009-12-04 08:34:14 +00002884 Methods.OverrideMethod(OGD, GD);
2885
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002886 GlobalDecl UGD = getUnique(GD);
2887 const CXXMethodDecl *UMD = cast<CXXMethodDecl>(UGD.getDecl());
2888 assert(UGD.getDecl() && "unique overrider not found");
2889 assert(UGD == getUnique(OGD) && "unique overrider not unique");
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002890
Eli Friedman47145832009-12-04 08:34:14 +00002891 ThisAdjustments.erase(Index);
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002892 if (MorallyVirtual || VCall.count(UMD)) {
Mike Stump15189fb2010-01-26 21:35:27 +00002893
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002894 Index_t &idx = VCall[UMD];
Eli Friedman47145832009-12-04 08:34:14 +00002895 if (idx == 0) {
Mike Stump15189fb2010-01-26 21:35:27 +00002896 VCallOffset[GD] = VCallOffset[OGD];
2897 // NonVirtualOffset[UMD] = CurrentVBaseOffset/8 - OverrideOffset/8;
2898 NonVirtualOffset[UMD] = VCallOffset[OGD];
Mike Stumpd99a4d22010-01-26 03:42:22 +00002899 VCallOffsetForVCall[UMD] = OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00002900 idx = VCalls.size()+1;
Mike Stumpd99a4d22010-01-26 03:42:22 +00002901 VCalls.push_back(OverrideOffset/8 - CurrentVBaseOffset/8);
Eli Friedman47145832009-12-04 08:34:14 +00002902 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
2903 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00002904 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00002905 } else {
Mike Stump15189fb2010-01-26 21:35:27 +00002906 VCallOffset[GD] = NonVirtualOffset[UMD];
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002907 VCalls[idx-1] = -VCallOffsetForVCall[UGD] + OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00002908 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
2909 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00002910 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00002911 }
Mike Stump15189fb2010-01-26 21:35:27 +00002912 int64_t NonVirtualAdjustment = -VCallOffset[OGD];
Mike Stump852f5ce2010-01-26 22:44:01 +00002913 QualType DerivedType = MD->getThisType(CGM.getContext());
2914 QualType BaseType = cast<const CXXMethodDecl>(OGD.getDecl())->getThisType(CGM.getContext());
2915 int64_t NonVirtualAdjustment2 = -(getNVOffset(BaseType, DerivedType)/8);
2916 if (NonVirtualAdjustment2 != NonVirtualAdjustment) {
2917 NonVirtualAdjustment = NonVirtualAdjustment2;
2918 }
Eli Friedman47145832009-12-04 08:34:14 +00002919 int64_t VirtualAdjustment =
2920 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson891bb4b2009-12-03 02:32:59 +00002921
Eli Friedman47145832009-12-04 08:34:14 +00002922 // Optimize out virtual adjustments of 0.
2923 if (VCalls[idx-1] == 0)
2924 VirtualAdjustment = 0;
Anders Carlsson891bb4b2009-12-03 02:32:59 +00002925
Eli Friedman47145832009-12-04 08:34:14 +00002926 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
2927 VirtualAdjustment);
Anders Carlssonbc0e3392009-12-03 02:22:59 +00002928
Eli Friedman72649ed2009-12-06 22:01:30 +00002929 if (!isPure && !ThisAdjustment.isEmpty()) {
Eli Friedman47145832009-12-04 08:34:14 +00002930 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002931 SavedAdjustments.push_back(
2932 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedman72649ed2009-12-06 22:01:30 +00002933 }
Anders Carlsson27682a32009-12-03 01:54:02 +00002934 return true;
2935 }
Eli Friedman47145832009-12-04 08:34:14 +00002936
Mike Stump15189fb2010-01-26 21:35:27 +00002937 VCallOffset[GD] = VCallOffset[OGD2] - OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00002938
Mike Stump15189fb2010-01-26 21:35:27 +00002939 int64_t NonVirtualAdjustment = -VCallOffset[GD];
2940 QualType DerivedType = MD->getThisType(CGM.getContext());
2941 QualType BaseType = cast<const CXXMethodDecl>(OGD.getDecl())->getThisType(CGM.getContext());
2942 int64_t NonVirtualAdjustment2 = -(getNVOffset(BaseType, DerivedType)/8);
2943 if (NonVirtualAdjustment2 != NonVirtualAdjustment) {
2944 NonVirtualAdjustment = NonVirtualAdjustment2;
2945 }
2946
Eli Friedman47145832009-12-04 08:34:14 +00002947 if (NonVirtualAdjustment) {
2948 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
2949
Eli Friedmanf062d9d2009-12-06 22:33:51 +00002950 if (!isPure) {
Eli Friedman47145832009-12-04 08:34:14 +00002951 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002952 SavedAdjustments.push_back(
2953 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedmanf062d9d2009-12-06 22:33:51 +00002954 }
Eli Friedman47145832009-12-04 08:34:14 +00002955 }
2956 return true;
Anders Carlsson27682a32009-12-03 01:54:02 +00002957 }
2958
2959 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +00002960}
2961
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002962void OldVtableBuilder::AppendMethodsToVtable() {
Eli Friedman152b5b12009-12-05 01:05:03 +00002963 if (!BuildVtable) {
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002964 VtableComponents.insert(VtableComponents.end(), Methods.size(),
2965 (llvm::Constant *)0);
Eli Friedman152b5b12009-12-05 01:05:03 +00002966 ThisAdjustments.clear();
2967 BaseReturnTypes.clear();
2968 Methods.clear();
2969 return;
2970 }
2971
Anders Carlsson15318f42009-12-04 16:19:30 +00002972 // Reserve room in the vtable for our new methods.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002973 VtableComponents.reserve(VtableComponents.size() + Methods.size());
Anders Carlsson29202d52009-12-04 03:07:26 +00002974
Anders Carlssonb73ba392009-12-04 02:43:50 +00002975 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
2976 GlobalDecl GD = Methods[i];
Anders Carlssonea357222009-12-04 02:52:22 +00002977 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2978
2979 // Get the 'this' pointer adjustment.
Anders Carlssonb73ba392009-12-04 02:43:50 +00002980 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlssonea357222009-12-04 02:52:22 +00002981
2982 // Construct the return type adjustment.
2983 ThunkAdjustment ReturnAdjustment;
2984
2985 QualType BaseReturnType = BaseReturnTypes.lookup(i);
2986 if (!BaseReturnType.isNull() && !MD->isPure()) {
2987 QualType DerivedType =
2988 MD->getType()->getAs<FunctionType>()->getResultType();
2989
2990 int64_t NonVirtualAdjustment =
2991 getNVOffset(BaseReturnType, DerivedType) / 8;
2992
2993 int64_t VirtualAdjustment =
2994 getVbaseOffset(BaseReturnType, DerivedType);
2995
2996 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
2997 VirtualAdjustment);
2998 }
2999
Anders Carlsson2fce2162009-12-04 03:06:03 +00003000 llvm::Constant *Method = 0;
Anders Carlssonea357222009-12-04 02:52:22 +00003001 if (!ReturnAdjustment.isEmpty()) {
3002 // Build a covariant thunk.
3003 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Eli Friedman72649ed2009-12-06 22:01:30 +00003004 Method = wrap(CGM.GetAddrOfCovariantThunk(GD, Adjustment));
Anders Carlssonea357222009-12-04 02:52:22 +00003005 } else if (!ThisAdjustment.isEmpty()) {
3006 // Build a "regular" thunk.
Eli Friedman72649ed2009-12-06 22:01:30 +00003007 Method = wrap(CGM.GetAddrOfThunk(GD, ThisAdjustment));
Anders Carlssonbf540272009-12-04 02:56:03 +00003008 } else if (MD->isPure()) {
3009 // We have a pure virtual method.
Anders Carlsson2fce2162009-12-04 03:06:03 +00003010 Method = getPureVirtualFn();
3011 } else {
3012 // We have a good old regular method.
3013 Method = WrapAddrOf(GD);
Anders Carlssonea357222009-12-04 02:52:22 +00003014 }
Anders Carlsson2fce2162009-12-04 03:06:03 +00003015
3016 // Add the method to the vtable.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003017 VtableComponents.push_back(Method);
Anders Carlssonb73ba392009-12-04 02:43:50 +00003018 }
3019
Anders Carlsson2fce2162009-12-04 03:06:03 +00003020
Anders Carlssonb73ba392009-12-04 02:43:50 +00003021 ThisAdjustments.clear();
Anders Carlssonea357222009-12-04 02:52:22 +00003022 BaseReturnTypes.clear();
Anders Carlssonb73ba392009-12-04 02:43:50 +00003023
Anders Carlssonadfa2672009-12-04 02:39:04 +00003024 Methods.clear();
Anders Carlssonadfa2672009-12-04 02:39:04 +00003025}
3026
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003027void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
3028
3029 // Itanium C++ ABI 2.5.2:
Anders Carlsson45147d02010-02-02 03:37:46 +00003030 // The order of the virtual function pointers in a virtual table is the
3031 // order of declaration of the corresponding member functions in the class.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003032 //
Anders Carlsson45147d02010-02-02 03:37:46 +00003033 // There is an entry for any virtual function declared in a class,
3034 // whether it is a new function or overrides a base class function,
3035 // unless it overrides a function from the primary base, and conversion
3036 // between their return types does not require an adjustment.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003037
3038 int64_t CurrentIndex = 0;
3039
3040 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3041 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3042
3043 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +00003044 assert(PrimaryBase->isDefinition() &&
3045 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003046
3047 // Since the record decl shares its vtable pointer with the primary base
3048 // we need to start counting at the end of the primary base's vtable.
3049 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
3050 }
Eli Friedmanea5ae312009-12-15 03:31:17 +00003051
3052 // Collect all the primary bases, so we can check whether methods override
3053 // a method from the base.
Anders Carlsson57071e22010-02-12 05:25:12 +00003054 VtableBuilder::PrimaryBasesSetTy PrimaryBases;
Eli Friedmanea5ae312009-12-15 03:31:17 +00003055 for (ASTRecordLayout::primary_base_info_iterator
3056 I = Layout.primary_base_begin(), E = Layout.primary_base_end();
3057 I != E; ++I)
3058 PrimaryBases.insert((*I).getBase());
3059
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003060 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
3061
3062 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
3063 e = RD->method_end(); i != e; ++i) {
3064 const CXXMethodDecl *MD = *i;
3065
3066 // We only want virtual methods.
3067 if (!MD->isVirtual())
3068 continue;
3069
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003070 // Check if this method overrides a method in the primary base.
Anders Carlsson57071e22010-02-12 05:25:12 +00003071 if (const CXXMethodDecl *OverriddenMD =
3072 OverridesMethodInPrimaryBase(MD, PrimaryBases)) {
3073 // Check if converting from the return type of the method to the
3074 // return type of the overridden method requires conversion.
Anders Carlssondf31af12010-02-13 23:17:31 +00003075 if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
3076 OverriddenMD).isEmpty()) {
Anders Carlsson57071e22010-02-12 05:25:12 +00003077 // This index is shared between the index in the vtable of the primary
3078 // base class.
3079 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3080 const CXXDestructorDecl *OverriddenDD =
3081 cast<CXXDestructorDecl>(OverriddenMD);
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003082
Anders Carlsson57071e22010-02-12 05:25:12 +00003083 // Add both the complete and deleting entries.
3084 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
3085 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
3086 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
3087 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
3088 } else {
3089 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
3090 }
3091
3092 // We don't need to add an entry for this method.
Anders Carlssonc1eec892010-02-12 18:14:46 +00003093 continue;
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003094 }
3095 }
3096
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003097 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3098 if (MD->isImplicit()) {
3099 assert(!ImplicitVirtualDtor &&
3100 "Did already see an implicit virtual dtor!");
3101 ImplicitVirtualDtor = DD;
3102 continue;
3103 }
3104
3105 // Add the complete dtor.
3106 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
3107
3108 // Add the deleting dtor.
3109 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
3110 } else {
3111 // Add the entry.
3112 MethodVtableIndices[MD] = CurrentIndex++;
3113 }
3114 }
3115
3116 if (ImplicitVirtualDtor) {
3117 // Itanium C++ ABI 2.5.2:
Anders Carlssona661a542010-02-16 04:49:44 +00003118 // If a class has an implicitly-defined virtual destructor,
3119 // its entries come after the declared virtual function pointers.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003120
3121 // Add the complete dtor.
3122 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
3123 CurrentIndex++;
3124
3125 // Add the deleting dtor.
3126 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
3127 CurrentIndex++;
3128 }
3129
3130 NumVirtualFunctionPointers[RD] = CurrentIndex;
3131}
3132
3133uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
3134 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
3135 NumVirtualFunctionPointers.find(RD);
3136 if (I != NumVirtualFunctionPointers.end())
3137 return I->second;
3138
3139 ComputeMethodVtableIndices(RD);
3140
3141 I = NumVirtualFunctionPointers.find(RD);
3142 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
3143 return I->second;
3144}
3145
3146uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00003147 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003148 if (I != MethodVtableIndices.end())
3149 return I->second;
3150
Anders Carlssona0fdd912009-11-13 17:08:56 +00003151 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003152
3153 ComputeMethodVtableIndices(RD);
3154
Anders Carlssona0fdd912009-11-13 17:08:56 +00003155 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003156 assert(I != MethodVtableIndices.end() && "Did not find index!");
3157 return I->second;
3158}
3159
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003160CGVtableInfo::AdjustmentVectorTy*
3161CGVtableInfo::getAdjustments(GlobalDecl GD) {
3162 SavedAdjustmentsTy::iterator I = SavedAdjustments.find(GD);
3163 if (I != SavedAdjustments.end())
3164 return &I->second;
Eli Friedman72649ed2009-12-06 22:01:30 +00003165
3166 const CXXRecordDecl *RD = cast<CXXRecordDecl>(GD.getDecl()->getDeclContext());
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003167 if (!SavedAdjustmentRecords.insert(RD).second)
3168 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00003169
Anders Carlsson1bb60992010-01-14 02:29:07 +00003170 AddressPointsMapTy AddressPoints;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003171 OldVtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Eli Friedman72649ed2009-12-06 22:01:30 +00003172 D1(printf("vtable %s\n", RD->getNameAsCString()));
3173 b.GenerateVtableForBase(RD);
3174 b.GenerateVtableForVBases(RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00003175
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003176 for (OldVtableBuilder::SavedAdjustmentsVectorTy::iterator
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003177 i = b.getSavedAdjustments().begin(),
3178 e = b.getSavedAdjustments().end(); i != e; i++)
3179 SavedAdjustments[i->first].push_back(i->second);
Eli Friedman72649ed2009-12-06 22:01:30 +00003180
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003181 I = SavedAdjustments.find(GD);
3182 if (I != SavedAdjustments.end())
3183 return &I->second;
3184
3185 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00003186}
3187
Anders Carlssondbd920c2009-10-11 22:13:54 +00003188int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
3189 const CXXRecordDecl *VBase) {
3190 ClassPairTy ClassPair(RD, VBase);
3191
3192 VirtualBaseClassIndiciesTy::iterator I =
3193 VirtualBaseClassIndicies.find(ClassPair);
3194 if (I != VirtualBaseClassIndicies.end())
3195 return I->second;
3196
Anders Carlssondbd920c2009-10-11 22:13:54 +00003197 // FIXME: This seems expensive. Can we do a partial job to get
3198 // just this data.
Anders Carlsson1bb60992010-01-14 02:29:07 +00003199 AddressPointsMapTy AddressPoints;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003200 OldVtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Mike Stump6a9612f2009-10-31 20:06:59 +00003201 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00003202 b.GenerateVtableForBase(RD);
3203 b.GenerateVtableForVBases(RD);
3204
3205 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
3206 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
3207 // Insert all types.
3208 ClassPairTy ClassPair(RD, I->first);
3209
3210 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
3211 }
3212
3213 I = VirtualBaseClassIndicies.find(ClassPair);
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00003214 // FIXME: The assertion below assertion currently fails with the old vtable
3215 /// layout code if there is a non-virtual thunk adjustment in a vtable.
3216 // Once the new layout is in place, this return should be removed.
3217 if (I == VirtualBaseClassIndicies.end())
3218 return 0;
3219
Anders Carlssondbd920c2009-10-11 22:13:54 +00003220 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
3221
3222 return I->second;
3223}
3224
Anders Carlsson9ac95b92009-12-05 21:03:56 +00003225uint64_t CGVtableInfo::getVtableAddressPoint(const CXXRecordDecl *RD) {
3226 uint64_t AddressPoint =
Anders Carlsson21431c52010-01-02 18:02:32 +00003227 (*(*(CGM.getVtableInfo().AddressPoints[RD]))[RD])[std::make_pair(RD, 0)];
Anders Carlsson9ac95b92009-12-05 21:03:56 +00003228
3229 return AddressPoint;
3230}
3231
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003232llvm::GlobalVariable *
Anders Carlsson35272252009-12-06 00:23:49 +00003233CGVtableInfo::GenerateVtable(llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson5794c972009-12-06 00:53:22 +00003234 bool GenerateDefinition,
Anders Carlsson35272252009-12-06 00:23:49 +00003235 const CXXRecordDecl *LayoutClass,
Anders Carlsson1bb60992010-01-14 02:29:07 +00003236 const CXXRecordDecl *RD, uint64_t Offset,
3237 AddressPointsMapTy& AddressPoints) {
Anders Carlssonc5874292010-02-14 00:22:59 +00003238 if (GenerateDefinition && CGM.getLangOptions().DumpVtableLayouts &&
3239 LayoutClass == RD) {
Anders Carlsson60db0ee2010-02-13 21:07:32 +00003240 VtableBuilder Builder(*this, RD);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +00003241
3242 Builder.dumpLayout(llvm::errs());
3243 }
3244
Anders Carlssondbd920c2009-10-11 22:13:54 +00003245 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00003246 if (LayoutClass != RD)
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003247 CGM.getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset / 8,
3248 RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00003249 else
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003250 CGM.getMangleContext().mangleCXXVtable(RD, OutName);
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00003251 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00003252
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003253 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
Anders Carlsson21431c52010-01-02 18:02:32 +00003254 if (GV == 0 || CGM.getVtableInfo().AddressPoints[LayoutClass] == 0 ||
3255 GV->isDeclaration()) {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003256 OldVtableBuilder b(RD, LayoutClass, Offset, CGM, GenerateDefinition,
3257 AddressPoints);
Eli Friedman152b5b12009-12-05 01:05:03 +00003258
3259 D1(printf("vtable %s\n", RD->getNameAsCString()));
3260 // First comes the vtables for all the non-virtual bases...
Mike Stump8cc4f102009-12-24 07:29:41 +00003261 b.GenerateVtableForBase(RD, Offset);
Eli Friedman152b5b12009-12-05 01:05:03 +00003262
3263 // then the vtables for all the virtual bases.
3264 b.GenerateVtableForVBases(RD, Offset);
3265
Anders Carlsson152d4dc2009-12-05 22:19:10 +00003266 llvm::Constant *Init = 0;
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003267 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson152d4dc2009-12-05 22:19:10 +00003268 llvm::ArrayType *ArrayType =
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003269 llvm::ArrayType::get(Int8PtrTy, b.getVtableComponents().size());
Anders Carlssone40477c2009-12-05 21:09:05 +00003270
Anders Carlsson5794c972009-12-06 00:53:22 +00003271 if (GenerateDefinition)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003272 Init = llvm::ConstantArray::get(ArrayType, &b.getVtableComponents()[0],
3273 b.getVtableComponents().size());
Anders Carlsson5794c972009-12-06 00:53:22 +00003274
Mike Stump85615df2009-11-19 04:04:36 +00003275 llvm::GlobalVariable *OGV = GV;
Anders Carlsson5794c972009-12-06 00:53:22 +00003276
3277 GV = new llvm::GlobalVariable(CGM.getModule(), ArrayType,
3278 /*isConstant=*/true, Linkage, Init, Name);
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003279 CGM.setGlobalVisibility(GV, RD);
3280
Mike Stump85615df2009-11-19 04:04:36 +00003281 if (OGV) {
3282 GV->takeName(OGV);
Anders Carlsson152d4dc2009-12-05 22:19:10 +00003283 llvm::Constant *NewPtr =
3284 llvm::ConstantExpr::getBitCast(GV, OGV->getType());
Mike Stump85615df2009-11-19 04:04:36 +00003285 OGV->replaceAllUsesWith(NewPtr);
3286 OGV->eraseFromParent();
3287 }
Mike Stump85615df2009-11-19 04:04:36 +00003288 }
Anders Carlssonbb27d862009-12-05 21:28:12 +00003289
3290 return GV;
Anders Carlssondbd920c2009-10-11 22:13:54 +00003291}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00003292
Anders Carlsson5794c972009-12-06 00:53:22 +00003293void CGVtableInfo::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
3294 const CXXRecordDecl *RD) {
Anders Carlssond58987c2009-12-07 07:59:52 +00003295 llvm::GlobalVariable *&Vtable = Vtables[RD];
3296 if (Vtable) {
3297 assert(Vtable->getInitializer() && "Vtable doesn't have a definition!");
3298 return;
3299 }
3300
Anders Carlsson1bb60992010-01-14 02:29:07 +00003301 AddressPointsMapTy AddressPoints;
3302 Vtable = GenerateVtable(Linkage, /*GenerateDefinition=*/true, RD, RD, 0,
3303 AddressPoints);
Anders Carlssonc997d422010-01-02 01:01:18 +00003304 GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
Mike Stump58588942009-11-19 01:08:19 +00003305}
3306
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003307llvm::GlobalVariable *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Anders Carlsson5794c972009-12-06 00:53:22 +00003308 llvm::GlobalVariable *Vtable = Vtables.lookup(RD);
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003309
Anders Carlsson1bb60992010-01-14 02:29:07 +00003310 if (!Vtable) {
3311 AddressPointsMapTy AddressPoints;
Anders Carlsson5794c972009-12-06 00:53:22 +00003312 Vtable = GenerateVtable(llvm::GlobalValue::ExternalLinkage,
Anders Carlsson1bb60992010-01-14 02:29:07 +00003313 /*GenerateDefinition=*/false, RD, RD, 0,
3314 AddressPoints);
3315 }
Mike Stump85615df2009-11-19 04:04:36 +00003316
Anders Carlsson224c3122009-12-05 22:42:54 +00003317 return Vtable;
Mike Stump380dd752009-11-10 07:44:33 +00003318}
Mike Stump8cfcb522009-11-11 20:26:26 +00003319
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003320void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
3321 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3322 const CXXRecordDecl *RD = MD->getParent();
3323
Anders Carlsson224c3122009-12-05 22:42:54 +00003324 // If the class doesn't have a vtable we don't need to emit one.
3325 if (!RD->isDynamicClass())
3326 return;
3327
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003328 // Get the key function.
Anders Carlssonf53df232009-12-07 04:35:11 +00003329 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003330
Anders Carlsson224c3122009-12-05 22:42:54 +00003331 if (KeyFunction) {
3332 // We don't have the right key function.
3333 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
3334 return;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003335 }
3336
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003337 // Emit the data.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00003338 GenerateClassData(CGM.getVtableLinkage(RD), RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00003339
3340 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
3341 e = RD->method_end(); i != e; ++i) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003342 if ((*i)->isVirtual() && ((*i)->hasInlineBody() || (*i)->isImplicit())) {
Eli Friedman72649ed2009-12-06 22:01:30 +00003343 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(*i)) {
3344 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Complete));
3345 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Deleting));
3346 } else {
3347 CGM.BuildThunksForVirtual(GlobalDecl(*i));
3348 }
3349 }
3350 }
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003351}
3352