blob: c8d4a736839af4f5e913f1963a87be65a20d94db [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;
31 std::vector<llvm::Constant *> submethods;
32 llvm::Type *Ptr8Ty;
33 /// Class - The most derived class that this vtable is being built for.
34 const CXXRecordDecl *Class;
Mike Stump83066c82009-11-13 01:54:23 +000035 /// LayoutClass - The most derived class used for virtual base layout
36 /// information.
37 const CXXRecordDecl *LayoutClass;
Mike Stump653d0b92009-11-13 02:13:54 +000038 /// LayoutOffset - The offset for Class in LayoutClass.
39 uint64_t LayoutOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000040 /// BLayout - Layout for the most derived class that this vtable is being
41 /// built for.
42 const ASTRecordLayout &BLayout;
43 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
44 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
45 llvm::Constant *rtti;
46 llvm::LLVMContext &VMContext;
47 CodeGenModule &CGM; // Per-module state.
48 /// Index - Maps a method decl into a vtable index. Useful for virtual
49 /// dispatch codegen.
Anders Carlssonfb4dda42009-11-13 17:08:56 +000050 llvm::DenseMap<GlobalDecl, Index_t> Index;
51 llvm::DenseMap<GlobalDecl, Index_t> VCall;
52 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpcd6f9ed2009-11-06 23:27:42 +000053 // This is the offset to the nearest virtual base
Anders Carlssonfb4dda42009-11-13 17:08:56 +000054 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000055 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stumpbb9ff052009-10-27 23:46:47 +000056
Anders Carlsson323bb042009-11-26 19:54:33 +000057 /// PureVirtualFunction - Points to __cxa_pure_virtual.
58 llvm::Constant *PureVirtualFn;
59
Anders Carlssona84b6e82009-12-04 02:01:07 +000060 /// VtableMethods - A data structure for keeping track of methods in a vtable.
61 /// Can add methods, override methods and iterate in vtable order.
62 class VtableMethods {
63 // MethodToIndexMap - Maps from a global decl to the index it has in the
64 // Methods vector.
65 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
66
67 /// Methods - The methods, in vtable order.
68 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
69 MethodsVectorTy Methods;
70
71 public:
72 /// AddMethod - Add a method to the vtable methods.
73 void AddMethod(GlobalDecl GD) {
74 assert(!MethodToIndexMap.count(GD) &&
75 "Method has already been added!");
76
77 MethodToIndexMap[GD] = Methods.size();
78 Methods.push_back(GD);
79 }
80
81 /// OverrideMethod - Replace a method with another.
82 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
83 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
84 = MethodToIndexMap.find(OverriddenGD);
85 assert(i != MethodToIndexMap.end() && "Did not find entry!");
86
87 // Get the index of the old decl.
88 uint64_t Index = i->second;
89
90 // Replace the old decl with the new decl.
91 Methods[Index] = GD;
92
93 // Now remove the old decl from the method to index map.
94 MethodToIndexMap.erase(i);
95
96 // And add the new.
97 MethodToIndexMap[GD] = Index;
98 }
99
100 MethodsVectorTy::size_type size() const {
101 return Methods.size();
102 }
103
104 void clear() {
105 MethodToIndexMap.clear();
106 Methods.clear();
107 }
108
109 GlobalDecl operator[](unsigned Index) const {
110 return Methods[Index];
111 }
112 };
113
114 /// Methods - The vtable methods we're currently building.
115 VtableMethods Methods;
116
Anders Carlsson4c837d22009-12-04 02:26:15 +0000117 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
118 /// pointer adjustment needed for a method.
119 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
120 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlssond420a312009-11-26 19:32:45 +0000121
Anders Carlssonc521f952009-12-04 02:22:02 +0000122 /// BaseReturnTypes - Contains the base return types of methods who have been
123 /// overridden with methods whose return types require adjustment. Used for
124 /// generating covariant thunk information.
125 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
126 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlssond420a312009-11-26 19:32:45 +0000127
128 /// PureVirtualMethods - Pure virtual methods.
129 typedef llvm::DenseSet<GlobalDecl> PureVirtualMethodsSetTy;
130 PureVirtualMethodsSetTy PureVirtualMethods;
131
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000132 std::vector<Index_t> VCalls;
Mike Stump2cefe382009-11-12 20:47:57 +0000133
134 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000135 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
136 // vtable for use in computing the initializers for the VTT.
137 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +0000138
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000139 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000140 const bool Extern;
141 const uint32_t LLVMPointerWidth;
142 Index_t extra;
Mike Stump37dbe962009-10-15 02:04:03 +0000143 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000144 static llvm::DenseMap<CtorVtable_t, int64_t>&
145 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
146 const CXXRecordDecl *c) {
147 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
148 if (oref == 0)
149 oref = new CodeGenModule::AddrMap_t;
150
151 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
152 if (ref == 0)
153 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
154 return *ref;
155 }
Anders Carlsson323bb042009-11-26 19:54:33 +0000156
157 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
158 llvm::Constant* getPureVirtualFn() {
159 if (!PureVirtualFn) {
160 const llvm::FunctionType *Ty =
161 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
162 /*isVarArg=*/false);
163 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
164 }
165
166 return PureVirtualFn;
167 }
168
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000169public:
Mike Stump653d0b92009-11-13 02:13:54 +0000170 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
171 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
172 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stump83066c82009-11-13 01:54:23 +0000173 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpc01c2b82009-12-02 18:57:08 +0000174 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000175 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump1960b202009-11-19 00:49:05 +0000176 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000177 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000178 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
179 }
180
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000181 llvm::DenseMap<GlobalDecl, Index_t> &getIndex() { return Index; }
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
291 void InstallThunks() {
Anders Carlssonc521f952009-12-04 02:22:02 +0000292 for (BaseReturnTypesMapTy::const_iterator i = BaseReturnTypes.begin(),
293 e = BaseReturnTypes.end(); i != e; ++i) {
Anders Carlsson8c889ab2009-12-04 02:11:21 +0000294 uint64_t Index = i->first;
295 GlobalDecl GD = Methods[Index];
296
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000297 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
298 if (MD->isPure())
299 continue;
300
Anders Carlssonc521f952009-12-04 02:22:02 +0000301 QualType BaseReturnType = i->second;
302
Anders Carlsson06c14b62009-12-03 02:16:14 +0000303 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000304
305 // Check if there is an adjustment for the 'this' pointer.
306 ThunkAdjustment ThisAdjustment;
Anders Carlsson4c837d22009-12-04 02:26:15 +0000307 ThisAdjustmentsMapTy::iterator it = ThisAdjustments.find(Index);
308 if (it != ThisAdjustments.end()) {
309 ThisAdjustment = it->second;
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000310
Anders Carlsson4c837d22009-12-04 02:26:15 +0000311 ThisAdjustments.erase(it);
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000312 }
Anders Carlsson657f1392009-12-03 02:32:59 +0000313
314 // Construct the return adjustment.
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000315 QualType DerivedType =
316 MD->getType()->getAs<FunctionType>()->getResultType();
317
318 int64_t NonVirtualAdjustment =
Anders Carlssonc521f952009-12-04 02:22:02 +0000319 getNVOffset(BaseReturnType, DerivedType) / 8;
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000320
321 int64_t VirtualAdjustment =
Anders Carlssonc521f952009-12-04 02:22:02 +0000322 getVbaseOffset(BaseReturnType, DerivedType);
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000323
324 ThunkAdjustment ReturnAdjustment(NonVirtualAdjustment, VirtualAdjustment);
Anders Carlsson657f1392009-12-03 02:32:59 +0000325
326 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson06c14b62009-12-03 02:16:14 +0000327 submethods[Index] = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000328 }
Anders Carlssonc521f952009-12-04 02:22:02 +0000329 BaseReturnTypes.clear();
Anders Carlssonc38b40a2009-12-03 02:03:29 +0000330
Anders Carlsson4c837d22009-12-04 02:26:15 +0000331 for (ThisAdjustmentsMapTy::const_iterator i = ThisAdjustments.begin(),
332 e = ThisAdjustments.end(); i != e; ++i) {
Anders Carlsson80bc5d52009-12-03 02:41:55 +0000333 uint64_t Index = i->first;
Anders Carlsson597c7762009-12-04 02:14:12 +0000334 GlobalDecl GD = Methods[Index];
Anders Carlsson4c837d22009-12-04 02:26:15 +0000335 const ThunkAdjustment &ThisAdjustment = i->second;
Anders Carlsson80bc5d52009-12-03 02:41:55 +0000336
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000337 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000338 assert(!MD->isPure() && "Can't thunk pure virtual methods!");
Anders Carlsson29a1f752009-12-03 02:39:59 +0000339
340 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000341
Anders Carlsson4c837d22009-12-04 02:26:15 +0000342 submethods[Index] = CGM.BuildThunk(GD, Extern, ThisAdjustment);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000343 }
Anders Carlsson4c837d22009-12-04 02:26:15 +0000344 ThisAdjustments.clear();
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000345
Anders Carlssond420a312009-11-26 19:32:45 +0000346 for (PureVirtualMethodsSetTy::iterator i = PureVirtualMethods.begin(),
347 e = PureVirtualMethods.end(); i != e; ++i) {
348 GlobalDecl GD = *i;
Anders Carlsson323bb042009-11-26 19:54:33 +0000349 submethods[Index[GD]] = getPureVirtualFn();
Mike Stumpbb9ff052009-10-27 23:46:47 +0000350 }
Anders Carlssond420a312009-11-26 19:32:45 +0000351 PureVirtualMethods.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000352 }
353
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000354 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
355 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
356
Anders Carlsson64457732009-11-24 05:08:52 +0000357 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump18e8b472009-10-27 23:36:26 +0000358
Mike Stumpcdeb8002009-12-03 16:55:20 +0000359 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump18e8b472009-10-27 23:36:26 +0000360 }
361
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000362 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
363 int64_t CurrentVBaseOffset) {
Mike Stump37dbe962009-10-15 02:04:03 +0000364 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000365 e = Path->rend(); i != e; ++i) {
366 const CXXRecordDecl *RD = i->first;
Mike Stump8bccbfd2009-10-15 09:30:16 +0000367 int64_t OverrideOffset = i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000368 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
369 ++mi) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000370 const CXXMethodDecl *MD = *mi;
371
372 if (!MD->isVirtual())
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000373 continue;
374
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000375 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
376 // Override both the complete and the deleting destructor.
377 GlobalDecl CompDtor(DD, Dtor_Complete);
378 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
379 OverrideOffset, Offset, CurrentVBaseOffset);
380
381 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
382 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
383 OverrideOffset, Offset, CurrentVBaseOffset);
384 } else {
385 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
386 Offset, CurrentVBaseOffset);
387 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000388 }
389 }
390 }
391
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000392 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000393 int64_t CurrentVBaseOffset) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000394 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump18e8b472009-10-27 23:36:26 +0000395
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000396 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000397 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000398 CurrentVBaseOffset))
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000399 return;
400
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000401 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
402
Anders Carlssoncdf18982009-12-04 02:08:24 +0000403 // We didn't find an entry in the vtable that we could use, add a new
404 // entry.
405 Methods.AddMethod(GD);
406
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000407 Index[GD] = submethods.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000408 submethods.push_back(m);
Mike Stumpc5a332c2009-11-13 23:45:53 +0000409 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
410 (int)Index[GD]));
Mike Stump375faa82009-10-28 00:35:46 +0000411 if (MD->isPure())
Anders Carlssond420a312009-11-26 19:32:45 +0000412 PureVirtualMethods.insert(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000413 if (MorallyVirtual) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000414 VCallOffset[GD] = Offset/8;
415 Index_t &idx = VCall[GD];
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000416 // Allocate the first one, after that, we reuse the previous one.
417 if (idx == 0) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000418 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000419 idx = VCalls.size()+1;
420 VCalls.push_back(0);
Mike Stump75ce5732009-10-31 20:06:59 +0000421 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpc5a332c2009-11-13 23:45:53 +0000422 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000423 }
424 }
425 }
426
427 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000428 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000429 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000430 ++mi) {
431 const CXXMethodDecl *MD = *mi;
432 if (!MD->isVirtual())
433 continue;
434
435 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
436 // For destructors, add both the complete and the deleting destructor
437 // to the vtable.
438 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000439 CurrentVBaseOffset);
Eli Friedman03aa2f12009-11-30 01:19:33 +0000440 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
441 CurrentVBaseOffset);
442 } else
443 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000444 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000445 }
446
447 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
448 const CXXRecordDecl *PrimaryBase,
449 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000450 int64_t Offset, int64_t CurrentVBaseOffset,
451 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000452 Path->push_back(std::make_pair(RD, Offset));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000453 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
454 e = RD->bases_end(); i != e; ++i) {
455 if (i->isVirtual())
456 continue;
457 const CXXRecordDecl *Base =
458 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
459 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
460 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
461 StartNewTable();
Mike Stump653d0b92009-11-13 02:13:54 +0000462 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000463 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000464 }
465 }
Mike Stump37dbe962009-10-15 02:04:03 +0000466 Path->pop_back();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000467 }
468
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000469// #define D(X) do { X; } while (0)
470#define D(X)
471
472 void insertVCalls(int InsertionPoint) {
473 llvm::Constant *e = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000474 D1(printf("============= combining vbase/vcall\n"));
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000475 D(VCalls.insert(VCalls.begin(), 673));
476 D(VCalls.push_back(672));
Mike Stump8bccbfd2009-10-15 09:30:16 +0000477 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000478 // The vcalls come first...
479 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
480 e = VCalls.rend();
481 i != e; ++i)
482 methods[InsertionPoint++] = wrap((0?600:0) + *i);
483 VCalls.clear();
Mike Stump9f23a142009-11-10 02:30:51 +0000484 VCall.clear();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000485 }
486
Mike Stump559387f2009-11-13 23:13:20 +0000487 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
488 Index_t AddressPoint) {
489 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
490 RD->getNameAsCString(), Class->getNameAsCString(),
491 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000492 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000493
494 // Now also add the address point for all our primary bases.
495 while (1) {
496 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
497 RD = Layout.getPrimaryBase();
498 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
499 // FIXME: Double check this.
500 if (RD == 0)
501 break;
502 if (PrimaryBaseWasVirtual &&
503 BLayout.getVBaseClassOffset(RD) != Offset)
504 break;
505 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
506 RD->getNameAsCString(), Class->getNameAsCString(),
507 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000508 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000509 }
510 }
511
512
Mike Stump75ce5732009-10-31 20:06:59 +0000513 Index_t end(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
514 const CXXRecordDecl *PrimaryBase, bool PrimaryBaseWasVirtual,
515 bool MorallyVirtual, int64_t Offset, bool ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000516 int64_t CurrentVBaseOffset,
Mike Stump75ce5732009-10-31 20:06:59 +0000517 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000518 bool alloc = false;
519 if (Path == 0) {
520 alloc = true;
521 Path = new Path_t;
522 }
523
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000524 StartNewTable();
525 extra = 0;
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000526 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
527 int VCallInsertionPoint = methods.size();
528 if (!DeferVCalls) {
529 insertVCalls(VCallInsertionPoint);
Mike Stump8bccbfd2009-10-15 09:30:16 +0000530 } else
531 // FIXME: just for extra, or for all uses of VCalls.size post this?
532 extra = -VCalls.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000533
Mike Stump653d0b92009-11-13 02:13:54 +0000534 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000535 methods.push_back(rtti);
536 Index_t AddressPoint = methods.size();
537
Anders Carlssoncdf18982009-12-04 02:08:24 +0000538 assert(submethods.size() == Methods.size() && "Method size mismatch!");
539
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000540 InstallThunks();
Mike Stump75ce5732009-10-31 20:06:59 +0000541 D1(printf("============= combining methods\n"));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000542 methods.insert(methods.end(), submethods.begin(), submethods.end());
Anders Carlssoncdf18982009-12-04 02:08:24 +0000543
544 Methods.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000545 submethods.clear();
546
547 // and then the non-virtual bases.
548 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000549 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000550
551 if (ForVirtualBase) {
Mike Stump2cefe382009-11-12 20:47:57 +0000552 // FIXME: We're adding to VCalls in callers, we need to do the overrides
553 // in the inner part, so that we know the complete set of vcalls during
554 // the build and don't have to insert into methods. Saving out the
555 // AddressPoint here, would need to be fixed, if we didn't do that. Also
556 // retroactively adding vcalls for overrides later wind up in the wrong
557 // place, the vcall slot has to be alloted during the walk of the base
558 // when the function is first introduces.
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000559 AddressPoint += VCalls.size();
Mike Stump2cefe382009-11-12 20:47:57 +0000560 insertVCalls(VCallInsertionPoint);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000561 }
562
Mike Stump559387f2009-11-13 23:13:20 +0000563 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump2cefe382009-11-12 20:47:57 +0000564
Mike Stump37dbe962009-10-15 02:04:03 +0000565 if (alloc) {
566 delete Path;
567 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000568 return AddressPoint;
569 }
570
Mike Stump75ce5732009-10-31 20:06:59 +0000571 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
572 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000573 int64_t CurrentVBaseOffset) {
Mike Stump75ce5732009-10-31 20:06:59 +0000574 if (!RD->isDynamicClass())
575 return;
576
577 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
578 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
579 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
580
581 // vtables are composed from the chain of primaries.
582 if (PrimaryBase) {
583 D1(printf(" doing primaries for %s most derived %s\n",
584 RD->getNameAsCString(), Class->getNameAsCString()));
585
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000586 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
587 if (PrimaryBaseWasVirtual)
588 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
589
Mike Stump75ce5732009-10-31 20:06:59 +0000590 if (!PrimaryBaseWasVirtual)
591 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000592 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000593 }
594
595 D1(printf(" doing vcall entries for %s most derived %s\n",
596 RD->getNameAsCString(), Class->getNameAsCString()));
597
598 // And add the virtuals for the class to the primary vtable.
Eli Friedman03aa2f12009-11-30 01:19:33 +0000599 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000600 }
601
602 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
603 bool updateVBIndex, Index_t current_vbindex,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000604 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000605 bool bottom) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000606 if (!RD->isDynamicClass())
607 return;
608
609 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
610 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
611 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
612
613 // vtables are composed from the chain of primaries.
614 if (PrimaryBase) {
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000615 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
616 if (PrimaryBaseWasVirtual) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000617 IndirectPrimary.insert(PrimaryBase);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000618 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
619 }
Mike Stump75ce5732009-10-31 20:06:59 +0000620
621 D1(printf(" doing primaries for %s most derived %s\n",
622 RD->getNameAsCString(), Class->getNameAsCString()));
623
624 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000625 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000626 BaseCurrentVBaseOffset, false);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000627 }
628
Mike Stump75ce5732009-10-31 20:06:59 +0000629 D1(printf(" doing vbase entries for %s most derived %s\n",
630 RD->getNameAsCString(), Class->getNameAsCString()));
631 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
632
633 if (RDisVirtualBase || bottom) {
634 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000635 CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000636 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000637 }
638
Mike Stump653d0b92009-11-13 02:13:54 +0000639 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
640 bool MorallyVirtual = false,
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000641 bool ForVirtualBase = false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000642 int CurrentVBaseOffset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000643 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000644 if (!RD->isDynamicClass())
645 return 0;
646
Mike Stumpfa818082009-11-13 02:35:38 +0000647 // Construction vtable don't need parts that have no virtual bases and
648 // aren't morally virtual.
649 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
650 return 0;
651
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000652 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
653 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
654 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
655
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000656 extra = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000657 D1(printf("building entries for base %s most derived %s\n",
658 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000659
Mike Stump75ce5732009-10-31 20:06:59 +0000660 if (ForVirtualBase)
661 extra = VCalls.size();
662
663 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000664 CurrentVBaseOffset, true);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000665
666 if (Path)
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000667 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000668
Mike Stump75ce5732009-10-31 20:06:59 +0000669 return end(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual, MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000670 Offset, ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000671 }
672
673 void GenerateVtableForVBases(const CXXRecordDecl *RD,
674 int64_t Offset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000675 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000676 bool alloc = false;
677 if (Path == 0) {
678 alloc = true;
Mike Stump37dbe962009-10-15 02:04:03 +0000679 Path = new Path_t;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000680 }
681 // FIXME: We also need to override using all paths to a virtual base,
682 // right now, we just process the first path
683 Path->push_back(std::make_pair(RD, Offset));
684 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
685 e = RD->bases_end(); i != e; ++i) {
686 const CXXRecordDecl *Base =
687 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
688 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
689 // Mark it so we don't output it twice.
690 IndirectPrimary.insert(Base);
691 StartNewTable();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000692 VCall.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000693 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000694 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump75ce5732009-10-31 20:06:59 +0000695 D1(printf("vtable %s virtual base %s\n",
696 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump653d0b92009-11-13 02:13:54 +0000697 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000698 Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000699 }
Mike Stump2cefe382009-11-12 20:47:57 +0000700 int64_t BaseOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000701 if (i->isVirtual())
702 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2cefe382009-11-12 20:47:57 +0000703 else {
704 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
705 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
706 }
707
Mike Stump37dbe962009-10-15 02:04:03 +0000708 if (Base->getNumVBases()) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000709 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump37dbe962009-10-15 02:04:03 +0000710 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000711 }
712 Path->pop_back();
713 if (alloc)
714 delete Path;
715 }
716};
Anders Carlssonca1bf682009-12-03 01:54:02 +0000717} // end anonymous namespace
718
Anders Carlsson657f1392009-12-03 02:32:59 +0000719/// TypeConversionRequiresAdjustment - Returns whether conversion from a
720/// derived type to a base type requires adjustment.
721static bool
722TypeConversionRequiresAdjustment(ASTContext &Ctx,
723 const CXXRecordDecl *DerivedDecl,
724 const CXXRecordDecl *BaseDecl) {
725 CXXBasePaths Paths(/*FindAmbiguities=*/false,
726 /*RecordPaths=*/true, /*DetectVirtual=*/true);
727 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
728 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
729 assert(false && "Class must be derived from the passed in base class!");
730 return false;
731 }
732
733 // If we found a virtual base we always want to require adjustment.
734 if (Paths.getDetectedVirtual())
735 return true;
736
737 const CXXBasePath &Path = Paths.front();
738
739 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
740 const CXXBasePathElement &Element = Path[Start];
741
742 // Check the base class offset.
743 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
744
745 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
746 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
747
748 if (Layout.getBaseClassOffset(Base) != 0) {
749 // This requires an adjustment.
750 return true;
751 }
752 }
753
754 return false;
755}
756
757static bool
758TypeConversionRequiresAdjustment(ASTContext &Ctx,
759 QualType DerivedType, QualType BaseType) {
760 // Canonicalize the types.
761 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
762 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
763
764 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
765 "Types must have same type class!");
766
767 if (CanDerivedType == CanBaseType) {
768 // No adjustment needed.
769 return false;
770 }
771
772 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
773 CanDerivedType = RT->getPointeeType();
774 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
775 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
776 CanDerivedType = PT->getPointeeType();
777 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
778 } else {
779 assert(false && "Unexpected return type!");
780 }
781
782 if (CanDerivedType == CanBaseType) {
783 // No adjustment needed.
784 return false;
785 }
786
787 const CXXRecordDecl *DerivedDecl =
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000788 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson657f1392009-12-03 02:32:59 +0000789
790 const CXXRecordDecl *BaseDecl =
791 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
792
793 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
794}
795
Anders Carlssonca1bf682009-12-03 01:54:02 +0000796bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
797 bool MorallyVirtual, Index_t OverrideOffset,
798 Index_t Offset, int64_t CurrentVBaseOffset) {
799 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
800
801 const bool isPure = MD->isPure();
802 typedef CXXMethodDecl::method_iterator meth_iter;
803 // FIXME: Should OverrideOffset's be Offset?
804
805 // FIXME: Don't like the nested loops. For very large inheritance
806 // heirarchies we could have a table on the side with the final overridder
807 // and just replace each instance of an overridden method once. Would be
808 // nice to measure the cost/benefit on real code.
809
810 for (meth_iter mi = MD->begin_overridden_methods(),
811 e = MD->end_overridden_methods();
812 mi != e; ++mi) {
813 GlobalDecl OGD;
814
815 const CXXMethodDecl *OMD = *mi;
816 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
817 OGD = GlobalDecl(DD, GD.getDtorType());
818 else
819 OGD = OMD;
820
821 llvm::Constant *om;
822 om = WrapAddrOf(OGD);
823 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
824
825 for (Index_t i = 0, e = submethods.size();
826 i != e; ++i) {
827 // FIXME: begin_overridden_methods might be too lax, covariance */
828 if (submethods[i] != om)
829 continue;
Anders Carlsson657f1392009-12-03 02:32:59 +0000830
831 QualType ReturnType =
832 MD->getType()->getAs<FunctionType>()->getResultType();
833 QualType OverriddenReturnType =
834 OMD->getType()->getAs<FunctionType>()->getResultType();
835
836 // Check if we need a return type adjustment.
837 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
838 OverriddenReturnType)) {
Anders Carlssonc521f952009-12-04 02:22:02 +0000839 CanQualType &BaseReturnType = BaseReturnTypes[i];
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000840
Anders Carlsson657f1392009-12-03 02:32:59 +0000841 // Get the canonical return type.
842 CanQualType CanReturnType =
843 CGM.getContext().getCanonicalType(ReturnType);
844
845 // Insert the base return type.
Anders Carlssonc521f952009-12-04 02:22:02 +0000846 if (BaseReturnType.isNull())
847 BaseReturnType =
Anders Carlsson657f1392009-12-03 02:32:59 +0000848 CGM.getContext().getCanonicalType(OverriddenReturnType);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000849 }
Anders Carlsson657f1392009-12-03 02:32:59 +0000850
Anders Carlssoncdf18982009-12-04 02:08:24 +0000851 Methods.OverrideMethod(OGD, GD);
852
Anders Carlssonca1bf682009-12-03 01:54:02 +0000853 Index[GD] = i;
854 submethods[i] = m;
855 if (isPure)
856 PureVirtualMethods.insert(GD);
857 PureVirtualMethods.erase(OGD);
Anders Carlsson4c837d22009-12-04 02:26:15 +0000858 ThisAdjustments.erase(i);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000859 if (MorallyVirtual || VCall.count(OGD)) {
860 Index_t &idx = VCall[OGD];
861 if (idx == 0) {
862 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
863 VCallOffset[GD] = OverrideOffset/8;
864 idx = VCalls.size()+1;
865 VCalls.push_back(0);
866 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
867 MD->getNameAsString().c_str(), (int)-idx-3,
868 (int)VCalls[idx-1], Class->getNameAsCString()));
869 } else {
870 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
871 VCallOffset[GD] = VCallOffset[OGD];
872 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
873 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
874 MD->getNameAsString().c_str(), (int)-idx-3,
875 (int)VCalls[idx-1], Class->getNameAsCString()));
876 }
877 VCall[GD] = idx;
878 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
879 int64_t VirtualAdjustment =
880 -((idx + extra + 2) * LLVMPointerWidth / 8);
881
882 // Optimize out virtual adjustments of 0.
883 if (VCalls[idx-1] == 0)
884 VirtualAdjustment = 0;
885
886 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
887 VirtualAdjustment);
888
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000889 if (!isPure && !ThisAdjustment.isEmpty())
Anders Carlsson4c837d22009-12-04 02:26:15 +0000890 ThisAdjustments[i] = ThisAdjustment;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000891 return true;
892 }
893
894 // FIXME: finish off
895 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
896
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000897 if (NonVirtualAdjustment) {
Anders Carlssonca1bf682009-12-03 01:54:02 +0000898 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
899
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000900 if (!isPure)
Anders Carlsson4c837d22009-12-04 02:26:15 +0000901 ThisAdjustments[i] = ThisAdjustment;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000902 }
903 return true;
904 }
905 }
906
907 return false;
Anders Carlssond59885022009-11-27 22:21:51 +0000908}
909
Anders Carlssonf942ee02009-11-27 20:47:55 +0000910void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
911
912 // Itanium C++ ABI 2.5.2:
913 // The order of the virtual function pointers in a virtual table is the
914 // order of declaration of the corresponding member functions in the class.
915 //
916 // There is an entry for any virtual function declared in a class,
917 // whether it is a new function or overrides a base class function,
918 // unless it overrides a function from the primary base, and conversion
919 // between their return types does not require an adjustment.
920
921 int64_t CurrentIndex = 0;
922
923 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
924 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
925
926 if (PrimaryBase) {
Anders Carlssonc920fa22009-11-30 19:43:26 +0000927 assert(PrimaryBase->isDefinition() &&
928 "Should have the definition decl of the primary base!");
Anders Carlssonf942ee02009-11-27 20:47:55 +0000929
930 // Since the record decl shares its vtable pointer with the primary base
931 // we need to start counting at the end of the primary base's vtable.
932 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
933 }
934
935 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
936
937 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
938 e = RD->method_end(); i != e; ++i) {
939 const CXXMethodDecl *MD = *i;
940
941 // We only want virtual methods.
942 if (!MD->isVirtual())
943 continue;
944
945 bool ShouldAddEntryForMethod = true;
946
947 // Check if this method overrides a method in the primary base.
948 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
949 e = MD->end_overridden_methods(); i != e; ++i) {
950 const CXXMethodDecl *OverriddenMD = *i;
951 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
952 assert(OverriddenMD->isCanonicalDecl() &&
953 "Should have the canonical decl of the overridden RD!");
954
955 if (OverriddenRD == PrimaryBase) {
956 // Check if converting from the return type of the method to the
957 // return type of the overridden method requires conversion.
958 QualType ReturnType =
959 MD->getType()->getAs<FunctionType>()->getResultType();
960 QualType OverriddenReturnType =
961 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
962
963 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
964 ReturnType, OverriddenReturnType)) {
965 // This index is shared between the index in the vtable of the primary
966 // base class.
967 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
968 const CXXDestructorDecl *OverriddenDD =
969 cast<CXXDestructorDecl>(OverriddenMD);
970
971 // Add both the complete and deleting entries.
972 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
973 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
974 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
975 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
976 } else {
977 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
978 }
979
980 // We don't need to add an entry for this method.
981 ShouldAddEntryForMethod = false;
982 break;
983 }
984 }
985 }
986
987 if (!ShouldAddEntryForMethod)
988 continue;
989
990 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
991 if (MD->isImplicit()) {
992 assert(!ImplicitVirtualDtor &&
993 "Did already see an implicit virtual dtor!");
994 ImplicitVirtualDtor = DD;
995 continue;
996 }
997
998 // Add the complete dtor.
999 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
1000
1001 // Add the deleting dtor.
1002 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
1003 } else {
1004 // Add the entry.
1005 MethodVtableIndices[MD] = CurrentIndex++;
1006 }
1007 }
1008
1009 if (ImplicitVirtualDtor) {
1010 // Itanium C++ ABI 2.5.2:
1011 // If a class has an implicitly-defined virtual destructor,
1012 // its entries come after the declared virtual function pointers.
1013
1014 // Add the complete dtor.
1015 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1016 CurrentIndex++;
1017
1018 // Add the deleting dtor.
1019 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1020 CurrentIndex++;
1021 }
1022
1023 NumVirtualFunctionPointers[RD] = CurrentIndex;
1024}
1025
1026uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1027 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1028 NumVirtualFunctionPointers.find(RD);
1029 if (I != NumVirtualFunctionPointers.end())
1030 return I->second;
1031
1032 ComputeMethodVtableIndices(RD);
1033
1034 I = NumVirtualFunctionPointers.find(RD);
1035 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1036 return I->second;
1037}
1038
1039uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001040 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001041 if (I != MethodVtableIndices.end())
1042 return I->second;
1043
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001044 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001045
1046 ComputeMethodVtableIndices(RD);
1047
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001048 I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001049 assert(I != MethodVtableIndices.end() && "Did not find index!");
1050 return I->second;
1051}
1052
1053int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1054 const CXXRecordDecl *VBase) {
1055 ClassPairTy ClassPair(RD, VBase);
1056
1057 VirtualBaseClassIndiciesTy::iterator I =
1058 VirtualBaseClassIndicies.find(ClassPair);
1059 if (I != VirtualBaseClassIndicies.end())
1060 return I->second;
1061
1062 std::vector<llvm::Constant *> methods;
1063 // FIXME: This seems expensive. Can we do a partial job to get
1064 // just this data.
Mike Stump653d0b92009-11-13 02:13:54 +00001065 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump75ce5732009-10-31 20:06:59 +00001066 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001067 b.GenerateVtableForBase(RD);
1068 b.GenerateVtableForVBases(RD);
1069
1070 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1071 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1072 // Insert all types.
1073 ClassPairTy ClassPair(RD, I->first);
1074
1075 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1076 }
1077
1078 I = VirtualBaseClassIndicies.find(ClassPair);
1079 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1080
1081 return I->second;
1082}
1083
Mike Stump2cefe382009-11-12 20:47:57 +00001084llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1085 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001086 uint64_t Offset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001087 llvm::SmallString<256> OutName;
Mike Stump2cefe382009-11-12 20:47:57 +00001088 if (LayoutClass != RD)
Daniel Dunbare128dd12009-11-21 09:06:22 +00001089 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stumpeac45592009-11-11 20:26:26 +00001090 else
Daniel Dunbare128dd12009-11-21 09:06:22 +00001091 getMangleContext().mangleCXXVtable(RD, OutName);
1092 llvm::StringRef Name = OutName.str();
Benjamin Kramerbb0a07b2009-10-11 22:57:54 +00001093
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001094 std::vector<llvm::Constant *> methods;
1095 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1096 int64_t AddressPoint;
1097
Mike Stumpaa51ad62009-11-19 04:04:36 +00001098 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stumpcd2b8212009-11-19 20:52:19 +00001099 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001100 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1101 Offset)];
Mike Stumpcd2b8212009-11-19 20:52:19 +00001102 // FIXME: We can never have 0 address point. Do this for now so gepping
1103 // retains the same structure. Later, we'll just assert.
1104 if (AddressPoint == 0)
1105 AddressPoint = 1;
1106 } else {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001107 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001108
Mike Stumpaa51ad62009-11-19 04:04:36 +00001109 D1(printf("vtable %s\n", RD->getNameAsCString()));
1110 // First comes the vtables for all the non-virtual bases...
1111 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001112
Mike Stumpaa51ad62009-11-19 04:04:36 +00001113 // then the vtables for all the virtual bases.
1114 b.GenerateVtableForVBases(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001115
Mike Stumpaa51ad62009-11-19 04:04:36 +00001116 bool CreateDefinition = true;
1117 if (LayoutClass != RD)
1118 CreateDefinition = true;
1119 else {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001120 const ASTRecordLayout &Layout =
1121 getContext().getASTRecordLayout(LayoutClass);
1122
1123 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001124 if (!KeyFunction->getBody()) {
1125 // If there is a KeyFunction, and it isn't defined, just build a
1126 // reference to the vtable.
1127 CreateDefinition = false;
1128 }
1129 }
1130 }
1131
1132 llvm::Constant *C = 0;
1133 llvm::Type *type = Ptr8Ty;
1134 llvm::GlobalVariable::LinkageTypes linktype
1135 = llvm::GlobalValue::ExternalLinkage;
1136 if (CreateDefinition) {
1137 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1138 C = llvm::ConstantArray::get(ntype, methods);
1139 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1140 if (LayoutClass->isInAnonymousNamespace())
1141 linktype = llvm::GlobalValue::InternalLinkage;
1142 type = ntype;
1143 }
1144 llvm::GlobalVariable *OGV = GV;
1145 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1146 if (OGV) {
1147 GV->takeName(OGV);
1148 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1149 OGV->getType());
1150 OGV->replaceAllUsesWith(NewPtr);
1151 OGV->eraseFromParent();
1152 }
1153 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1154 if (Hidden)
1155 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1156 }
Mike Stumpc0f632d2009-11-18 04:00:48 +00001157 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stumpd846d082009-11-10 07:44:33 +00001158 llvm::Constant *AddressPointC;
1159 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1160 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1161 AddressPoint*LLVMPointerWidth/8);
Mike Stump2cefe382009-11-12 20:47:57 +00001162 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1163 1);
Mike Stumpd846d082009-11-10 07:44:33 +00001164
Mike Stumpcd2b8212009-11-19 20:52:19 +00001165 assert(vtable->getType() == Ptr8Ty);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001166 return vtable;
1167}
Mike Stump9f23a142009-11-10 02:30:51 +00001168
Mike Stumpae1b85d2009-12-02 19:07:44 +00001169namespace {
Mike Stump9f23a142009-11-10 02:30:51 +00001170class VTTBuilder {
1171 /// Inits - The list of values built for the VTT.
1172 std::vector<llvm::Constant *> &Inits;
1173 /// Class - The most derived class that this vtable is being built for.
1174 const CXXRecordDecl *Class;
1175 CodeGenModule &CGM; // Per-module state.
Mike Stump8b2d2d02009-11-11 00:35:07 +00001176 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001177 /// BLayout - Layout for the most derived class that this vtable is being
1178 /// built for.
1179 const ASTRecordLayout &BLayout;
Mike Stump83066c82009-11-13 01:54:23 +00001180 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +00001181 // vtbl - A pointer to the vtable for Class.
1182 llvm::Constant *ClassVtbl;
1183 llvm::LLVMContext &VMContext;
Mike Stump9f23a142009-11-10 02:30:51 +00001184
Mike Stump8677bc22009-11-12 22:56:32 +00001185 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stump83066c82009-11-13 01:54:23 +00001186 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1187 const CXXRecordDecl *VtblClass,
1188 const CXXRecordDecl *RD,
Mike Stump8677bc22009-11-12 22:56:32 +00001189 uint64_t Offset) {
1190 int64_t AddressPoint;
Mike Stump83066c82009-11-13 01:54:23 +00001191 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump2b34bc52009-11-12 23:36:21 +00001192 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stumpcd2b8212009-11-19 20:52:19 +00001193 // retains the same structure. Later we'll just assert.
Mike Stump2b34bc52009-11-12 23:36:21 +00001194 if (AddressPoint == 0)
1195 AddressPoint = 1;
Mike Stump83066c82009-11-13 01:54:23 +00001196 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1197 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1198 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump8677bc22009-11-12 22:56:32 +00001199 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1200 llvm::Constant *init;
1201 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1202 AddressPoint*LLVMPointerWidth/8);
1203 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1204 return init;
1205 }
1206
Mike Stump2cefe382009-11-12 20:47:57 +00001207 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1208 /// current offset in bits to the object we're working on.
Mike Stump8677bc22009-11-12 22:56:32 +00001209 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stump83066c82009-11-13 01:54:23 +00001210 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1211 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001212 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1213 return;
1214
1215 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1216 e = RD->bases_end(); i != e; ++i) {
1217 const CXXRecordDecl *Base =
1218 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1219 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1220 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1221 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1222 bool NonVirtualPrimaryBase;
1223 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1224 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001225 uint64_t BaseOffset;
1226 if (!i->isVirtual()) {
1227 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1228 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1229 } else
1230 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2b34bc52009-11-12 23:36:21 +00001231 llvm::Constant *subvtbl = vtbl;
Mike Stump83066c82009-11-13 01:54:23 +00001232 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump8b2d2d02009-11-11 00:35:07 +00001233 if ((Base->getNumVBases() || BaseMorallyVirtual)
1234 && !NonVirtualPrimaryBase) {
1235 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump8677bc22009-11-12 22:56:32 +00001236 llvm::Constant *init;
Mike Stump2b34bc52009-11-12 23:36:21 +00001237 if (BaseMorallyVirtual)
Mike Stump83066c82009-11-13 01:54:23 +00001238 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001239 else {
Mike Stump8677bc22009-11-12 22:56:32 +00001240 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001241 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump83066c82009-11-13 01:54:23 +00001242 subVtblClass = Base;
Mike Stump2b34bc52009-11-12 23:36:21 +00001243 }
Mike Stump8677bc22009-11-12 22:56:32 +00001244 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001245 }
Mike Stump83066c82009-11-13 01:54:23 +00001246 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001247 }
1248 }
1249
Mike Stump2cefe382009-11-12 20:47:57 +00001250 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1251 /// currnet object we're working on.
1252 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001253 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1254 return;
1255
Mike Stump2cefe382009-11-12 20:47:57 +00001256 llvm::Constant *init;
Mike Stump83066c82009-11-13 01:54:23 +00001257 const CXXRecordDecl *VtblClass;
1258
Mike Stump8b2d2d02009-11-11 00:35:07 +00001259 // First comes the primary virtual table pointer...
Mike Stump83066c82009-11-13 01:54:23 +00001260 if (MorallyVirtual) {
1261 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1262 VtblClass = Class;
1263 } else {
Mike Stump2cefe382009-11-12 20:47:57 +00001264 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stump83066c82009-11-13 01:54:23 +00001265 VtblClass = RD;
1266 }
Mike Stump8677bc22009-11-12 22:56:32 +00001267 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump2cefe382009-11-12 20:47:57 +00001268 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001269
1270 // then the secondary VTTs....
Mike Stump2cefe382009-11-12 20:47:57 +00001271 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001272
1273 // and last the secondary vtable pointers.
Mike Stump83066c82009-11-13 01:54:23 +00001274 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001275 }
1276
1277 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1278 /// built from each direct non-virtual proper base that requires a VTT in
1279 /// declaration order.
Mike Stump2cefe382009-11-12 20:47:57 +00001280 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1281 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001282 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1283 e = RD->bases_end(); i != e; ++i) {
1284 const CXXRecordDecl *Base =
1285 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1286 if (i->isVirtual())
1287 continue;
Mike Stump2cefe382009-11-12 20:47:57 +00001288 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1289 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1290 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001291 }
1292 }
1293
1294 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1295 /// graph preorder.
1296 void VirtualVTTs(const CXXRecordDecl *RD) {
1297 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1298 e = RD->bases_end(); i != e; ++i) {
1299 const CXXRecordDecl *Base =
1300 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1301 if (i->isVirtual() && !SeenVBase.count(Base)) {
1302 SeenVBase.insert(Base);
Mike Stump2cefe382009-11-12 20:47:57 +00001303 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1304 BuildVTT(Base, BaseOffset, true);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001305 }
1306 VirtualVTTs(Base);
1307 }
1308 }
Mike Stump9f23a142009-11-10 02:30:51 +00001309public:
1310 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001311 CodeGenModule &cgm)
1312 : Inits(inits), Class(c), CGM(cgm),
Mike Stump2cefe382009-11-12 20:47:57 +00001313 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stump83066c82009-11-13 01:54:23 +00001314 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump2cefe382009-11-12 20:47:57 +00001315 VMContext(cgm.getModule().getContext()) {
Mike Stumpd846d082009-11-10 07:44:33 +00001316
Mike Stump8b2d2d02009-11-11 00:35:07 +00001317 // First comes the primary virtual table pointer for the complete class...
Mike Stump2cefe382009-11-12 20:47:57 +00001318 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1319 Inits.push_back(ClassVtbl);
1320 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1321
Mike Stump8b2d2d02009-11-11 00:35:07 +00001322 // then the secondary VTTs...
1323 SecondaryVTTs(Class);
1324
1325 // then the secondary vtable pointers...
Mike Stump83066c82009-11-13 01:54:23 +00001326 Secondary(Class, ClassVtbl, Class);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001327
1328 // and last, the virtual VTTs.
1329 VirtualVTTs(Class);
Mike Stump9f23a142009-11-10 02:30:51 +00001330 }
1331};
Mike Stumpae1b85d2009-12-02 19:07:44 +00001332}
Mike Stump9f23a142009-11-10 02:30:51 +00001333
Mike Stumpd846d082009-11-10 07:44:33 +00001334llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpb4722212009-11-10 19:13:04 +00001335 // Only classes that have virtual bases need a VTT.
1336 if (RD->getNumVBases() == 0)
1337 return 0;
1338
Mike Stump9f23a142009-11-10 02:30:51 +00001339 llvm::SmallString<256> OutName;
Daniel Dunbare128dd12009-11-21 09:06:22 +00001340 getMangleContext().mangleCXXVTT(RD, OutName);
1341 llvm::StringRef Name = OutName.str();
Mike Stump9f23a142009-11-10 02:30:51 +00001342
1343 llvm::GlobalVariable::LinkageTypes linktype;
1344 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stumpaa51ad62009-11-19 04:04:36 +00001345 if (RD->isInAnonymousNamespace())
1346 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stump9f23a142009-11-10 02:30:51 +00001347 std::vector<llvm::Constant *> inits;
1348 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1349
Mike Stump9f23a142009-11-10 02:30:51 +00001350 D1(printf("vtt %s\n", RD->getNameAsCString()));
1351
Mike Stump8b2d2d02009-11-11 00:35:07 +00001352 VTTBuilder b(inits, RD, *this);
1353
Mike Stump9f23a142009-11-10 02:30:51 +00001354 llvm::Constant *C;
1355 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1356 C = llvm::ConstantArray::get(type, inits);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001357 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stumpaa51ad62009-11-19 04:04:36 +00001358 linktype, C, Name);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001359 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1360 if (Hidden)
1361 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1362 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stump9f23a142009-11-10 02:30:51 +00001363}
Mike Stumpd846d082009-11-10 07:44:33 +00001364
Mike Stump1a139f82009-11-19 01:08:19 +00001365void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1366 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpc01c2b82009-12-02 18:57:08 +00001367 CGM.GenerateRTTI(RD);
Mike Stump1a139f82009-11-19 01:08:19 +00001368 CGM.GenerateVTT(RD);
1369}
1370
Mike Stumpeac45592009-11-11 20:26:26 +00001371llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stumpd846d082009-11-10 07:44:33 +00001372 llvm::Constant *&vtbl = Vtables[RD];
1373 if (vtbl)
1374 return vtbl;
Mike Stump2cefe382009-11-12 20:47:57 +00001375 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001376
1377 bool CreateDefinition = true;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001378
1379 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1380 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001381 if (!KeyFunction->getBody()) {
1382 // If there is a KeyFunction, and it isn't defined, just build a
1383 // reference to the vtable.
1384 CreateDefinition = false;
1385 }
1386 }
1387
1388 if (CreateDefinition) {
Mike Stumpc01c2b82009-12-02 18:57:08 +00001389 CGM.GenerateRTTI(RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001390 CGM.GenerateVTT(RD);
1391 }
Mike Stumpd846d082009-11-10 07:44:33 +00001392 return vtbl;
1393}
Mike Stumpeac45592009-11-11 20:26:26 +00001394
Mike Stump2cefe382009-11-12 20:47:57 +00001395llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1396 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001397 uint64_t Offset) {
Mike Stump2cefe382009-11-12 20:47:57 +00001398 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stumpeac45592009-11-11 20:26:26 +00001399}
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001400
1401void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1402 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1403 const CXXRecordDecl *RD = MD->getParent();
1404
1405 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1406
1407 // Get the key function.
1408 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1409
1410 if (!KeyFunction) {
1411 // If there's no key function, we don't want to emit the vtable here.
1412 return;
1413 }
1414
1415 // Check if we have the key function.
1416 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1417 return;
1418
1419 // If the key function is a destructor, we only want to emit the vtable once,
1420 // so do it for the complete destructor.
1421 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1422 return;
1423
1424 // Emit the data.
1425 GenerateClassData(RD);
1426}
1427