blob: 40daadb824d22973164b78cfa6164d4acc99db9d [file] [log] [blame]
Anders Carlsson2bb27f52009-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 Carlssonf942ee02009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlssond420a312009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Zhongxing Xu1721ef72009-11-13 05:46:16 +000019#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000020
21using namespace clang;
22using namespace CodeGen;
23
Anders Carlssond59885022009-11-27 22:21:51 +000024namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000025class VtableBuilder {
Anders Carlsson2bb27f52009-10-11 22:13:54 +000026public:
27 /// Index_t - Vtable index type.
28 typedef uint64_t Index_t;
29private:
30 std::vector<llvm::Constant *> &methods;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000031 llvm::Type *Ptr8Ty;
32 /// Class - The most derived class that this vtable is being built for.
33 const CXXRecordDecl *Class;
Mike Stump83066c82009-11-13 01:54:23 +000034 /// LayoutClass - The most derived class used for virtual base layout
35 /// information.
36 const CXXRecordDecl *LayoutClass;
Mike Stump653d0b92009-11-13 02:13:54 +000037 /// LayoutOffset - The offset for Class in LayoutClass.
38 uint64_t LayoutOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000039 /// BLayout - Layout for the most derived class that this vtable is being
40 /// built for.
41 const ASTRecordLayout &BLayout;
42 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
43 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
44 llvm::Constant *rtti;
45 llvm::LLVMContext &VMContext;
46 CodeGenModule &CGM; // Per-module state.
Anders Carlssonf2f31f42009-12-04 03:46:21 +000047
Anders Carlssonfb4dda42009-11-13 17:08:56 +000048 llvm::DenseMap<GlobalDecl, Index_t> VCall;
49 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpcd6f9ed2009-11-06 23:27:42 +000050 // This is the offset to the nearest virtual base
Anders Carlssonfb4dda42009-11-13 17:08:56 +000051 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000052 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stumpbb9ff052009-10-27 23:46:47 +000053
Anders Carlsson323bb042009-11-26 19:54:33 +000054 /// PureVirtualFunction - Points to __cxa_pure_virtual.
55 llvm::Constant *PureVirtualFn;
56
Anders Carlssona84b6e82009-12-04 02:01:07 +000057 /// VtableMethods - A data structure for keeping track of methods in a vtable.
58 /// Can add methods, override methods and iterate in vtable order.
59 class VtableMethods {
60 // MethodToIndexMap - Maps from a global decl to the index it has in the
61 // Methods vector.
62 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
63
64 /// Methods - The methods, in vtable order.
65 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
66 MethodsVectorTy Methods;
67
68 public:
69 /// AddMethod - Add a method to the vtable methods.
70 void AddMethod(GlobalDecl GD) {
71 assert(!MethodToIndexMap.count(GD) &&
72 "Method has already been added!");
73
74 MethodToIndexMap[GD] = Methods.size();
75 Methods.push_back(GD);
76 }
77
78 /// OverrideMethod - Replace a method with another.
79 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
80 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
81 = MethodToIndexMap.find(OverriddenGD);
82 assert(i != MethodToIndexMap.end() && "Did not find entry!");
83
84 // Get the index of the old decl.
85 uint64_t Index = i->second;
86
87 // Replace the old decl with the new decl.
88 Methods[Index] = GD;
89
Anders Carlssona84b6e82009-12-04 02:01:07 +000090 // And add the new.
91 MethodToIndexMap[GD] = Index;
92 }
93
Eli Friedman3d2e9de2009-12-04 08:34:14 +000094 bool hasIndex(GlobalDecl GD) const {
95 return MethodToIndexMap.count(GD);
96 }
97
Anders Carlssone6096362009-12-04 03:41:37 +000098 /// getIndex - Returns the index of the given method.
99 uint64_t getIndex(GlobalDecl GD) const {
100 assert(MethodToIndexMap.count(GD) && "Did not find method!");
101
102 return MethodToIndexMap.lookup(GD);
103 }
104
Anders Carlssona84b6e82009-12-04 02:01:07 +0000105 MethodsVectorTy::size_type size() const {
106 return Methods.size();
107 }
108
109 void clear() {
110 MethodToIndexMap.clear();
111 Methods.clear();
112 }
113
Anders Carlssone6096362009-12-04 03:41:37 +0000114 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssona84b6e82009-12-04 02:01:07 +0000115 return Methods[Index];
116 }
117 };
118
119 /// Methods - The vtable methods we're currently building.
120 VtableMethods Methods;
121
Anders Carlsson4c837d22009-12-04 02:26:15 +0000122 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
123 /// pointer adjustment needed for a method.
124 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
125 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlssond420a312009-11-26 19:32:45 +0000126
Anders Carlssonc521f952009-12-04 02:22:02 +0000127 /// BaseReturnTypes - Contains the base return types of methods who have been
128 /// overridden with methods whose return types require adjustment. Used for
129 /// generating covariant thunk information.
130 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
131 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlssond420a312009-11-26 19:32:45 +0000132
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000133 std::vector<Index_t> VCalls;
Mike Stump2cefe382009-11-12 20:47:57 +0000134
135 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000136 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
137 // vtable for use in computing the initializers for the VTT.
138 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +0000139
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000140 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000141 const bool Extern;
142 const uint32_t LLVMPointerWidth;
143 Index_t extra;
Mike Stump37dbe962009-10-15 02:04:03 +0000144 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000145 static llvm::DenseMap<CtorVtable_t, int64_t>&
146 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
147 const CXXRecordDecl *c) {
148 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
149 if (oref == 0)
150 oref = new CodeGenModule::AddrMap_t;
151
152 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
153 if (ref == 0)
154 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
155 return *ref;
156 }
Anders Carlsson323bb042009-11-26 19:54:33 +0000157
158 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
159 llvm::Constant* getPureVirtualFn() {
160 if (!PureVirtualFn) {
161 const llvm::FunctionType *Ty =
162 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
163 /*isVarArg=*/false);
164 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
165 }
166
167 return PureVirtualFn;
168 }
169
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000170public:
Mike Stump653d0b92009-11-13 02:13:54 +0000171 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
172 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
173 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stump83066c82009-11-13 01:54:23 +0000174 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpc01c2b82009-12-02 18:57:08 +0000175 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000176 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump1960b202009-11-19 00:49:05 +0000177 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000178 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000179 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
180 }
181
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000182 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
183 { return VBIndex; }
184
185 llvm::Constant *wrap(Index_t i) {
186 llvm::Constant *m;
187 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
188 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
189 }
190
191 llvm::Constant *wrap(llvm::Constant *m) {
192 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
193 }
194
Mike Stump8a96d3a2009-12-02 19:50:41 +0000195#define D1(x)
196//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump75ce5732009-10-31 20:06:59 +0000197
198 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stump28431212009-10-13 22:54:56 +0000199 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000200 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
201 e = RD->bases_end(); i != e; ++i) {
202 const CXXRecordDecl *Base =
203 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump28431212009-10-13 22:54:56 +0000204 Index_t next_vbindex = current_vbindex;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000205 if (i->isVirtual() && !SeenVBase.count(Base)) {
206 SeenVBase.insert(Base);
Mike Stump28431212009-10-13 22:54:56 +0000207 if (updateVBIndex) {
Mike Stump75ce5732009-10-31 20:06:59 +0000208 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stump28431212009-10-13 22:54:56 +0000209 - 3*LLVMPointerWidth/8);
210 VBIndex[Base] = next_vbindex;
211 }
Mike Stump75ce5732009-10-31 20:06:59 +0000212 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
213 VCalls.push_back((0?700:0) + BaseOffset);
214 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
215 Base->getNameAsCString(),
216 (int)-VCalls.size()-3, (int)BaseOffset,
217 Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000218 }
Mike Stump28431212009-10-13 22:54:56 +0000219 // We also record offsets for non-virtual bases to closest enclosing
220 // virtual base. We do this so that we don't have to search
221 // for the nearst virtual base class when generating thunks.
222 if (updateVBIndex && VBIndex.count(Base) == 0)
223 VBIndex[Base] = next_vbindex;
Mike Stump75ce5732009-10-31 20:06:59 +0000224 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000225 }
226 }
227
228 void StartNewTable() {
229 SeenVBase.clear();
230 }
231
Mike Stump8bccbfd2009-10-15 09:30:16 +0000232 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
233 Index_t Offset = 0) {
234
235 if (B == D)
236 return Offset;
237
238 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
239 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
240 e = D->bases_end(); i != e; ++i) {
241 const CXXRecordDecl *Base =
242 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
243 int64_t BaseOffset = 0;
244 if (!i->isVirtual())
245 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
246 int64_t o = getNVOffset_1(Base, B, BaseOffset);
247 if (o >= 0)
248 return o;
249 }
250
251 return -1;
252 }
253
254 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
255 /// derived class D.
256 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000257 qD = qD->getPointeeType();
258 qB = qB->getPointeeType();
Mike Stump8bccbfd2009-10-15 09:30:16 +0000259 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
260 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
261 int64_t o = getNVOffset_1(D, B);
262 if (o >= 0)
263 return o;
264
265 assert(false && "FIXME: non-virtual base not found");
266 return 0;
267 }
268
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000269 /// getVbaseOffset - Returns the index into the vtable for the virtual base
270 /// offset for the given (B) virtual base of the derived class D.
271 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000272 qD = qD->getPointeeType();
273 qB = qB->getPointeeType();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000274 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
275 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
276 if (D != Class)
Eli Friedman03aa2f12009-11-30 01:19:33 +0000277 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000278 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
279 i = VBIndex.find(B);
280 if (i != VBIndex.end())
281 return i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000282
Mike Stump28431212009-10-13 22:54:56 +0000283 assert(false && "FIXME: Base not found");
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000284 return 0;
285 }
286
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000287 bool OverrideMethod(GlobalDecl GD, llvm::Constant *m,
Mike Stump8bccbfd2009-10-15 09:30:16 +0000288 bool MorallyVirtual, Index_t OverrideOffset,
Anders Carlssonca1bf682009-12-03 01:54:02 +0000289 Index_t Offset, int64_t CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000290
Anders Carlsson495634e2009-12-04 02:39:04 +0000291 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonddf42c82009-12-04 02:56:03 +0000292 void AppendMethodsToVtable();
Anders Carlsson495634e2009-12-04 02:39:04 +0000293
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000294 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
295 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
296
Anders Carlsson64457732009-11-24 05:08:52 +0000297 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump18e8b472009-10-27 23:36:26 +0000298
Mike Stumpcdeb8002009-12-03 16:55:20 +0000299 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump18e8b472009-10-27 23:36:26 +0000300 }
301
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000302 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
303 int64_t CurrentVBaseOffset) {
Mike Stump37dbe962009-10-15 02:04:03 +0000304 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000305 e = Path->rend(); i != e; ++i) {
306 const CXXRecordDecl *RD = i->first;
Mike Stump8bccbfd2009-10-15 09:30:16 +0000307 int64_t OverrideOffset = i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000308 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
309 ++mi) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000310 const CXXMethodDecl *MD = *mi;
311
312 if (!MD->isVirtual())
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000313 continue;
314
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000315 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
316 // Override both the complete and the deleting destructor.
317 GlobalDecl CompDtor(DD, Dtor_Complete);
318 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
319 OverrideOffset, Offset, CurrentVBaseOffset);
320
321 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
322 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
323 OverrideOffset, Offset, CurrentVBaseOffset);
324 } else {
325 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
326 Offset, CurrentVBaseOffset);
327 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000328 }
329 }
330 }
331
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000332 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000333 int64_t CurrentVBaseOffset) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000334 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump18e8b472009-10-27 23:36:26 +0000335
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000336 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000337 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000338 CurrentVBaseOffset))
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000339 return;
340
Anders Carlssoncdf18982009-12-04 02:08:24 +0000341 // We didn't find an entry in the vtable that we could use, add a new
342 // entry.
343 Methods.AddMethod(GD);
344
Mike Stumpc5a332c2009-11-13 23:45:53 +0000345 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
346 (int)Index[GD]));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000347 if (MorallyVirtual) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000348 VCallOffset[GD] = Offset/8;
349 Index_t &idx = VCall[GD];
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000350 // Allocate the first one, after that, we reuse the previous one.
351 if (idx == 0) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000352 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000353 idx = VCalls.size()+1;
354 VCalls.push_back(0);
Mike Stump75ce5732009-10-31 20:06:59 +0000355 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpc5a332c2009-11-13 23:45:53 +0000356 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000357 }
358 }
359 }
360
361 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000362 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000363 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000364 ++mi) {
365 const CXXMethodDecl *MD = *mi;
366 if (!MD->isVirtual())
367 continue;
368
369 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
370 // For destructors, add both the complete and the deleting destructor
371 // to the vtable.
372 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000373 CurrentVBaseOffset);
Eli Friedman03aa2f12009-11-30 01:19:33 +0000374 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
375 CurrentVBaseOffset);
376 } else
377 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000378 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000379 }
380
381 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
382 const CXXRecordDecl *PrimaryBase,
383 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000384 int64_t Offset, int64_t CurrentVBaseOffset,
385 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000386 Path->push_back(std::make_pair(RD, Offset));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000387 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
388 e = RD->bases_end(); i != e; ++i) {
389 if (i->isVirtual())
390 continue;
391 const CXXRecordDecl *Base =
392 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
393 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
394 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
395 StartNewTable();
Mike Stump653d0b92009-11-13 02:13:54 +0000396 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000397 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000398 }
399 }
Mike Stump37dbe962009-10-15 02:04:03 +0000400 Path->pop_back();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000401 }
402
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000403// #define D(X) do { X; } while (0)
404#define D(X)
405
406 void insertVCalls(int InsertionPoint) {
407 llvm::Constant *e = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000408 D1(printf("============= combining vbase/vcall\n"));
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000409 D(VCalls.insert(VCalls.begin(), 673));
410 D(VCalls.push_back(672));
Mike Stump8bccbfd2009-10-15 09:30:16 +0000411 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000412 // The vcalls come first...
413 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
414 e = VCalls.rend();
415 i != e; ++i)
416 methods[InsertionPoint++] = wrap((0?600:0) + *i);
417 VCalls.clear();
Mike Stump9f23a142009-11-10 02:30:51 +0000418 VCall.clear();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000419 }
420
Mike Stump559387f2009-11-13 23:13:20 +0000421 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
422 Index_t AddressPoint) {
423 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
424 RD->getNameAsCString(), Class->getNameAsCString(),
425 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000426 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000427
428 // Now also add the address point for all our primary bases.
429 while (1) {
430 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
431 RD = Layout.getPrimaryBase();
432 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
433 // FIXME: Double check this.
434 if (RD == 0)
435 break;
436 if (PrimaryBaseWasVirtual &&
437 BLayout.getVBaseClassOffset(RD) != Offset)
438 break;
439 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
440 RD->getNameAsCString(), Class->getNameAsCString(),
441 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000442 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000443 }
444 }
445
446
Eli Friedmanb05eb962009-12-04 03:54:56 +0000447 Index_t FinishGenerateVtable(const CXXRecordDecl *RD,
448 const ASTRecordLayout &Layout,
449 const CXXRecordDecl *PrimaryBase,
450 bool PrimaryBaseWasVirtual,
451 bool MorallyVirtual, int64_t Offset,
452 bool ForVirtualBase, int64_t CurrentVBaseOffset,
453 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000454 bool alloc = false;
455 if (Path == 0) {
456 alloc = true;
457 Path = new Path_t;
458 }
459
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000460 StartNewTable();
461 extra = 0;
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000462 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
463 int VCallInsertionPoint = methods.size();
464 if (!DeferVCalls) {
465 insertVCalls(VCallInsertionPoint);
Mike Stump8bccbfd2009-10-15 09:30:16 +0000466 } else
467 // FIXME: just for extra, or for all uses of VCalls.size post this?
468 extra = -VCalls.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000469
Mike Stump653d0b92009-11-13 02:13:54 +0000470 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000471 methods.push_back(rtti);
472 Index_t AddressPoint = methods.size();
473
Anders Carlssonddf42c82009-12-04 02:56:03 +0000474 AppendMethodsToVtable();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000475
476 // and then the non-virtual bases.
477 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000478 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000479
480 if (ForVirtualBase) {
Mike Stump2cefe382009-11-12 20:47:57 +0000481 // FIXME: We're adding to VCalls in callers, we need to do the overrides
482 // in the inner part, so that we know the complete set of vcalls during
483 // the build and don't have to insert into methods. Saving out the
484 // AddressPoint here, would need to be fixed, if we didn't do that. Also
485 // retroactively adding vcalls for overrides later wind up in the wrong
486 // place, the vcall slot has to be alloted during the walk of the base
487 // when the function is first introduces.
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000488 AddressPoint += VCalls.size();
Mike Stump2cefe382009-11-12 20:47:57 +0000489 insertVCalls(VCallInsertionPoint);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000490 }
491
Mike Stump559387f2009-11-13 23:13:20 +0000492 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump2cefe382009-11-12 20:47:57 +0000493
Mike Stump37dbe962009-10-15 02:04:03 +0000494 if (alloc) {
495 delete Path;
496 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000497 return AddressPoint;
498 }
499
Mike Stump75ce5732009-10-31 20:06:59 +0000500 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
501 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000502 int64_t CurrentVBaseOffset) {
Mike Stump75ce5732009-10-31 20:06:59 +0000503 if (!RD->isDynamicClass())
504 return;
505
506 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
507 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
508 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
509
510 // vtables are composed from the chain of primaries.
511 if (PrimaryBase) {
512 D1(printf(" doing primaries for %s most derived %s\n",
513 RD->getNameAsCString(), Class->getNameAsCString()));
514
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000515 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
516 if (PrimaryBaseWasVirtual)
517 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
518
Mike Stump75ce5732009-10-31 20:06:59 +0000519 if (!PrimaryBaseWasVirtual)
520 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000521 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000522 }
523
524 D1(printf(" doing vcall entries for %s most derived %s\n",
525 RD->getNameAsCString(), Class->getNameAsCString()));
526
527 // And add the virtuals for the class to the primary vtable.
Eli Friedman03aa2f12009-11-30 01:19:33 +0000528 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000529 }
530
531 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
532 bool updateVBIndex, Index_t current_vbindex,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000533 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000534 bool bottom) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000535 if (!RD->isDynamicClass())
536 return;
537
538 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
539 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
540 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
541
542 // vtables are composed from the chain of primaries.
543 if (PrimaryBase) {
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000544 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
545 if (PrimaryBaseWasVirtual) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000546 IndirectPrimary.insert(PrimaryBase);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000547 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
548 }
Mike Stump75ce5732009-10-31 20:06:59 +0000549
550 D1(printf(" doing primaries for %s most derived %s\n",
551 RD->getNameAsCString(), Class->getNameAsCString()));
552
553 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000554 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000555 BaseCurrentVBaseOffset, false);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000556 }
557
Mike Stump75ce5732009-10-31 20:06:59 +0000558 D1(printf(" doing vbase entries for %s most derived %s\n",
559 RD->getNameAsCString(), Class->getNameAsCString()));
560 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
561
562 if (RDisVirtualBase || bottom) {
563 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000564 CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000565 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000566 }
567
Mike Stump653d0b92009-11-13 02:13:54 +0000568 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
569 bool MorallyVirtual = false,
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000570 bool ForVirtualBase = false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000571 int CurrentVBaseOffset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000572 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000573 if (!RD->isDynamicClass())
574 return 0;
575
Mike Stumpfa818082009-11-13 02:35:38 +0000576 // Construction vtable don't need parts that have no virtual bases and
577 // aren't morally virtual.
578 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
579 return 0;
580
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000581 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
582 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
583 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
584
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000585 extra = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000586 D1(printf("building entries for base %s most derived %s\n",
587 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000588
Mike Stump75ce5732009-10-31 20:06:59 +0000589 if (ForVirtualBase)
590 extra = VCalls.size();
591
592 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000593 CurrentVBaseOffset, true);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000594
595 if (Path)
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000596 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000597
Eli Friedmanb05eb962009-12-04 03:54:56 +0000598 return FinishGenerateVtable(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
599 MorallyVirtual, Offset, ForVirtualBase,
600 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000601 }
602
603 void GenerateVtableForVBases(const CXXRecordDecl *RD,
604 int64_t Offset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000605 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000606 bool alloc = false;
607 if (Path == 0) {
608 alloc = true;
Mike Stump37dbe962009-10-15 02:04:03 +0000609 Path = new Path_t;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000610 }
611 // FIXME: We also need to override using all paths to a virtual base,
612 // right now, we just process the first path
613 Path->push_back(std::make_pair(RD, Offset));
614 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
615 e = RD->bases_end(); i != e; ++i) {
616 const CXXRecordDecl *Base =
617 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
618 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
619 // Mark it so we don't output it twice.
620 IndirectPrimary.insert(Base);
621 StartNewTable();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000622 VCall.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000623 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000624 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump75ce5732009-10-31 20:06:59 +0000625 D1(printf("vtable %s virtual base %s\n",
626 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump653d0b92009-11-13 02:13:54 +0000627 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000628 Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000629 }
Mike Stump2cefe382009-11-12 20:47:57 +0000630 int64_t BaseOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000631 if (i->isVirtual())
632 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2cefe382009-11-12 20:47:57 +0000633 else {
634 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
635 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
636 }
637
Mike Stump37dbe962009-10-15 02:04:03 +0000638 if (Base->getNumVBases()) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000639 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump37dbe962009-10-15 02:04:03 +0000640 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000641 }
642 Path->pop_back();
643 if (alloc)
644 delete Path;
645 }
646};
Anders Carlssonca1bf682009-12-03 01:54:02 +0000647} // end anonymous namespace
648
Anders Carlsson657f1392009-12-03 02:32:59 +0000649/// TypeConversionRequiresAdjustment - Returns whether conversion from a
650/// derived type to a base type requires adjustment.
651static bool
652TypeConversionRequiresAdjustment(ASTContext &Ctx,
653 const CXXRecordDecl *DerivedDecl,
654 const CXXRecordDecl *BaseDecl) {
655 CXXBasePaths Paths(/*FindAmbiguities=*/false,
656 /*RecordPaths=*/true, /*DetectVirtual=*/true);
657 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
658 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
659 assert(false && "Class must be derived from the passed in base class!");
660 return false;
661 }
662
663 // If we found a virtual base we always want to require adjustment.
664 if (Paths.getDetectedVirtual())
665 return true;
666
667 const CXXBasePath &Path = Paths.front();
668
669 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
670 const CXXBasePathElement &Element = Path[Start];
671
672 // Check the base class offset.
673 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
674
675 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
676 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
677
678 if (Layout.getBaseClassOffset(Base) != 0) {
679 // This requires an adjustment.
680 return true;
681 }
682 }
683
684 return false;
685}
686
687static bool
688TypeConversionRequiresAdjustment(ASTContext &Ctx,
689 QualType DerivedType, QualType BaseType) {
690 // Canonicalize the types.
691 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
692 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
693
694 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
695 "Types must have same type class!");
696
697 if (CanDerivedType == CanBaseType) {
698 // No adjustment needed.
699 return false;
700 }
701
702 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
703 CanDerivedType = RT->getPointeeType();
704 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
705 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
706 CanDerivedType = PT->getPointeeType();
707 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
708 } else {
709 assert(false && "Unexpected return type!");
710 }
711
712 if (CanDerivedType == CanBaseType) {
713 // No adjustment needed.
714 return false;
715 }
716
717 const CXXRecordDecl *DerivedDecl =
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000718 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson657f1392009-12-03 02:32:59 +0000719
720 const CXXRecordDecl *BaseDecl =
721 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
722
723 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
724}
725
Anders Carlssonca1bf682009-12-03 01:54:02 +0000726bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
727 bool MorallyVirtual, Index_t OverrideOffset,
728 Index_t Offset, int64_t CurrentVBaseOffset) {
729 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
730
731 const bool isPure = MD->isPure();
732 typedef CXXMethodDecl::method_iterator meth_iter;
733 // FIXME: Should OverrideOffset's be Offset?
734
735 // FIXME: Don't like the nested loops. For very large inheritance
736 // heirarchies we could have a table on the side with the final overridder
737 // and just replace each instance of an overridden method once. Would be
738 // nice to measure the cost/benefit on real code.
739
740 for (meth_iter mi = MD->begin_overridden_methods(),
741 e = MD->end_overridden_methods();
742 mi != e; ++mi) {
743 GlobalDecl OGD;
744
Anders Carlssonf3935b42009-12-04 05:51:56 +0000745 const CXXMethodDecl *OMD = *mi;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000746 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
747 OGD = GlobalDecl(DD, GD.getDtorType());
748 else
749 OGD = OMD;
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000750
751 // FIXME: Explain why this is necessary!
752 if (!Methods.hasIndex(OGD))
753 continue;
754
755 uint64_t Index = Methods.getIndex(OGD);
756
757 QualType ReturnType =
758 MD->getType()->getAs<FunctionType>()->getResultType();
759 QualType OverriddenReturnType =
760 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonca1bf682009-12-03 01:54:02 +0000761
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000762 // Check if we need a return type adjustment.
763 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
764 OverriddenReturnType)) {
765 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlssonca1bf682009-12-03 01:54:02 +0000766
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000767 // Get the canonical return type.
768 CanQualType CanReturnType =
769 CGM.getContext().getCanonicalType(ReturnType);
Anders Carlssone6096362009-12-04 03:41:37 +0000770
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000771 // Insert the base return type.
772 if (BaseReturnType.isNull())
773 BaseReturnType =
774 CGM.getContext().getCanonicalType(OverriddenReturnType);
775 }
Anders Carlssona93e9802009-12-04 03:52:52 +0000776
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000777 Methods.OverrideMethod(OGD, GD);
778
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000779 ThisAdjustments.erase(Index);
780 if (MorallyVirtual || VCall.count(OGD)) {
781 Index_t &idx = VCall[OGD];
782 if (idx == 0) {
783 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
784 VCallOffset[GD] = OverrideOffset/8;
785 idx = VCalls.size()+1;
786 VCalls.push_back(0);
787 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
788 MD->getNameAsString().c_str(), (int)-idx-3,
789 (int)VCalls[idx-1], Class->getNameAsCString()));
790 } else {
791 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
792 VCallOffset[GD] = VCallOffset[OGD];
793 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
794 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
795 MD->getNameAsString().c_str(), (int)-idx-3,
796 (int)VCalls[idx-1], Class->getNameAsCString()));
797 }
798 VCall[GD] = idx;
799 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
800 int64_t VirtualAdjustment =
801 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson657f1392009-12-03 02:32:59 +0000802
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000803 // Optimize out virtual adjustments of 0.
804 if (VCalls[idx-1] == 0)
805 VirtualAdjustment = 0;
Anders Carlsson657f1392009-12-03 02:32:59 +0000806
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000807 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
808 VirtualAdjustment);
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000809
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000810 if (!isPure && !ThisAdjustment.isEmpty())
811 ThisAdjustments[Index] = ThisAdjustment;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000812 return true;
813 }
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000814
815 // FIXME: finish off
816 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
817
818 if (NonVirtualAdjustment) {
819 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
820
821 if (!isPure)
822 ThisAdjustments[Index] = ThisAdjustment;
823 }
824 return true;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000825 }
826
827 return false;
Anders Carlssond59885022009-11-27 22:21:51 +0000828}
829
Anders Carlssonddf42c82009-12-04 02:56:03 +0000830void VtableBuilder::AppendMethodsToVtable() {
Anders Carlssonb07567c2009-12-04 03:07:26 +0000831 // Reserve room for our new methods.
832 methods.reserve(methods.size() + Methods.size());
833
Anders Carlsson86809cd2009-12-04 02:43:50 +0000834 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
835 GlobalDecl GD = Methods[i];
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000836 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
837
838 // Get the 'this' pointer adjustment.
Anders Carlsson86809cd2009-12-04 02:43:50 +0000839 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000840
841 // Construct the return type adjustment.
842 ThunkAdjustment ReturnAdjustment;
843
844 QualType BaseReturnType = BaseReturnTypes.lookup(i);
845 if (!BaseReturnType.isNull() && !MD->isPure()) {
846 QualType DerivedType =
847 MD->getType()->getAs<FunctionType>()->getResultType();
848
849 int64_t NonVirtualAdjustment =
850 getNVOffset(BaseReturnType, DerivedType) / 8;
851
852 int64_t VirtualAdjustment =
853 getVbaseOffset(BaseReturnType, DerivedType);
854
855 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
856 VirtualAdjustment);
857 }
858
Anders Carlsson50f14742009-12-04 03:06:03 +0000859 llvm::Constant *Method = 0;
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000860 if (!ReturnAdjustment.isEmpty()) {
861 // Build a covariant thunk.
862 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson50f14742009-12-04 03:06:03 +0000863 Method = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000864 } else if (!ThisAdjustment.isEmpty()) {
865 // Build a "regular" thunk.
Anders Carlsson50f14742009-12-04 03:06:03 +0000866 Method = CGM.BuildThunk(GD, Extern, ThisAdjustment);
Anders Carlssonddf42c82009-12-04 02:56:03 +0000867 } else if (MD->isPure()) {
868 // We have a pure virtual method.
Anders Carlsson50f14742009-12-04 03:06:03 +0000869 Method = getPureVirtualFn();
870 } else {
871 // We have a good old regular method.
872 Method = WrapAddrOf(GD);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000873 }
Anders Carlsson50f14742009-12-04 03:06:03 +0000874
875 // Add the method to the vtable.
876 methods.push_back(Method);
Anders Carlsson86809cd2009-12-04 02:43:50 +0000877 }
878
Anders Carlsson50f14742009-12-04 03:06:03 +0000879
Anders Carlsson86809cd2009-12-04 02:43:50 +0000880 ThisAdjustments.clear();
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000881 BaseReturnTypes.clear();
Anders Carlsson86809cd2009-12-04 02:43:50 +0000882
Anders Carlsson495634e2009-12-04 02:39:04 +0000883 Methods.clear();
Anders Carlsson495634e2009-12-04 02:39:04 +0000884}
885
Anders Carlssonf942ee02009-11-27 20:47:55 +0000886void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
887
888 // Itanium C++ ABI 2.5.2:
889 // The order of the virtual function pointers in a virtual table is the
890 // order of declaration of the corresponding member functions in the class.
891 //
892 // There is an entry for any virtual function declared in a class,
893 // whether it is a new function or overrides a base class function,
894 // unless it overrides a function from the primary base, and conversion
895 // between their return types does not require an adjustment.
896
897 int64_t CurrentIndex = 0;
898
899 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
900 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
901
902 if (PrimaryBase) {
Anders Carlssonc920fa22009-11-30 19:43:26 +0000903 assert(PrimaryBase->isDefinition() &&
904 "Should have the definition decl of the primary base!");
Anders Carlssonf942ee02009-11-27 20:47:55 +0000905
906 // Since the record decl shares its vtable pointer with the primary base
907 // we need to start counting at the end of the primary base's vtable.
908 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
909 }
910
911 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
912
913 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
914 e = RD->method_end(); i != e; ++i) {
915 const CXXMethodDecl *MD = *i;
916
917 // We only want virtual methods.
918 if (!MD->isVirtual())
919 continue;
920
921 bool ShouldAddEntryForMethod = true;
922
923 // Check if this method overrides a method in the primary base.
924 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
925 e = MD->end_overridden_methods(); i != e; ++i) {
Anders Carlssonf3935b42009-12-04 05:51:56 +0000926 const CXXMethodDecl *OverriddenMD = *i;
Anders Carlssonf942ee02009-11-27 20:47:55 +0000927 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
928 assert(OverriddenMD->isCanonicalDecl() &&
929 "Should have the canonical decl of the overridden RD!");
930
931 if (OverriddenRD == PrimaryBase) {
932 // Check if converting from the return type of the method to the
933 // return type of the overridden method requires conversion.
934 QualType ReturnType =
935 MD->getType()->getAs<FunctionType>()->getResultType();
936 QualType OverriddenReturnType =
937 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
938
939 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
940 ReturnType, OverriddenReturnType)) {
941 // This index is shared between the index in the vtable of the primary
942 // base class.
943 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
944 const CXXDestructorDecl *OverriddenDD =
945 cast<CXXDestructorDecl>(OverriddenMD);
946
947 // Add both the complete and deleting entries.
948 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
949 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
950 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
951 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
952 } else {
953 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
954 }
955
956 // We don't need to add an entry for this method.
957 ShouldAddEntryForMethod = false;
958 break;
959 }
960 }
961 }
962
963 if (!ShouldAddEntryForMethod)
964 continue;
965
966 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
967 if (MD->isImplicit()) {
968 assert(!ImplicitVirtualDtor &&
969 "Did already see an implicit virtual dtor!");
970 ImplicitVirtualDtor = DD;
971 continue;
972 }
973
974 // Add the complete dtor.
975 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
976
977 // Add the deleting dtor.
978 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
979 } else {
980 // Add the entry.
981 MethodVtableIndices[MD] = CurrentIndex++;
982 }
983 }
984
985 if (ImplicitVirtualDtor) {
986 // Itanium C++ ABI 2.5.2:
987 // If a class has an implicitly-defined virtual destructor,
988 // its entries come after the declared virtual function pointers.
989
990 // Add the complete dtor.
991 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
992 CurrentIndex++;
993
994 // Add the deleting dtor.
995 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
996 CurrentIndex++;
997 }
998
999 NumVirtualFunctionPointers[RD] = CurrentIndex;
1000}
1001
1002uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1003 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1004 NumVirtualFunctionPointers.find(RD);
1005 if (I != NumVirtualFunctionPointers.end())
1006 return I->second;
1007
1008 ComputeMethodVtableIndices(RD);
1009
1010 I = NumVirtualFunctionPointers.find(RD);
1011 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1012 return I->second;
1013}
1014
1015uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001016 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001017 if (I != MethodVtableIndices.end())
1018 return I->second;
1019
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001020 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001021
1022 ComputeMethodVtableIndices(RD);
1023
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001024 I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001025 assert(I != MethodVtableIndices.end() && "Did not find index!");
1026 return I->second;
1027}
1028
1029int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1030 const CXXRecordDecl *VBase) {
1031 ClassPairTy ClassPair(RD, VBase);
1032
1033 VirtualBaseClassIndiciesTy::iterator I =
1034 VirtualBaseClassIndicies.find(ClassPair);
1035 if (I != VirtualBaseClassIndicies.end())
1036 return I->second;
1037
1038 std::vector<llvm::Constant *> methods;
1039 // FIXME: This seems expensive. Can we do a partial job to get
1040 // just this data.
Mike Stump653d0b92009-11-13 02:13:54 +00001041 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump75ce5732009-10-31 20:06:59 +00001042 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001043 b.GenerateVtableForBase(RD);
1044 b.GenerateVtableForVBases(RD);
1045
1046 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1047 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1048 // Insert all types.
1049 ClassPairTy ClassPair(RD, I->first);
1050
1051 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1052 }
1053
1054 I = VirtualBaseClassIndicies.find(ClassPair);
1055 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1056
1057 return I->second;
1058}
1059
Mike Stump2cefe382009-11-12 20:47:57 +00001060llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1061 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001062 uint64_t Offset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001063 llvm::SmallString<256> OutName;
Mike Stump2cefe382009-11-12 20:47:57 +00001064 if (LayoutClass != RD)
Daniel Dunbare128dd12009-11-21 09:06:22 +00001065 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stumpeac45592009-11-11 20:26:26 +00001066 else
Daniel Dunbare128dd12009-11-21 09:06:22 +00001067 getMangleContext().mangleCXXVtable(RD, OutName);
1068 llvm::StringRef Name = OutName.str();
Benjamin Kramerbb0a07b2009-10-11 22:57:54 +00001069
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001070 std::vector<llvm::Constant *> methods;
1071 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1072 int64_t AddressPoint;
1073
Mike Stumpaa51ad62009-11-19 04:04:36 +00001074 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stumpcd2b8212009-11-19 20:52:19 +00001075 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001076 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1077 Offset)];
Mike Stumpcd2b8212009-11-19 20:52:19 +00001078 // FIXME: We can never have 0 address point. Do this for now so gepping
1079 // retains the same structure. Later, we'll just assert.
1080 if (AddressPoint == 0)
1081 AddressPoint = 1;
1082 } else {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001083 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001084
Mike Stumpaa51ad62009-11-19 04:04:36 +00001085 D1(printf("vtable %s\n", RD->getNameAsCString()));
1086 // First comes the vtables for all the non-virtual bases...
1087 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001088
Mike Stumpaa51ad62009-11-19 04:04:36 +00001089 // then the vtables for all the virtual bases.
1090 b.GenerateVtableForVBases(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001091
Mike Stumpaa51ad62009-11-19 04:04:36 +00001092 bool CreateDefinition = true;
1093 if (LayoutClass != RD)
1094 CreateDefinition = true;
1095 else {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001096 const ASTRecordLayout &Layout =
1097 getContext().getASTRecordLayout(LayoutClass);
1098
1099 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001100 if (!KeyFunction->getBody()) {
1101 // If there is a KeyFunction, and it isn't defined, just build a
1102 // reference to the vtable.
1103 CreateDefinition = false;
1104 }
1105 }
1106 }
1107
1108 llvm::Constant *C = 0;
1109 llvm::Type *type = Ptr8Ty;
1110 llvm::GlobalVariable::LinkageTypes linktype
1111 = llvm::GlobalValue::ExternalLinkage;
1112 if (CreateDefinition) {
1113 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1114 C = llvm::ConstantArray::get(ntype, methods);
1115 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1116 if (LayoutClass->isInAnonymousNamespace())
1117 linktype = llvm::GlobalValue::InternalLinkage;
1118 type = ntype;
1119 }
1120 llvm::GlobalVariable *OGV = GV;
1121 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1122 if (OGV) {
1123 GV->takeName(OGV);
1124 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1125 OGV->getType());
1126 OGV->replaceAllUsesWith(NewPtr);
1127 OGV->eraseFromParent();
1128 }
1129 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1130 if (Hidden)
1131 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1132 }
Mike Stumpc0f632d2009-11-18 04:00:48 +00001133 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stumpd846d082009-11-10 07:44:33 +00001134 llvm::Constant *AddressPointC;
1135 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1136 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1137 AddressPoint*LLVMPointerWidth/8);
Mike Stump2cefe382009-11-12 20:47:57 +00001138 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1139 1);
Mike Stumpd846d082009-11-10 07:44:33 +00001140
Mike Stumpcd2b8212009-11-19 20:52:19 +00001141 assert(vtable->getType() == Ptr8Ty);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001142 return vtable;
1143}
Mike Stump9f23a142009-11-10 02:30:51 +00001144
Mike Stumpae1b85d2009-12-02 19:07:44 +00001145namespace {
Mike Stump9f23a142009-11-10 02:30:51 +00001146class VTTBuilder {
1147 /// Inits - The list of values built for the VTT.
1148 std::vector<llvm::Constant *> &Inits;
1149 /// Class - The most derived class that this vtable is being built for.
1150 const CXXRecordDecl *Class;
1151 CodeGenModule &CGM; // Per-module state.
Mike Stump8b2d2d02009-11-11 00:35:07 +00001152 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001153 /// BLayout - Layout for the most derived class that this vtable is being
1154 /// built for.
1155 const ASTRecordLayout &BLayout;
Mike Stump83066c82009-11-13 01:54:23 +00001156 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +00001157 // vtbl - A pointer to the vtable for Class.
1158 llvm::Constant *ClassVtbl;
1159 llvm::LLVMContext &VMContext;
Mike Stump9f23a142009-11-10 02:30:51 +00001160
Mike Stump8677bc22009-11-12 22:56:32 +00001161 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stump83066c82009-11-13 01:54:23 +00001162 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1163 const CXXRecordDecl *VtblClass,
1164 const CXXRecordDecl *RD,
Mike Stump8677bc22009-11-12 22:56:32 +00001165 uint64_t Offset) {
1166 int64_t AddressPoint;
Mike Stump83066c82009-11-13 01:54:23 +00001167 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump2b34bc52009-11-12 23:36:21 +00001168 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stumpcd2b8212009-11-19 20:52:19 +00001169 // retains the same structure. Later we'll just assert.
Mike Stump2b34bc52009-11-12 23:36:21 +00001170 if (AddressPoint == 0)
1171 AddressPoint = 1;
Mike Stump83066c82009-11-13 01:54:23 +00001172 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1173 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1174 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump8677bc22009-11-12 22:56:32 +00001175 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1176 llvm::Constant *init;
1177 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1178 AddressPoint*LLVMPointerWidth/8);
1179 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1180 return init;
1181 }
1182
Mike Stump2cefe382009-11-12 20:47:57 +00001183 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1184 /// current offset in bits to the object we're working on.
Mike Stump8677bc22009-11-12 22:56:32 +00001185 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stump83066c82009-11-13 01:54:23 +00001186 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1187 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001188 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1189 return;
1190
1191 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1192 e = RD->bases_end(); i != e; ++i) {
1193 const CXXRecordDecl *Base =
1194 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1195 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1196 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1197 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1198 bool NonVirtualPrimaryBase;
1199 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1200 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001201 uint64_t BaseOffset;
1202 if (!i->isVirtual()) {
1203 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1204 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1205 } else
1206 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2b34bc52009-11-12 23:36:21 +00001207 llvm::Constant *subvtbl = vtbl;
Mike Stump83066c82009-11-13 01:54:23 +00001208 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump8b2d2d02009-11-11 00:35:07 +00001209 if ((Base->getNumVBases() || BaseMorallyVirtual)
1210 && !NonVirtualPrimaryBase) {
1211 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump8677bc22009-11-12 22:56:32 +00001212 llvm::Constant *init;
Mike Stump2b34bc52009-11-12 23:36:21 +00001213 if (BaseMorallyVirtual)
Mike Stump83066c82009-11-13 01:54:23 +00001214 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001215 else {
Mike Stump8677bc22009-11-12 22:56:32 +00001216 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001217 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump83066c82009-11-13 01:54:23 +00001218 subVtblClass = Base;
Mike Stump2b34bc52009-11-12 23:36:21 +00001219 }
Mike Stump8677bc22009-11-12 22:56:32 +00001220 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001221 }
Mike Stump83066c82009-11-13 01:54:23 +00001222 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001223 }
1224 }
1225
Mike Stump2cefe382009-11-12 20:47:57 +00001226 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1227 /// currnet object we're working on.
1228 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001229 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1230 return;
1231
Mike Stump2cefe382009-11-12 20:47:57 +00001232 llvm::Constant *init;
Mike Stump83066c82009-11-13 01:54:23 +00001233 const CXXRecordDecl *VtblClass;
1234
Mike Stump8b2d2d02009-11-11 00:35:07 +00001235 // First comes the primary virtual table pointer...
Mike Stump83066c82009-11-13 01:54:23 +00001236 if (MorallyVirtual) {
1237 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1238 VtblClass = Class;
1239 } else {
Mike Stump2cefe382009-11-12 20:47:57 +00001240 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stump83066c82009-11-13 01:54:23 +00001241 VtblClass = RD;
1242 }
Mike Stump8677bc22009-11-12 22:56:32 +00001243 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump2cefe382009-11-12 20:47:57 +00001244 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001245
1246 // then the secondary VTTs....
Mike Stump2cefe382009-11-12 20:47:57 +00001247 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001248
1249 // and last the secondary vtable pointers.
Mike Stump83066c82009-11-13 01:54:23 +00001250 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001251 }
1252
1253 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1254 /// built from each direct non-virtual proper base that requires a VTT in
1255 /// declaration order.
Mike Stump2cefe382009-11-12 20:47:57 +00001256 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1257 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001258 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1259 e = RD->bases_end(); i != e; ++i) {
1260 const CXXRecordDecl *Base =
1261 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1262 if (i->isVirtual())
1263 continue;
Mike Stump2cefe382009-11-12 20:47:57 +00001264 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1265 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1266 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001267 }
1268 }
1269
1270 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1271 /// graph preorder.
1272 void VirtualVTTs(const CXXRecordDecl *RD) {
1273 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1274 e = RD->bases_end(); i != e; ++i) {
1275 const CXXRecordDecl *Base =
1276 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1277 if (i->isVirtual() && !SeenVBase.count(Base)) {
1278 SeenVBase.insert(Base);
Mike Stump2cefe382009-11-12 20:47:57 +00001279 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1280 BuildVTT(Base, BaseOffset, true);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001281 }
1282 VirtualVTTs(Base);
1283 }
1284 }
Mike Stump9f23a142009-11-10 02:30:51 +00001285public:
1286 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001287 CodeGenModule &cgm)
1288 : Inits(inits), Class(c), CGM(cgm),
Mike Stump2cefe382009-11-12 20:47:57 +00001289 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stump83066c82009-11-13 01:54:23 +00001290 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump2cefe382009-11-12 20:47:57 +00001291 VMContext(cgm.getModule().getContext()) {
Mike Stumpd846d082009-11-10 07:44:33 +00001292
Mike Stump8b2d2d02009-11-11 00:35:07 +00001293 // First comes the primary virtual table pointer for the complete class...
Mike Stump2cefe382009-11-12 20:47:57 +00001294 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1295 Inits.push_back(ClassVtbl);
1296 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1297
Mike Stump8b2d2d02009-11-11 00:35:07 +00001298 // then the secondary VTTs...
1299 SecondaryVTTs(Class);
1300
1301 // then the secondary vtable pointers...
Mike Stump83066c82009-11-13 01:54:23 +00001302 Secondary(Class, ClassVtbl, Class);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001303
1304 // and last, the virtual VTTs.
1305 VirtualVTTs(Class);
Mike Stump9f23a142009-11-10 02:30:51 +00001306 }
1307};
Mike Stumpae1b85d2009-12-02 19:07:44 +00001308}
Mike Stump9f23a142009-11-10 02:30:51 +00001309
Mike Stumpd846d082009-11-10 07:44:33 +00001310llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpb4722212009-11-10 19:13:04 +00001311 // Only classes that have virtual bases need a VTT.
1312 if (RD->getNumVBases() == 0)
1313 return 0;
1314
Mike Stump9f23a142009-11-10 02:30:51 +00001315 llvm::SmallString<256> OutName;
Daniel Dunbare128dd12009-11-21 09:06:22 +00001316 getMangleContext().mangleCXXVTT(RD, OutName);
1317 llvm::StringRef Name = OutName.str();
Mike Stump9f23a142009-11-10 02:30:51 +00001318
1319 llvm::GlobalVariable::LinkageTypes linktype;
1320 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stumpaa51ad62009-11-19 04:04:36 +00001321 if (RD->isInAnonymousNamespace())
1322 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stump9f23a142009-11-10 02:30:51 +00001323 std::vector<llvm::Constant *> inits;
1324 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1325
Mike Stump9f23a142009-11-10 02:30:51 +00001326 D1(printf("vtt %s\n", RD->getNameAsCString()));
1327
Mike Stump8b2d2d02009-11-11 00:35:07 +00001328 VTTBuilder b(inits, RD, *this);
1329
Mike Stump9f23a142009-11-10 02:30:51 +00001330 llvm::Constant *C;
1331 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1332 C = llvm::ConstantArray::get(type, inits);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001333 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stumpaa51ad62009-11-19 04:04:36 +00001334 linktype, C, Name);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001335 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1336 if (Hidden)
1337 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1338 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stump9f23a142009-11-10 02:30:51 +00001339}
Mike Stumpd846d082009-11-10 07:44:33 +00001340
Mike Stump1a139f82009-11-19 01:08:19 +00001341void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1342 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpc01c2b82009-12-02 18:57:08 +00001343 CGM.GenerateRTTI(RD);
Mike Stump1a139f82009-11-19 01:08:19 +00001344 CGM.GenerateVTT(RD);
1345}
1346
Mike Stumpeac45592009-11-11 20:26:26 +00001347llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stumpd846d082009-11-10 07:44:33 +00001348 llvm::Constant *&vtbl = Vtables[RD];
1349 if (vtbl)
1350 return vtbl;
Mike Stump2cefe382009-11-12 20:47:57 +00001351 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001352
1353 bool CreateDefinition = true;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001354
1355 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1356 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001357 if (!KeyFunction->getBody()) {
1358 // If there is a KeyFunction, and it isn't defined, just build a
1359 // reference to the vtable.
1360 CreateDefinition = false;
1361 }
1362 }
1363
1364 if (CreateDefinition) {
Mike Stumpc01c2b82009-12-02 18:57:08 +00001365 CGM.GenerateRTTI(RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001366 CGM.GenerateVTT(RD);
1367 }
Mike Stumpd846d082009-11-10 07:44:33 +00001368 return vtbl;
1369}
Mike Stumpeac45592009-11-11 20:26:26 +00001370
Mike Stump2cefe382009-11-12 20:47:57 +00001371llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1372 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001373 uint64_t Offset) {
Mike Stump2cefe382009-11-12 20:47:57 +00001374 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stumpeac45592009-11-11 20:26:26 +00001375}
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001376
1377void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1378 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1379 const CXXRecordDecl *RD = MD->getParent();
1380
1381 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1382
1383 // Get the key function.
1384 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1385
1386 if (!KeyFunction) {
1387 // If there's no key function, we don't want to emit the vtable here.
1388 return;
1389 }
1390
1391 // Check if we have the key function.
1392 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1393 return;
1394
1395 // If the key function is a destructor, we only want to emit the vtable once,
1396 // so do it for the complete destructor.
1397 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1398 return;
1399
1400 // Emit the data.
1401 GenerateClassData(RD);
1402}
1403