blob: 007960e9983f36f8f27689ea38f7e225e59889a1 [file] [log] [blame]
Anders Carlssondbd920c2009-10-11 22:13:54 +00001//===--- CGVtable.cpp - Emit LLVM Code for C++ vtables --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000019#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000020
21using namespace clang;
22using namespace CodeGen;
23
Anders Carlsson27f69d02009-11-27 22:21:51 +000024namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000025class VtableBuilder {
Anders Carlssondbd920c2009-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 Stumpacfd1e52009-11-13 01:54:23 +000035 /// LayoutClass - The most derived class used for virtual base layout
36 /// information.
37 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +000038 /// LayoutOffset - The offset for Class in LayoutClass.
39 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-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 Carlssona0fdd912009-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 Stump9e7e3c62009-11-06 23:27:42 +000053 // This is the offset to the nearest virtual base
Anders Carlssona0fdd912009-11-13 17:08:56 +000054 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000055 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +000056
Anders Carlsson6d4ccb72009-11-26 19:54:33 +000057 /// PureVirtualFunction - Points to __cxa_pure_virtual.
58 llvm::Constant *PureVirtualFn;
59
Anders Carlssondb131512009-11-26 03:25:13 +000060 /// Thunk - Represents a single thunk.
61 struct Thunk {
Anders Carlsson3b908ce2009-12-03 02:41:55 +000062 Thunk() { }
Anders Carlssondb131512009-11-26 03:25:13 +000063
Anders Carlsson3b908ce2009-12-03 02:41:55 +000064 Thunk(GlobalDecl GD, const ThunkAdjustment &Adjustment)
65 : GD(GD), Adjustment(Adjustment) { }
Anders Carlssondb131512009-11-26 03:25:13 +000066
Anders Carlsson6fd247b2009-12-03 02:36:40 +000067 GlobalDecl GD;
68
Anders Carlsson5dd730a2009-11-26 19:32:45 +000069 /// Adjustment - The thunk adjustment.
Anders Carlssondb131512009-11-26 03:25:13 +000070 ThunkAdjustment Adjustment;
71 };
Anders Carlsson5dd730a2009-11-26 19:32:45 +000072
73 /// Thunks - The thunks in a vtable.
Anders Carlsson491b9552009-12-03 02:39:59 +000074 typedef llvm::DenseMap<uint64_t, Thunk> ThunksMapTy;
Anders Carlssondb131512009-11-26 03:25:13 +000075 ThunksMapTy Thunks;
Anders Carlsson5dd730a2009-11-26 19:32:45 +000076
77 /// CovariantThunk - Represents a single covariant thunk.
78 struct CovariantThunk {
Anders Carlsson1db4a9b2009-12-03 02:20:26 +000079 CovariantThunk() { }
80
Anders Carlsson1345f4a2009-12-03 02:34:59 +000081 CovariantThunk(GlobalDecl GD, CanQualType ReturnType)
82 : GD(GD), ReturnType(ReturnType) { }
Anders Carlsson5f96bc12009-12-03 02:16:14 +000083
Anders Carlssonbdd8e382009-12-03 02:03:29 +000084 GlobalDecl GD;
85
Anders Carlsson5dd730a2009-11-26 19:32:45 +000086 /// ReturnType - The return type of the function.
87 CanQualType ReturnType;
88 };
Anders Carlssondb131512009-11-26 03:25:13 +000089
Anders Carlsson5dd730a2009-11-26 19:32:45 +000090 /// CovariantThunks - The covariant thunks in a vtable.
Anders Carlssond6f7af52009-12-03 02:12:03 +000091 typedef llvm::DenseMap<uint64_t, CovariantThunk> CovariantThunksMapTy;
Anders Carlsson5dd730a2009-11-26 19:32:45 +000092 CovariantThunksMapTy CovariantThunks;
93
94 /// PureVirtualMethods - Pure virtual methods.
95 typedef llvm::DenseSet<GlobalDecl> PureVirtualMethodsSetTy;
96 PureVirtualMethodsSetTy PureVirtualMethods;
97
Anders Carlssondbd920c2009-10-11 22:13:54 +000098 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +000099
100 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +0000101 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
102 // vtable for use in computing the initializers for the VTT.
103 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +0000104
Anders Carlssondbd920c2009-10-11 22:13:54 +0000105 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000106 const bool Extern;
107 const uint32_t LLVMPointerWidth;
108 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +0000109 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +0000110 static llvm::DenseMap<CtorVtable_t, int64_t>&
111 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
112 const CXXRecordDecl *c) {
113 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
114 if (oref == 0)
115 oref = new CodeGenModule::AddrMap_t;
116
117 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
118 if (ref == 0)
119 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
120 return *ref;
121 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000122
123 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
124 llvm::Constant* getPureVirtualFn() {
125 if (!PureVirtualFn) {
126 const llvm::FunctionType *Ty =
127 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
128 /*isVarArg=*/false);
129 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
130 }
131
132 return PureVirtualFn;
133 }
134
Anders Carlssondbd920c2009-10-11 22:13:54 +0000135public:
Mike Stump4cde6262009-11-13 02:13:54 +0000136 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
137 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
138 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stumpacfd1e52009-11-13 01:54:23 +0000139 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpde050572009-12-02 18:57:08 +0000140 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000141 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump6be2b172009-11-19 00:49:05 +0000142 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000143 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000144 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
145 }
146
Anders Carlssona0fdd912009-11-13 17:08:56 +0000147 llvm::DenseMap<GlobalDecl, Index_t> &getIndex() { return Index; }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000148 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
149 { return VBIndex; }
150
151 llvm::Constant *wrap(Index_t i) {
152 llvm::Constant *m;
153 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
154 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
155 }
156
157 llvm::Constant *wrap(llvm::Constant *m) {
158 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
159 }
160
Mike Stump79336282009-12-02 19:50:41 +0000161#define D1(x)
162//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +0000163
164 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +0000165 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000166 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
167 e = RD->bases_end(); i != e; ++i) {
168 const CXXRecordDecl *Base =
169 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +0000170 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000171 if (i->isVirtual() && !SeenVBase.count(Base)) {
172 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +0000173 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000174 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +0000175 - 3*LLVMPointerWidth/8);
176 VBIndex[Base] = next_vbindex;
177 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000178 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
179 VCalls.push_back((0?700:0) + BaseOffset);
180 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
181 Base->getNameAsCString(),
182 (int)-VCalls.size()-3, (int)BaseOffset,
183 Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000184 }
Mike Stumpab28c132009-10-13 22:54:56 +0000185 // We also record offsets for non-virtual bases to closest enclosing
186 // virtual base. We do this so that we don't have to search
187 // for the nearst virtual base class when generating thunks.
188 if (updateVBIndex && VBIndex.count(Base) == 0)
189 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +0000190 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000191 }
192 }
193
194 void StartNewTable() {
195 SeenVBase.clear();
196 }
197
Mike Stump3425b972009-10-15 09:30:16 +0000198 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
199 Index_t Offset = 0) {
200
201 if (B == D)
202 return Offset;
203
204 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
205 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
206 e = D->bases_end(); i != e; ++i) {
207 const CXXRecordDecl *Base =
208 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
209 int64_t BaseOffset = 0;
210 if (!i->isVirtual())
211 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
212 int64_t o = getNVOffset_1(Base, B, BaseOffset);
213 if (o >= 0)
214 return o;
215 }
216
217 return -1;
218 }
219
220 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
221 /// derived class D.
222 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000223 qD = qD->getPointeeType();
224 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +0000225 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
226 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
227 int64_t o = getNVOffset_1(D, B);
228 if (o >= 0)
229 return o;
230
231 assert(false && "FIXME: non-virtual base not found");
232 return 0;
233 }
234
Anders Carlssondbd920c2009-10-11 22:13:54 +0000235 /// getVbaseOffset - Returns the index into the vtable for the virtual base
236 /// offset for the given (B) virtual base of the derived class D.
237 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000238 qD = qD->getPointeeType();
239 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000240 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
241 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
242 if (D != Class)
Eli Friedman76ed1f72009-11-30 01:19:33 +0000243 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000244 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
245 i = VBIndex.find(B);
246 if (i != VBIndex.end())
247 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000248
Mike Stumpab28c132009-10-13 22:54:56 +0000249 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +0000250 return 0;
251 }
252
Anders Carlssona0fdd912009-11-13 17:08:56 +0000253 bool OverrideMethod(GlobalDecl GD, llvm::Constant *m,
Mike Stump3425b972009-10-15 09:30:16 +0000254 bool MorallyVirtual, Index_t OverrideOffset,
Anders Carlsson27682a32009-12-03 01:54:02 +0000255 Index_t Offset, int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000256
257 void InstallThunks() {
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000258 for (CovariantThunksMapTy::const_iterator i = CovariantThunks.begin(),
259 e = CovariantThunks.end(); i != e; ++i) {
Anders Carlssond6f7af52009-12-03 02:12:03 +0000260 GlobalDecl GD = i->second.GD;
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000261 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
262 if (MD->isPure())
263 continue;
264
Anders Carlsson5f96bc12009-12-03 02:16:14 +0000265 uint64_t Index = i->first;
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000266 const CovariantThunk &Thunk = i->second;
Anders Carlsson5f96bc12009-12-03 02:16:14 +0000267 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000268
269 // Check if there is an adjustment for the 'this' pointer.
270 ThunkAdjustment ThisAdjustment;
Anders Carlsson491b9552009-12-03 02:39:59 +0000271 ThunksMapTy::iterator i = Thunks.find(Index);
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000272 if (i != Thunks.end()) {
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000273 ThisAdjustment = i->second.Adjustment;
274
275 Thunks.erase(i);
276 }
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000277
278 // Construct the return adjustment.
Anders Carlsson1750b4f2009-12-03 03:28:24 +0000279 QualType DerivedType =
280 MD->getType()->getAs<FunctionType>()->getResultType();
281
282 int64_t NonVirtualAdjustment =
283 getNVOffset(Thunk.ReturnType, DerivedType) / 8;
284
285 int64_t VirtualAdjustment =
286 getVbaseOffset(Thunk.ReturnType, DerivedType);
287
288 ThunkAdjustment ReturnAdjustment(NonVirtualAdjustment, VirtualAdjustment);
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000289
290 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson5f96bc12009-12-03 02:16:14 +0000291 submethods[Index] = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000292 }
293 CovariantThunks.clear();
Anders Carlssonbdd8e382009-12-03 02:03:29 +0000294
Anders Carlssondb131512009-11-26 03:25:13 +0000295 for (ThunksMapTy::const_iterator i = Thunks.begin(), e = Thunks.end();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000296 i != e; ++i) {
Anders Carlsson3b908ce2009-12-03 02:41:55 +0000297 uint64_t Index = i->first;
298 const Thunk& Thunk = i->second;
299
300 GlobalDecl GD = Thunk.GD;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000301 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssondb131512009-11-26 03:25:13 +0000302 assert(!MD->isPure() && "Can't thunk pure virtual methods!");
Anders Carlsson491b9552009-12-03 02:39:59 +0000303
304 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlssondb131512009-11-26 03:25:13 +0000305
Anders Carlsson3b908ce2009-12-03 02:41:55 +0000306 submethods[Index] = CGM.BuildThunk(MD, Extern, Thunk.Adjustment);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000307 }
308 Thunks.clear();
Anders Carlssondb131512009-11-26 03:25:13 +0000309
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000310 for (PureVirtualMethodsSetTy::iterator i = PureVirtualMethods.begin(),
311 e = PureVirtualMethods.end(); i != e; ++i) {
312 GlobalDecl GD = *i;
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000313 submethods[Index[GD]] = getPureVirtualFn();
Mike Stump94aff932009-10-27 23:46:47 +0000314 }
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000315 PureVirtualMethods.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000316 }
317
Anders Carlssona0fdd912009-11-13 17:08:56 +0000318 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
319 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
320
Mike Stump1ae31782009-10-27 23:36:26 +0000321 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD))
Anders Carlssona0fdd912009-11-13 17:08:56 +0000322 return wrap(CGM.GetAddrOfCXXDestructor(Dtor, GD.getDtorType()));
Mike Stump1ae31782009-10-27 23:36:26 +0000323
Anders Carlssonecf282b2009-11-24 05:08:52 +0000324 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +0000325
326 return wrap(CGM.GetAddrOfFunction(MD, Ty));
327 }
328
Mike Stump9e7e3c62009-11-06 23:27:42 +0000329 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
330 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +0000331 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +0000332 e = Path->rend(); i != e; ++i) {
333 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +0000334 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000335 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
336 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000337 const CXXMethodDecl *MD = *mi;
338
339 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +0000340 continue;
341
Anders Carlssona0fdd912009-11-13 17:08:56 +0000342 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
343 // Override both the complete and the deleting destructor.
344 GlobalDecl CompDtor(DD, Dtor_Complete);
345 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
346 OverrideOffset, Offset, CurrentVBaseOffset);
347
348 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
349 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
350 OverrideOffset, Offset, CurrentVBaseOffset);
351 } else {
352 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
353 Offset, CurrentVBaseOffset);
354 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000355 }
356 }
357 }
358
Anders Carlssona0fdd912009-11-13 17:08:56 +0000359 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000360 int64_t CurrentVBaseOffset) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000361 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump1ae31782009-10-27 23:36:26 +0000362
Anders Carlssondbd920c2009-10-11 22:13:54 +0000363 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssona0fdd912009-11-13 17:08:56 +0000364 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000365 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +0000366 return;
367
Anders Carlssona0fdd912009-11-13 17:08:56 +0000368 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
369
Anders Carlssondbd920c2009-10-11 22:13:54 +0000370 // else allocate a new slot.
Anders Carlssona0fdd912009-11-13 17:08:56 +0000371 Index[GD] = submethods.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000372 submethods.push_back(m);
Mike Stumpe99cc452009-11-13 23:45:53 +0000373 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
374 (int)Index[GD]));
Mike Stump7809e0d2009-10-28 00:35:46 +0000375 if (MD->isPure())
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000376 PureVirtualMethods.insert(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000377 if (MorallyVirtual) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000378 VCallOffset[GD] = Offset/8;
379 Index_t &idx = VCall[GD];
Anders Carlssondbd920c2009-10-11 22:13:54 +0000380 // Allocate the first one, after that, we reuse the previous one.
381 if (idx == 0) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000382 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000383 idx = VCalls.size()+1;
384 VCalls.push_back(0);
Mike Stump6a9612f2009-10-31 20:06:59 +0000385 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpe99cc452009-11-13 23:45:53 +0000386 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000387 }
388 }
389 }
390
391 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000392 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000393 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000394 ++mi) {
395 const CXXMethodDecl *MD = *mi;
396 if (!MD->isVirtual())
397 continue;
398
399 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
400 // For destructors, add both the complete and the deleting destructor
401 // to the vtable.
402 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000403 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +0000404 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
405 CurrentVBaseOffset);
406 } else
407 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000408 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000409 }
410
411 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
412 const CXXRecordDecl *PrimaryBase,
413 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000414 int64_t Offset, int64_t CurrentVBaseOffset,
415 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000416 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000417 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
418 e = RD->bases_end(); i != e; ++i) {
419 if (i->isVirtual())
420 continue;
421 const CXXRecordDecl *Base =
422 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
423 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
424 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
425 StartNewTable();
Mike Stump4cde6262009-11-13 02:13:54 +0000426 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000427 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000428 }
429 }
Mike Stump11dea942009-10-15 02:04:03 +0000430 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000431 }
432
Mike Stump0ca42792009-10-14 18:14:51 +0000433// #define D(X) do { X; } while (0)
434#define D(X)
435
436 void insertVCalls(int InsertionPoint) {
437 llvm::Constant *e = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000438 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +0000439 D(VCalls.insert(VCalls.begin(), 673));
440 D(VCalls.push_back(672));
Mike Stump3425b972009-10-15 09:30:16 +0000441 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stump0ca42792009-10-14 18:14:51 +0000442 // The vcalls come first...
443 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
444 e = VCalls.rend();
445 i != e; ++i)
446 methods[InsertionPoint++] = wrap((0?600:0) + *i);
447 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +0000448 VCall.clear();
Mike Stump0ca42792009-10-14 18:14:51 +0000449 }
450
Mike Stump65d0e282009-11-13 23:13:20 +0000451 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
452 Index_t AddressPoint) {
453 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
454 RD->getNameAsCString(), Class->getNameAsCString(),
455 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000456 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000457
458 // Now also add the address point for all our primary bases.
459 while (1) {
460 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
461 RD = Layout.getPrimaryBase();
462 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
463 // FIXME: Double check this.
464 if (RD == 0)
465 break;
466 if (PrimaryBaseWasVirtual &&
467 BLayout.getVBaseClassOffset(RD) != Offset)
468 break;
469 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
470 RD->getNameAsCString(), Class->getNameAsCString(),
471 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000472 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000473 }
474 }
475
476
Mike Stump6a9612f2009-10-31 20:06:59 +0000477 Index_t end(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
478 const CXXRecordDecl *PrimaryBase, bool PrimaryBaseWasVirtual,
479 bool MorallyVirtual, int64_t Offset, bool ForVirtualBase,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000480 int64_t CurrentVBaseOffset,
Mike Stump6a9612f2009-10-31 20:06:59 +0000481 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000482 bool alloc = false;
483 if (Path == 0) {
484 alloc = true;
485 Path = new Path_t;
486 }
487
Anders Carlssondbd920c2009-10-11 22:13:54 +0000488 StartNewTable();
489 extra = 0;
Mike Stump0ca42792009-10-14 18:14:51 +0000490 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
491 int VCallInsertionPoint = methods.size();
492 if (!DeferVCalls) {
493 insertVCalls(VCallInsertionPoint);
Mike Stump3425b972009-10-15 09:30:16 +0000494 } else
495 // FIXME: just for extra, or for all uses of VCalls.size post this?
496 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000497
Mike Stump4cde6262009-11-13 02:13:54 +0000498 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000499 methods.push_back(rtti);
500 Index_t AddressPoint = methods.size();
501
502 InstallThunks();
Mike Stump6a9612f2009-10-31 20:06:59 +0000503 D1(printf("============= combining methods\n"));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000504 methods.insert(methods.end(), submethods.begin(), submethods.end());
505 submethods.clear();
506
507 // and then the non-virtual bases.
508 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000509 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +0000510
511 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +0000512 // FIXME: We're adding to VCalls in callers, we need to do the overrides
513 // in the inner part, so that we know the complete set of vcalls during
514 // the build and don't have to insert into methods. Saving out the
515 // AddressPoint here, would need to be fixed, if we didn't do that. Also
516 // retroactively adding vcalls for overrides later wind up in the wrong
517 // place, the vcall slot has to be alloted during the walk of the base
518 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +0000519 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +0000520 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +0000521 }
522
Mike Stump65d0e282009-11-13 23:13:20 +0000523 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +0000524
Mike Stump11dea942009-10-15 02:04:03 +0000525 if (alloc) {
526 delete Path;
527 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000528 return AddressPoint;
529 }
530
Mike Stump6a9612f2009-10-31 20:06:59 +0000531 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
532 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000533 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000534 if (!RD->isDynamicClass())
535 return;
536
537 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
538 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
539 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
540
541 // vtables are composed from the chain of primaries.
542 if (PrimaryBase) {
543 D1(printf(" doing primaries for %s most derived %s\n",
544 RD->getNameAsCString(), Class->getNameAsCString()));
545
Mike Stump9e7e3c62009-11-06 23:27:42 +0000546 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
547 if (PrimaryBaseWasVirtual)
548 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
549
Mike Stump6a9612f2009-10-31 20:06:59 +0000550 if (!PrimaryBaseWasVirtual)
551 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000552 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000553 }
554
555 D1(printf(" doing vcall entries for %s most derived %s\n",
556 RD->getNameAsCString(), Class->getNameAsCString()));
557
558 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +0000559 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000560 }
561
562 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
563 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000564 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000565 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000566 if (!RD->isDynamicClass())
567 return;
568
569 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
570 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
571 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
572
573 // vtables are composed from the chain of primaries.
574 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +0000575 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
576 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000577 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000578 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
579 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000580
581 D1(printf(" doing primaries for %s most derived %s\n",
582 RD->getNameAsCString(), Class->getNameAsCString()));
583
584 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000585 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000586 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000587 }
588
Mike Stump6a9612f2009-10-31 20:06:59 +0000589 D1(printf(" doing vbase entries for %s most derived %s\n",
590 RD->getNameAsCString(), Class->getNameAsCString()));
591 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
592
593 if (RDisVirtualBase || bottom) {
594 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000595 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000596 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000597 }
598
Mike Stump4cde6262009-11-13 02:13:54 +0000599 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
600 bool MorallyVirtual = false,
Anders Carlssondbd920c2009-10-11 22:13:54 +0000601 bool ForVirtualBase = false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000602 int CurrentVBaseOffset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000603 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000604 if (!RD->isDynamicClass())
605 return 0;
606
Mike Stump92774d12009-11-13 02:35:38 +0000607 // Construction vtable don't need parts that have no virtual bases and
608 // aren't morally virtual.
609 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
610 return 0;
611
Anders Carlssondbd920c2009-10-11 22:13:54 +0000612 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
613 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
614 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
615
Anders Carlssondbd920c2009-10-11 22:13:54 +0000616 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000617 D1(printf("building entries for base %s most derived %s\n",
618 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000619
Mike Stump6a9612f2009-10-31 20:06:59 +0000620 if (ForVirtualBase)
621 extra = VCalls.size();
622
623 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000624 CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000625
626 if (Path)
Mike Stump9e7e3c62009-11-06 23:27:42 +0000627 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000628
Mike Stump6a9612f2009-10-31 20:06:59 +0000629 return end(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual, MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000630 Offset, ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000631 }
632
633 void GenerateVtableForVBases(const CXXRecordDecl *RD,
634 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000635 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000636 bool alloc = false;
637 if (Path == 0) {
638 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +0000639 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000640 }
641 // FIXME: We also need to override using all paths to a virtual base,
642 // right now, we just process the first path
643 Path->push_back(std::make_pair(RD, Offset));
644 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
645 e = RD->bases_end(); i != e; ++i) {
646 const CXXRecordDecl *Base =
647 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
648 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
649 // Mark it so we don't output it twice.
650 IndirectPrimary.insert(Base);
651 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +0000652 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000653 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000654 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +0000655 D1(printf("vtable %s virtual base %s\n",
656 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump4cde6262009-11-13 02:13:54 +0000657 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000658 Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000659 }
Mike Stump9840c702009-11-12 20:47:57 +0000660 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000661 if (i->isVirtual())
662 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +0000663 else {
664 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
665 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
666 }
667
Mike Stump11dea942009-10-15 02:04:03 +0000668 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000669 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +0000670 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000671 }
672 Path->pop_back();
673 if (alloc)
674 delete Path;
675 }
676};
Anders Carlsson27682a32009-12-03 01:54:02 +0000677} // end anonymous namespace
678
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000679/// TypeConversionRequiresAdjustment - Returns whether conversion from a
680/// derived type to a base type requires adjustment.
681static bool
682TypeConversionRequiresAdjustment(ASTContext &Ctx,
683 const CXXRecordDecl *DerivedDecl,
684 const CXXRecordDecl *BaseDecl) {
685 CXXBasePaths Paths(/*FindAmbiguities=*/false,
686 /*RecordPaths=*/true, /*DetectVirtual=*/true);
687 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
688 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
689 assert(false && "Class must be derived from the passed in base class!");
690 return false;
691 }
692
693 // If we found a virtual base we always want to require adjustment.
694 if (Paths.getDetectedVirtual())
695 return true;
696
697 const CXXBasePath &Path = Paths.front();
698
699 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
700 const CXXBasePathElement &Element = Path[Start];
701
702 // Check the base class offset.
703 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
704
705 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
706 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
707
708 if (Layout.getBaseClassOffset(Base) != 0) {
709 // This requires an adjustment.
710 return true;
711 }
712 }
713
714 return false;
715}
716
717static bool
718TypeConversionRequiresAdjustment(ASTContext &Ctx,
719 QualType DerivedType, QualType BaseType) {
720 // Canonicalize the types.
721 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
722 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
723
724 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
725 "Types must have same type class!");
726
727 if (CanDerivedType == CanBaseType) {
728 // No adjustment needed.
729 return false;
730 }
731
732 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
733 CanDerivedType = RT->getPointeeType();
734 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
735 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
736 CanDerivedType = PT->getPointeeType();
737 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
738 } else {
739 assert(false && "Unexpected return type!");
740 }
741
742 if (CanDerivedType == CanBaseType) {
743 // No adjustment needed.
744 return false;
745 }
746
747 const CXXRecordDecl *DerivedDecl =
Anders Carlsson1750b4f2009-12-03 03:28:24 +0000748 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000749
750 const CXXRecordDecl *BaseDecl =
751 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
752
753 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
754}
755
Anders Carlsson27682a32009-12-03 01:54:02 +0000756bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
757 bool MorallyVirtual, Index_t OverrideOffset,
758 Index_t Offset, int64_t CurrentVBaseOffset) {
759 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
760
761 const bool isPure = MD->isPure();
762 typedef CXXMethodDecl::method_iterator meth_iter;
763 // FIXME: Should OverrideOffset's be Offset?
764
765 // FIXME: Don't like the nested loops. For very large inheritance
766 // heirarchies we could have a table on the side with the final overridder
767 // and just replace each instance of an overridden method once. Would be
768 // nice to measure the cost/benefit on real code.
769
770 for (meth_iter mi = MD->begin_overridden_methods(),
771 e = MD->end_overridden_methods();
772 mi != e; ++mi) {
773 GlobalDecl OGD;
774
775 const CXXMethodDecl *OMD = *mi;
776 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
777 OGD = GlobalDecl(DD, GD.getDtorType());
778 else
779 OGD = OMD;
780
781 llvm::Constant *om;
782 om = WrapAddrOf(OGD);
783 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
784
785 for (Index_t i = 0, e = submethods.size();
786 i != e; ++i) {
787 // FIXME: begin_overridden_methods might be too lax, covariance */
788 if (submethods[i] != om)
789 continue;
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000790
791 QualType ReturnType =
792 MD->getType()->getAs<FunctionType>()->getResultType();
793 QualType OverriddenReturnType =
794 OMD->getType()->getAs<FunctionType>()->getResultType();
795
796 // Check if we need a return type adjustment.
797 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
798 OverriddenReturnType)) {
799 CovariantThunk &Adjustment = CovariantThunks[i];
Anders Carlssonbc0e3392009-12-03 02:22:59 +0000800
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000801 // Get the canonical return type.
802 CanQualType CanReturnType =
803 CGM.getContext().getCanonicalType(ReturnType);
804
805 // Insert the base return type.
806 if (Adjustment.ReturnType.isNull())
807 Adjustment.ReturnType =
808 CGM.getContext().getCanonicalType(OverriddenReturnType);
809
810 Adjustment.GD = GD;
Anders Carlsson27682a32009-12-03 01:54:02 +0000811 }
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000812
Anders Carlsson27682a32009-12-03 01:54:02 +0000813 Index[GD] = i;
814 submethods[i] = m;
815 if (isPure)
816 PureVirtualMethods.insert(GD);
817 PureVirtualMethods.erase(OGD);
Anders Carlsson491b9552009-12-03 02:39:59 +0000818 Thunks.erase(i);
Anders Carlsson27682a32009-12-03 01:54:02 +0000819 if (MorallyVirtual || VCall.count(OGD)) {
820 Index_t &idx = VCall[OGD];
821 if (idx == 0) {
822 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
823 VCallOffset[GD] = OverrideOffset/8;
824 idx = VCalls.size()+1;
825 VCalls.push_back(0);
826 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
827 MD->getNameAsString().c_str(), (int)-idx-3,
828 (int)VCalls[idx-1], Class->getNameAsCString()));
829 } else {
830 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
831 VCallOffset[GD] = VCallOffset[OGD];
832 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
833 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
834 MD->getNameAsString().c_str(), (int)-idx-3,
835 (int)VCalls[idx-1], Class->getNameAsCString()));
836 }
837 VCall[GD] = idx;
838 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
839 int64_t VirtualAdjustment =
840 -((idx + extra + 2) * LLVMPointerWidth / 8);
841
842 // Optimize out virtual adjustments of 0.
843 if (VCalls[idx-1] == 0)
844 VirtualAdjustment = 0;
845
846 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
847 VirtualAdjustment);
848
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000849 if (!isPure && !ThisAdjustment.isEmpty())
Anders Carlsson3b908ce2009-12-03 02:41:55 +0000850 Thunks[i] = Thunk(GD, ThisAdjustment);
Anders Carlsson27682a32009-12-03 01:54:02 +0000851 return true;
852 }
853
854 // FIXME: finish off
855 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
856
Anders Carlssonbc0e3392009-12-03 02:22:59 +0000857 if (NonVirtualAdjustment) {
Anders Carlsson27682a32009-12-03 01:54:02 +0000858 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
859
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000860 if (!isPure)
Anders Carlsson3b908ce2009-12-03 02:41:55 +0000861 Thunks[i] = Thunk(GD, ThisAdjustment);
Anders Carlsson27682a32009-12-03 01:54:02 +0000862 }
863 return true;
864 }
865 }
866
867 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +0000868}
869
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000870void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
871
872 // Itanium C++ ABI 2.5.2:
873 // The order of the virtual function pointers in a virtual table is the
874 // order of declaration of the corresponding member functions in the class.
875 //
876 // There is an entry for any virtual function declared in a class,
877 // whether it is a new function or overrides a base class function,
878 // unless it overrides a function from the primary base, and conversion
879 // between their return types does not require an adjustment.
880
881 int64_t CurrentIndex = 0;
882
883 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
884 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
885
886 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +0000887 assert(PrimaryBase->isDefinition() &&
888 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000889
890 // Since the record decl shares its vtable pointer with the primary base
891 // we need to start counting at the end of the primary base's vtable.
892 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
893 }
894
895 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
896
897 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
898 e = RD->method_end(); i != e; ++i) {
899 const CXXMethodDecl *MD = *i;
900
901 // We only want virtual methods.
902 if (!MD->isVirtual())
903 continue;
904
905 bool ShouldAddEntryForMethod = true;
906
907 // Check if this method overrides a method in the primary base.
908 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
909 e = MD->end_overridden_methods(); i != e; ++i) {
910 const CXXMethodDecl *OverriddenMD = *i;
911 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
912 assert(OverriddenMD->isCanonicalDecl() &&
913 "Should have the canonical decl of the overridden RD!");
914
915 if (OverriddenRD == PrimaryBase) {
916 // Check if converting from the return type of the method to the
917 // return type of the overridden method requires conversion.
918 QualType ReturnType =
919 MD->getType()->getAs<FunctionType>()->getResultType();
920 QualType OverriddenReturnType =
921 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
922
923 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
924 ReturnType, OverriddenReturnType)) {
925 // This index is shared between the index in the vtable of the primary
926 // base class.
927 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
928 const CXXDestructorDecl *OverriddenDD =
929 cast<CXXDestructorDecl>(OverriddenMD);
930
931 // Add both the complete and deleting entries.
932 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
933 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
934 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
935 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
936 } else {
937 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
938 }
939
940 // We don't need to add an entry for this method.
941 ShouldAddEntryForMethod = false;
942 break;
943 }
944 }
945 }
946
947 if (!ShouldAddEntryForMethod)
948 continue;
949
950 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
951 if (MD->isImplicit()) {
952 assert(!ImplicitVirtualDtor &&
953 "Did already see an implicit virtual dtor!");
954 ImplicitVirtualDtor = DD;
955 continue;
956 }
957
958 // Add the complete dtor.
959 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
960
961 // Add the deleting dtor.
962 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
963 } else {
964 // Add the entry.
965 MethodVtableIndices[MD] = CurrentIndex++;
966 }
967 }
968
969 if (ImplicitVirtualDtor) {
970 // Itanium C++ ABI 2.5.2:
971 // If a class has an implicitly-defined virtual destructor,
972 // its entries come after the declared virtual function pointers.
973
974 // Add the complete dtor.
975 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
976 CurrentIndex++;
977
978 // Add the deleting dtor.
979 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
980 CurrentIndex++;
981 }
982
983 NumVirtualFunctionPointers[RD] = CurrentIndex;
984}
985
986uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
987 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
988 NumVirtualFunctionPointers.find(RD);
989 if (I != NumVirtualFunctionPointers.end())
990 return I->second;
991
992 ComputeMethodVtableIndices(RD);
993
994 I = NumVirtualFunctionPointers.find(RD);
995 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
996 return I->second;
997}
998
999uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00001000 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001001 if (I != MethodVtableIndices.end())
1002 return I->second;
1003
Anders Carlssona0fdd912009-11-13 17:08:56 +00001004 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001005
1006 ComputeMethodVtableIndices(RD);
1007
Anders Carlssona0fdd912009-11-13 17:08:56 +00001008 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001009 assert(I != MethodVtableIndices.end() && "Did not find index!");
1010 return I->second;
1011}
1012
1013int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1014 const CXXRecordDecl *VBase) {
1015 ClassPairTy ClassPair(RD, VBase);
1016
1017 VirtualBaseClassIndiciesTy::iterator I =
1018 VirtualBaseClassIndicies.find(ClassPair);
1019 if (I != VirtualBaseClassIndicies.end())
1020 return I->second;
1021
1022 std::vector<llvm::Constant *> methods;
1023 // FIXME: This seems expensive. Can we do a partial job to get
1024 // just this data.
Mike Stump4cde6262009-11-13 02:13:54 +00001025 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump6a9612f2009-10-31 20:06:59 +00001026 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001027 b.GenerateVtableForBase(RD);
1028 b.GenerateVtableForVBases(RD);
1029
1030 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1031 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1032 // Insert all types.
1033 ClassPairTy ClassPair(RD, I->first);
1034
1035 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1036 }
1037
1038 I = VirtualBaseClassIndicies.find(ClassPair);
1039 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1040
1041 return I->second;
1042}
1043
Mike Stump9840c702009-11-12 20:47:57 +00001044llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1045 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001046 uint64_t Offset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001047 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00001048 if (LayoutClass != RD)
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001049 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00001050 else
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001051 getMangleContext().mangleCXXVtable(RD, OutName);
1052 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00001053
Anders Carlssondbd920c2009-10-11 22:13:54 +00001054 std::vector<llvm::Constant *> methods;
1055 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1056 int64_t AddressPoint;
1057
Mike Stump85615df2009-11-19 04:04:36 +00001058 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stump23a35422009-11-19 20:52:19 +00001059 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stump85615df2009-11-19 04:04:36 +00001060 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1061 Offset)];
Mike Stump23a35422009-11-19 20:52:19 +00001062 // FIXME: We can never have 0 address point. Do this for now so gepping
1063 // retains the same structure. Later, we'll just assert.
1064 if (AddressPoint == 0)
1065 AddressPoint = 1;
1066 } else {
Mike Stump85615df2009-11-19 04:04:36 +00001067 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001068
Mike Stump85615df2009-11-19 04:04:36 +00001069 D1(printf("vtable %s\n", RD->getNameAsCString()));
1070 // First comes the vtables for all the non-virtual bases...
1071 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001072
Mike Stump85615df2009-11-19 04:04:36 +00001073 // then the vtables for all the virtual bases.
1074 b.GenerateVtableForVBases(RD, Offset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001075
Mike Stump85615df2009-11-19 04:04:36 +00001076 bool CreateDefinition = true;
1077 if (LayoutClass != RD)
1078 CreateDefinition = true;
1079 else {
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001080 const ASTRecordLayout &Layout =
1081 getContext().getASTRecordLayout(LayoutClass);
1082
1083 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001084 if (!KeyFunction->getBody()) {
1085 // If there is a KeyFunction, and it isn't defined, just build a
1086 // reference to the vtable.
1087 CreateDefinition = false;
1088 }
1089 }
1090 }
1091
1092 llvm::Constant *C = 0;
1093 llvm::Type *type = Ptr8Ty;
1094 llvm::GlobalVariable::LinkageTypes linktype
1095 = llvm::GlobalValue::ExternalLinkage;
1096 if (CreateDefinition) {
1097 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1098 C = llvm::ConstantArray::get(ntype, methods);
1099 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1100 if (LayoutClass->isInAnonymousNamespace())
1101 linktype = llvm::GlobalValue::InternalLinkage;
1102 type = ntype;
1103 }
1104 llvm::GlobalVariable *OGV = GV;
1105 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1106 if (OGV) {
1107 GV->takeName(OGV);
1108 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1109 OGV->getType());
1110 OGV->replaceAllUsesWith(NewPtr);
1111 OGV->eraseFromParent();
1112 }
1113 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1114 if (Hidden)
1115 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1116 }
Mike Stumpe56ceca2009-11-18 04:00:48 +00001117 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stump380dd752009-11-10 07:44:33 +00001118 llvm::Constant *AddressPointC;
1119 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1120 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1121 AddressPoint*LLVMPointerWidth/8);
Mike Stump9840c702009-11-12 20:47:57 +00001122 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1123 1);
Mike Stump380dd752009-11-10 07:44:33 +00001124
Mike Stump23a35422009-11-19 20:52:19 +00001125 assert(vtable->getType() == Ptr8Ty);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001126 return vtable;
1127}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001128
Mike Stump92f2fe22009-12-02 19:07:44 +00001129namespace {
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001130class VTTBuilder {
1131 /// Inits - The list of values built for the VTT.
1132 std::vector<llvm::Constant *> &Inits;
1133 /// Class - The most derived class that this vtable is being built for.
1134 const CXXRecordDecl *Class;
1135 CodeGenModule &CGM; // Per-module state.
Mike Stump971977f2009-11-11 00:35:07 +00001136 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpaee8de32009-11-11 03:08:24 +00001137 /// BLayout - Layout for the most derived class that this vtable is being
1138 /// built for.
1139 const ASTRecordLayout &BLayout;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001140 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +00001141 // vtbl - A pointer to the vtable for Class.
1142 llvm::Constant *ClassVtbl;
1143 llvm::LLVMContext &VMContext;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001144
Mike Stump28f7ce12009-11-12 22:56:32 +00001145 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stumpacfd1e52009-11-13 01:54:23 +00001146 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1147 const CXXRecordDecl *VtblClass,
1148 const CXXRecordDecl *RD,
Mike Stump28f7ce12009-11-12 22:56:32 +00001149 uint64_t Offset) {
1150 int64_t AddressPoint;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001151 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump80ac2352009-11-12 23:36:21 +00001152 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stump23a35422009-11-19 20:52:19 +00001153 // retains the same structure. Later we'll just assert.
Mike Stump80ac2352009-11-12 23:36:21 +00001154 if (AddressPoint == 0)
1155 AddressPoint = 1;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001156 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1157 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1158 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump28f7ce12009-11-12 22:56:32 +00001159 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1160 llvm::Constant *init;
1161 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1162 AddressPoint*LLVMPointerWidth/8);
1163 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1164 return init;
1165 }
1166
Mike Stump9840c702009-11-12 20:47:57 +00001167 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1168 /// current offset in bits to the object we're working on.
Mike Stump28f7ce12009-11-12 22:56:32 +00001169 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stumpacfd1e52009-11-13 01:54:23 +00001170 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1171 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001172 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1173 return;
1174
1175 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1176 e = RD->bases_end(); i != e; ++i) {
1177 const CXXRecordDecl *Base =
1178 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1179 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1180 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1181 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1182 bool NonVirtualPrimaryBase;
1183 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1184 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpaee8de32009-11-11 03:08:24 +00001185 uint64_t BaseOffset;
1186 if (!i->isVirtual()) {
1187 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1188 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1189 } else
1190 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump80ac2352009-11-12 23:36:21 +00001191 llvm::Constant *subvtbl = vtbl;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001192 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump971977f2009-11-11 00:35:07 +00001193 if ((Base->getNumVBases() || BaseMorallyVirtual)
1194 && !NonVirtualPrimaryBase) {
1195 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump28f7ce12009-11-12 22:56:32 +00001196 llvm::Constant *init;
Mike Stump80ac2352009-11-12 23:36:21 +00001197 if (BaseMorallyVirtual)
Mike Stumpacfd1e52009-11-13 01:54:23 +00001198 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump80ac2352009-11-12 23:36:21 +00001199 else {
Mike Stump28f7ce12009-11-12 22:56:32 +00001200 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump80ac2352009-11-12 23:36:21 +00001201 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stumpacfd1e52009-11-13 01:54:23 +00001202 subVtblClass = Base;
Mike Stump80ac2352009-11-12 23:36:21 +00001203 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001204 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001205 }
Mike Stumpacfd1e52009-11-13 01:54:23 +00001206 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001207 }
1208 }
1209
Mike Stump9840c702009-11-12 20:47:57 +00001210 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1211 /// currnet object we're working on.
1212 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump971977f2009-11-11 00:35:07 +00001213 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1214 return;
1215
Mike Stump9840c702009-11-12 20:47:57 +00001216 llvm::Constant *init;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001217 const CXXRecordDecl *VtblClass;
1218
Mike Stump971977f2009-11-11 00:35:07 +00001219 // First comes the primary virtual table pointer...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001220 if (MorallyVirtual) {
1221 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1222 VtblClass = Class;
1223 } else {
Mike Stump9840c702009-11-12 20:47:57 +00001224 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stumpacfd1e52009-11-13 01:54:23 +00001225 VtblClass = RD;
1226 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001227 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump9840c702009-11-12 20:47:57 +00001228 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001229
1230 // then the secondary VTTs....
Mike Stump9840c702009-11-12 20:47:57 +00001231 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001232
1233 // and last the secondary vtable pointers.
Mike Stumpacfd1e52009-11-13 01:54:23 +00001234 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001235 }
1236
1237 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1238 /// built from each direct non-virtual proper base that requires a VTT in
1239 /// declaration order.
Mike Stump9840c702009-11-12 20:47:57 +00001240 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1241 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001242 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1243 e = RD->bases_end(); i != e; ++i) {
1244 const CXXRecordDecl *Base =
1245 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1246 if (i->isVirtual())
1247 continue;
Mike Stump9840c702009-11-12 20:47:57 +00001248 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1249 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1250 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001251 }
1252 }
1253
1254 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1255 /// graph preorder.
1256 void VirtualVTTs(const CXXRecordDecl *RD) {
1257 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1258 e = RD->bases_end(); i != e; ++i) {
1259 const CXXRecordDecl *Base =
1260 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1261 if (i->isVirtual() && !SeenVBase.count(Base)) {
1262 SeenVBase.insert(Base);
Mike Stump9840c702009-11-12 20:47:57 +00001263 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1264 BuildVTT(Base, BaseOffset, true);
Mike Stump971977f2009-11-11 00:35:07 +00001265 }
1266 VirtualVTTs(Base);
1267 }
1268 }
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001269public:
1270 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpaee8de32009-11-11 03:08:24 +00001271 CodeGenModule &cgm)
1272 : Inits(inits), Class(c), CGM(cgm),
Mike Stump9840c702009-11-12 20:47:57 +00001273 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stumpacfd1e52009-11-13 01:54:23 +00001274 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump9840c702009-11-12 20:47:57 +00001275 VMContext(cgm.getModule().getContext()) {
Mike Stump380dd752009-11-10 07:44:33 +00001276
Mike Stump971977f2009-11-11 00:35:07 +00001277 // First comes the primary virtual table pointer for the complete class...
Mike Stump9840c702009-11-12 20:47:57 +00001278 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1279 Inits.push_back(ClassVtbl);
1280 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1281
Mike Stump971977f2009-11-11 00:35:07 +00001282 // then the secondary VTTs...
1283 SecondaryVTTs(Class);
1284
1285 // then the secondary vtable pointers...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001286 Secondary(Class, ClassVtbl, Class);
Mike Stump971977f2009-11-11 00:35:07 +00001287
1288 // and last, the virtual VTTs.
1289 VirtualVTTs(Class);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001290 }
1291};
Mike Stump92f2fe22009-12-02 19:07:44 +00001292}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001293
Mike Stump380dd752009-11-10 07:44:33 +00001294llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpf1c03332009-11-10 19:13:04 +00001295 // Only classes that have virtual bases need a VTT.
1296 if (RD->getNumVBases() == 0)
1297 return 0;
1298
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001299 llvm::SmallString<256> OutName;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001300 getMangleContext().mangleCXXVTT(RD, OutName);
1301 llvm::StringRef Name = OutName.str();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001302
1303 llvm::GlobalVariable::LinkageTypes linktype;
1304 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stump85615df2009-11-19 04:04:36 +00001305 if (RD->isInAnonymousNamespace())
1306 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001307 std::vector<llvm::Constant *> inits;
1308 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1309
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001310 D1(printf("vtt %s\n", RD->getNameAsCString()));
1311
Mike Stump971977f2009-11-11 00:35:07 +00001312 VTTBuilder b(inits, RD, *this);
1313
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001314 llvm::Constant *C;
1315 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1316 C = llvm::ConstantArray::get(type, inits);
Mike Stumpe56ceca2009-11-18 04:00:48 +00001317 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stump85615df2009-11-19 04:04:36 +00001318 linktype, C, Name);
Mike Stumpe56ceca2009-11-18 04:00:48 +00001319 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1320 if (Hidden)
1321 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1322 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001323}
Mike Stump380dd752009-11-10 07:44:33 +00001324
Mike Stump58588942009-11-19 01:08:19 +00001325void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1326 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpde050572009-12-02 18:57:08 +00001327 CGM.GenerateRTTI(RD);
Mike Stump58588942009-11-19 01:08:19 +00001328 CGM.GenerateVTT(RD);
1329}
1330
Mike Stump8cfcb522009-11-11 20:26:26 +00001331llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stump380dd752009-11-10 07:44:33 +00001332 llvm::Constant *&vtbl = Vtables[RD];
1333 if (vtbl)
1334 return vtbl;
Mike Stump9840c702009-11-12 20:47:57 +00001335 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stump85615df2009-11-19 04:04:36 +00001336
1337 bool CreateDefinition = true;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001338
1339 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1340 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001341 if (!KeyFunction->getBody()) {
1342 // If there is a KeyFunction, and it isn't defined, just build a
1343 // reference to the vtable.
1344 CreateDefinition = false;
1345 }
1346 }
1347
1348 if (CreateDefinition) {
Mike Stumpde050572009-12-02 18:57:08 +00001349 CGM.GenerateRTTI(RD);
Mike Stump85615df2009-11-19 04:04:36 +00001350 CGM.GenerateVTT(RD);
1351 }
Mike Stump380dd752009-11-10 07:44:33 +00001352 return vtbl;
1353}
Mike Stump8cfcb522009-11-11 20:26:26 +00001354
Mike Stump9840c702009-11-12 20:47:57 +00001355llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1356 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001357 uint64_t Offset) {
Mike Stump9840c702009-11-12 20:47:57 +00001358 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stump8cfcb522009-11-11 20:26:26 +00001359}
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001360
1361void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1362 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1363 const CXXRecordDecl *RD = MD->getParent();
1364
1365 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1366
1367 // Get the key function.
1368 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1369
1370 if (!KeyFunction) {
1371 // If there's no key function, we don't want to emit the vtable here.
1372 return;
1373 }
1374
1375 // Check if we have the key function.
1376 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1377 return;
1378
1379 // If the key function is a destructor, we only want to emit the vtable once,
1380 // so do it for the complete destructor.
1381 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1382 return;
1383
1384 // Emit the data.
1385 GenerateClassData(RD);
1386}
1387