blob: 32f8ab2fb5da3bbb1395c7337a2eb6248165793e [file] [log] [blame]
Charles Davis74ce8592010-06-09 23:25:41 +00001//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
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//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davis74ce8592010-06-09 23:25:41 +000011// The class in this file generates structures that follow the Microsoft
12// Visual C++ ABI, which is actually not very well documented at all outside
13// of Microsoft.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGCXXABI.h"
Reid Kleckner7810af02013-06-19 15:20:38 +000018#include "CGVTables.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "CodeGenModule.h"
Charles Davis74ce8592010-06-09 23:25:41 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000022#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000023#include "llvm/ADT/StringSet.h"
Charles Davis74ce8592010-06-09 23:25:41 +000024
25using namespace clang;
26using namespace CodeGen;
27
28namespace {
29
Reid Klecknerb40a27d2014-01-03 00:14:35 +000030/// Holds all the vbtable globals for a given class.
31struct VBTableGlobals {
32 const VBTableVector *VBTables;
33 SmallVector<llvm::GlobalVariable *, 2> Globals;
34};
35
Charles Davis53c59df2010-08-16 03:33:14 +000036class MicrosoftCXXABI : public CGCXXABI {
Charles Davis74ce8592010-06-09 23:25:41 +000037public:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000038 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall5d865c322010-08-31 07:33:07 +000039
Stephen Lin9dc6eef2013-06-30 20:40:16 +000040 bool HasThisReturn(GlobalDecl GD) const;
41
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000042 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
43 // Structures that are not C++03 PODs are always indirect.
44 return !RD->isPOD();
45 }
46
47 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000048 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000049 return RAA_DirectInMemory;
50 return RAA_Default;
51 }
52
Joao Matos2ce88ef2012-07-17 17:10:11 +000053 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-10-16 22:56:05 +000054 // No known support for deleted functions in MSVC yet, so this choice is
55 // arbitrary.
56 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +000057
Hans Wennborgfeedf852013-11-21 00:15:56 +000058 bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
59
John McCall82fb8922012-09-25 10:10:39 +000060 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
61 llvm::Value *ptr,
62 QualType type);
63
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000064 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
65 llvm::Value *This,
66 const CXXRecordDecl *ClassDecl,
67 const CXXRecordDecl *BaseClassDecl);
68
John McCall5d865c322010-08-31 07:33:07 +000069 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
70 CXXCtorType Type,
71 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000072 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000073
Reid Kleckner7810af02013-06-19 15:20:38 +000074 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
75 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000076
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000077 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
78 const CXXRecordDecl *RD);
79
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000080 void EmitCXXConstructors(const CXXConstructorDecl *D);
81
Reid Klecknere7de47e2013-07-22 13:51:44 +000082 // Background on MSVC destructors
83 // ==============================
84 //
85 // Both Itanium and MSVC ABIs have destructor variants. The variant names
86 // roughly correspond in the following way:
87 // Itanium Microsoft
88 // Base -> no name, just ~Class
89 // Complete -> vbase destructor
90 // Deleting -> scalar deleting destructor
91 // vector deleting destructor
92 //
93 // The base and complete destructors are the same as in Itanium, although the
94 // complete destructor does not accept a VTT parameter when there are virtual
95 // bases. A separate mechanism involving vtordisps is used to ensure that
96 // virtual methods of destroyed subobjects are not called.
97 //
98 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
99 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
100 // pointer points to an array. The scalar deleting destructor assumes that
101 // bit 2 is zero, and therefore does not contain a loop.
102 //
103 // For virtual destructors, only one entry is reserved in the vftable, and it
104 // always points to the vector deleting destructor. The vector deleting
105 // destructor is the most general, so it can be used to destroy objects in
106 // place, delete single heap objects, or delete arrays.
107 //
108 // A TU defining a non-inline destructor is only guaranteed to emit a base
109 // destructor, and all of the other variants are emitted on an as-needed basis
110 // in COMDATs. Because a non-base destructor can be emitted in a TU that
111 // lacks a definition for the destructor, non-base destructors must always
112 // delegate to or alias the base destructor.
113
114 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000115 CXXDtorType Type,
116 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000117 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000118
Reid Klecknere7de47e2013-07-22 13:51:44 +0000119 /// Non-base dtors should be emitted as delegating thunks in this ABI.
120 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
121 CXXDtorType DT) const {
122 return DT != Dtor_Base;
123 }
124
125 void EmitCXXDestructors(const CXXDestructorDecl *D);
126
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000127 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
128 MD = MD->getCanonicalDecl();
129 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000130 MicrosoftVTableContext::MethodVFTableLocation ML =
131 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000132 // The vbases might be ordered differently in the final overrider object
133 // and the complete object, so the "this" argument may sometimes point to
134 // memory that has no particular type (e.g. past the complete object).
135 // In this case, we just use a generic pointer type.
136 // FIXME: might want to have a more precise type in the non-virtual
137 // multiple inheritance case.
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000138 if (ML.VBase || !ML.VFPtrOffset.isZero())
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000139 return 0;
140 }
141 return MD->getParent();
142 }
143
144 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
145 GlobalDecl GD,
146 llvm::Value *This);
147
Reid Kleckner89077a12013-12-17 19:46:40 +0000148 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
149 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000150
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000151 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
152 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
153
John McCall0f999f32012-09-25 08:00:39 +0000154 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000155
Reid Kleckner89077a12013-12-17 19:46:40 +0000156 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
157 const CXXConstructorDecl *D,
158 CXXCtorType Type, bool ForVirtualBase,
159 bool Delegating, CallArgList &Args);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000160
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000161 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
162 CXXDtorType Type, bool ForVirtualBase,
163 bool Delegating, llvm::Value *This);
164
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000165 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
166
167 llvm::Value *getVTableAddressPointInStructor(
168 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
169 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
170 bool &NeedsVirtualOffset);
171
172 llvm::Constant *
173 getVTableAddressPointForConstExpr(BaseSubobject Base,
174 const CXXRecordDecl *VTableClass);
175
176 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
177 CharUnits VPtrOffset);
178
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000179 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
180 llvm::Value *This, llvm::Type *Ty);
181
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000182 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
183 const CXXDestructorDecl *Dtor,
184 CXXDtorType DtorType, SourceLocation CallLoc,
185 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000186
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000187 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
188 CallArgList &CallArgs) {
189 assert(GD.getDtorType() == Dtor_Deleting &&
190 "Only deleting destructor thunks are available in this ABI");
191 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
192 CGM.getContext().IntTy);
193 }
194
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000196
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000197 llvm::GlobalVariable *
198 getAddrOfVBTable(const VBTableInfo &VBT, const CXXRecordDecl *RD,
199 llvm::GlobalVariable::LinkageTypes Linkage);
200
201 void emitVBTableDefinition(const VBTableInfo &VBT, const CXXRecordDecl *RD,
202 llvm::GlobalVariable *GV) const;
203
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000204 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
205 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
206 }
207
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000208 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
209 const ThisAdjustment &TA);
210
211 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
212 const ReturnAdjustment &RA);
213
John McCallc84ed6a2012-05-01 06:13:13 +0000214 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
215 llvm::GlobalVariable *DeclPtr,
216 bool PerformInit);
217
John McCall29036752011-01-27 02:46:02 +0000218 // ==== Notes on array cookies =========
219 //
220 // MSVC seems to only use cookies when the class has a destructor; a
221 // two-argument usual array deallocation function isn't sufficient.
222 //
223 // For example, this code prints "100" and "1":
224 // struct A {
225 // char x;
226 // void *operator new[](size_t sz) {
227 // printf("%u\n", sz);
228 // return malloc(sz);
229 // }
230 // void operator delete[](void *p, size_t sz) {
231 // printf("%u\n", sz);
232 // free(p);
233 // }
234 // };
235 // int main() {
236 // A *p = new A[100];
237 // delete[] p;
238 // }
239 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000240
241 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
242 bool requiresArrayCookie(const CXXNewExpr *expr);
243 CharUnits getArrayCookieSizeImpl(QualType type);
244 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
245 llvm::Value *NewPtr,
246 llvm::Value *NumElements,
247 const CXXNewExpr *expr,
248 QualType ElementType);
249 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
250 llvm::Value *allocPtr,
251 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000252
253private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000254 MicrosoftMangleContext &getMangleContext() {
255 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
256 }
257
Reid Kleckner2341ae32013-04-11 18:13:19 +0000258 llvm::Constant *getZeroInt() {
259 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000260 }
261
Reid Kleckner2341ae32013-04-11 18:13:19 +0000262 llvm::Constant *getAllOnesInt() {
263 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000264 }
265
Reid Kleckner452abac2013-05-09 21:01:17 +0000266 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
267 return C ? C : getZeroInt();
268 }
269
270 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
271 return C ? C : getZeroInt();
272 }
273
Reid Kleckner2341ae32013-04-11 18:13:19 +0000274 void
275 GetNullMemberPointerFields(const MemberPointerType *MPT,
276 llvm::SmallVectorImpl<llvm::Constant *> &fields);
277
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000278 /// \brief Shared code for virtual base adjustment. Returns the offset from
279 /// the vbptr to the virtual base. Optionally returns the address of the
280 /// vbptr itself.
281 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
282 llvm::Value *Base,
283 llvm::Value *VBPtrOffset,
284 llvm::Value *VBTableOffset,
285 llvm::Value **VBPtr = 0);
286
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000287 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
288 llvm::Value *Base,
289 int32_t VBPtrOffset,
290 int32_t VBTableOffset,
291 llvm::Value **VBPtr = 0) {
292 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
293 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
294 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
295 }
296
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000297 /// \brief Performs a full virtual base adjustment. Used to dereference
298 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000299 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
300 llvm::Value *Base,
301 llvm::Value *VirtualBaseAdjustmentOffset,
302 llvm::Value *VBPtrOffset /* optional */);
303
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000304 /// \brief Emits a full member pointer with the fields common to data and
305 /// function member pointers.
306 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
307 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000308 const CXXRecordDecl *RD,
309 CharUnits NonVirtualBaseAdjustment);
310
311 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
312 const CXXMethodDecl *MD,
313 CharUnits NonVirtualBaseAdjustment);
314
315 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
316 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000317
Reid Kleckner7810af02013-06-19 15:20:38 +0000318 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
319 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
320
321 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000322 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000323
Hans Wennborg88497d62013-11-15 17:24:45 +0000324 /// \brief Generate a thunk for calling a virtual member function MD.
325 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
326 StringRef ThunkName);
327
Reid Kleckner407e8b62013-03-22 19:02:54 +0000328public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000329 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
330
331 virtual bool isZeroInitializable(const MemberPointerType *MPT);
332
Reid Kleckner407e8b62013-03-22 19:02:54 +0000333 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
334
335 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
336 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000337 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
338 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000339
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000340 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
341 llvm::Value *L,
342 llvm::Value *R,
343 const MemberPointerType *MPT,
344 bool Inequality);
345
Reid Kleckner407e8b62013-03-22 19:02:54 +0000346 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
347 llvm::Value *MemPtr,
348 const MemberPointerType *MPT);
349
350 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
351 llvm::Value *Base,
352 llvm::Value *MemPtr,
353 const MemberPointerType *MPT);
354
Reid Kleckner452abac2013-05-09 21:01:17 +0000355 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
356 const CastExpr *E,
357 llvm::Value *Src);
358
359 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
360 llvm::Constant *Src);
361
Reid Kleckner2341ae32013-04-11 18:13:19 +0000362 virtual llvm::Value *
363 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
364 llvm::Value *&This,
365 llvm::Value *MemPtr,
366 const MemberPointerType *MPT);
367
Reid Kleckner7810af02013-06-19 15:20:38 +0000368private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000369 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
370 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
371 /// \brief All the vftables that have been referenced.
372 VFTablesMapTy VFTablesMap;
373
374 /// \brief This set holds the record decls we've deferred vtable emission for.
375 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
376
377
378 /// \brief All the vbtables which have been referenced.
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000379 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000380
381 /// Info on the global variable used to guard initialization of static locals.
382 /// The BitIndex field is only used for externally invisible declarations.
383 struct GuardInfo {
384 GuardInfo() : Guard(0), BitIndex(0) {}
385 llvm::GlobalVariable *Guard;
386 unsigned BitIndex;
387 };
388
389 /// Map from DeclContext to the current guard variable. We assume that the
390 /// AST is visited in source code order.
391 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000392};
393
394}
395
John McCall82fb8922012-09-25 10:10:39 +0000396llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
397 llvm::Value *ptr,
398 QualType type) {
399 // FIXME: implement
400 return ptr;
401}
402
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000403llvm::Value *
404MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
405 llvm::Value *This,
406 const CXXRecordDecl *ClassDecl,
407 const CXXRecordDecl *BaseClassDecl) {
Reid Kleckner5b1b5d52014-01-14 00:50:39 +0000408 int64_t VBPtrChars =
409 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000410 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000411 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000412 CharUnits VBTableChars =
413 IntSize *
414 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000415 llvm::Value *VBTableOffset =
416 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
417
418 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000419 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000420 VBPtrToNewBase =
421 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
422 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
423}
424
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000425bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
426 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000427}
428
Reid Kleckner89077a12013-12-17 19:46:40 +0000429void MicrosoftCXXABI::BuildConstructorSignature(
430 const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
431 SmallVectorImpl<CanQualType> &ArgTys) {
432
433 // All parameters are already in place except is_most_derived, which goes
434 // after 'this' if it's variadic and last if it's not.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000435
436 const CXXRecordDecl *Class = Ctor->getParent();
Reid Kleckner89077a12013-12-17 19:46:40 +0000437 const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000438 if (Class->getNumVBases()) {
Reid Kleckner89077a12013-12-17 19:46:40 +0000439 if (FPT->isVariadic())
440 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
441 else
442 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000443 }
444}
445
Reid Kleckner7810af02013-06-19 15:20:38 +0000446llvm::BasicBlock *
447MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
448 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000449 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
450 assert(IsMostDerivedClass &&
451 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000452 llvm::Value *IsCompleteObject =
453 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000454
455 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
456 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
457 CGF.Builder.CreateCondBr(IsCompleteObject,
458 CallVbaseCtorsBB, SkipVbaseCtorsBB);
459
460 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000461
462 // Fill in the vbtable pointers here.
463 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000464
465 // CGF will put the base ctor calls in this basic block for us later.
466
467 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000468}
469
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000470void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
471 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
472 // In most cases, an override for a vbase virtual method can adjust
473 // the "this" parameter by applying a constant offset.
474 // However, this is not enough while a constructor or a destructor of some
475 // class X is being executed if all the following conditions are met:
476 // - X has virtual bases, (1)
477 // - X overrides a virtual method M of a vbase Y, (2)
478 // - X itself is a vbase of the most derived class.
479 //
480 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
481 // which holds the extra amount of "this" adjustment we must do when we use
482 // the X vftables (i.e. during X ctor or dtor).
483 // Outside the ctors and dtors, the values of vtorDisps are zero.
484
485 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
486 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
487 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
488 CGBuilderTy &Builder = CGF.Builder;
489
490 unsigned AS =
491 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
492 llvm::Value *Int8This = 0; // Initialize lazily.
493
494 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
495 I != E; ++I) {
496 if (!I->second.hasVtorDisp())
497 continue;
498
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000499 llvm::Value *VBaseOffset =
500 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000501 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
502 // just to Trunc back immediately.
503 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
504 uint64_t ConstantVBaseOffset =
505 Layout.getVBaseClassOffset(I->first).getQuantity();
506
507 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
508 llvm::Value *VtorDispValue = Builder.CreateSub(
509 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
510 "vtordisp.value");
511
512 if (!Int8This)
513 Int8This = Builder.CreateBitCast(getThisValue(CGF),
514 CGF.Int8Ty->getPointerTo(AS));
515 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
516 // vtorDisp is always the 32-bits before the vbase in the class layout.
517 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
518 VtorDispPtr = Builder.CreateBitCast(
519 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
520
521 Builder.CreateStore(VtorDispValue, VtorDispPtr);
522 }
523}
524
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000525void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
526 // There's only one constructor type in this ABI.
527 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
528}
529
Reid Kleckner7810af02013-06-19 15:20:38 +0000530void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
531 const CXXRecordDecl *RD) {
532 llvm::Value *ThisInt8Ptr =
533 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
Reid Kleckner5f080942014-01-03 23:42:00 +0000534 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000535
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000536 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
537 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +0000538 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000539 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
Reid Kleckner7810af02013-06-19 15:20:38 +0000540 const ASTRecordLayout &SubobjectLayout =
Reid Kleckner5f080942014-01-03 23:42:00 +0000541 CGM.getContext().getASTRecordLayout(VBT->BaseWithVBPtr);
542 CharUnits Offs = VBT->NonVirtualOffset;
543 Offs += SubobjectLayout.getVBPtrOffset();
544 if (VBT->getVBaseWithVBPtr())
545 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVBPtr());
Reid Kleckner7810af02013-06-19 15:20:38 +0000546 llvm::Value *VBPtr =
Reid Kleckner5f080942014-01-03 23:42:00 +0000547 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000548 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
Reid Kleckner5f080942014-01-03 23:42:00 +0000549 "vbptr." + VBT->ReusingBase->getName());
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000550 CGF.Builder.CreateStore(GV, VBPtr);
Reid Kleckner7810af02013-06-19 15:20:38 +0000551 }
552}
553
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000554void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
555 CXXDtorType Type,
556 CanQualType &ResTy,
557 SmallVectorImpl<CanQualType> &ArgTys) {
558 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000559
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000560 // TODO: 'for base' flag
561
562 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000563 // The scalar deleting destructor takes an implicit int parameter.
564 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000565 }
566}
567
Reid Klecknere7de47e2013-07-22 13:51:44 +0000568void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
569 // The TU defining a dtor is only guaranteed to emit a base destructor. All
570 // other destructor variants are delegating thunks.
571 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
572}
573
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000574llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
575 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
576 GD = GD.getCanonicalDecl();
577 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000578 // FIXME: consider splitting the vdtor vs regular method code into two
579 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000580
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000581 GlobalDecl LookupGD = GD;
582 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
583 // Complete dtors take a pointer to the complete object,
584 // thus don't need adjustment.
585 if (GD.getDtorType() == Dtor_Complete)
586 return This;
587
588 // There's only Dtor_Deleting in vftable but it shares the this adjustment
589 // with the base one, so look up the deleting one instead.
590 LookupGD = GlobalDecl(DD, Dtor_Deleting);
591 }
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000592 MicrosoftVTableContext::MethodVFTableLocation ML =
593 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000594
595 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
596 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000597 CharUnits StaticOffset = ML.VFPtrOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000598 if (ML.VBase) {
599 bool AvoidVirtualOffset = false;
600 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
601 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000602 // same record type or another destructor of a more derived type;
603 // or a constructor of the same record type if an exception is thrown.
604 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
605 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000606 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000607 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000608
609 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000610 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
611 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
612 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
613 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
614 // We're calling the main base dtor from a complete structor,
615 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000616 AvoidVirtualOffset = true;
617 } else {
618 // Let's see if we try to call a destructor of a non-virtual base.
619 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
620 E = CurRD->bases_end(); I != E; ++I) {
621 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
622 continue;
623 // If we call a base destructor for a non-virtual base, we statically
624 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000625 // The total offset should reflect the adjustment done by
626 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000627 AvoidVirtualOffset = true;
628 break;
629 }
630 }
631 }
632
633 if (AvoidVirtualOffset) {
634 const ASTRecordLayout &Layout =
635 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000636 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
637 } else {
638 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000639 llvm::Value *VBaseOffset =
640 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000641 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
642 }
643 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000644 if (!StaticOffset.isZero()) {
645 assert(StaticOffset.isPositive());
646 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000647 if (ML.VBase) {
648 // Non-virtual adjustment might result in a pointer outside the allocated
649 // object, e.g. if the final overrider class is laid out after the virtual
650 // base that declares a method in the most derived class.
651 // FIXME: Update the code that emits this adjustment in thunks prologues.
652 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
653 } else {
654 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
655 StaticOffset.getQuantity());
656 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000657 }
658 return This;
659}
660
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000661static bool IsDeletingDtor(GlobalDecl GD) {
662 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
663 if (isa<CXXDestructorDecl>(MD)) {
664 return GD.getDtorType() == Dtor_Deleting;
665 }
666 return false;
667}
668
Reid Kleckner89077a12013-12-17 19:46:40 +0000669void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
670 QualType &ResTy,
671 FunctionArgList &Params) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000672 ASTContext &Context = getContext();
673 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000674 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000675 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
676 ImplicitParamDecl *IsMostDerived
677 = ImplicitParamDecl::Create(Context, 0,
678 CGF.CurGD.getDecl()->getLocation(),
679 &Context.Idents.get("is_most_derived"),
680 Context.IntTy);
Reid Kleckner89077a12013-12-17 19:46:40 +0000681 // The 'most_derived' parameter goes second if the ctor is variadic and last
682 // if it's not. Dtors can't be variadic.
683 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
684 if (FPT->isVariadic())
685 Params.insert(Params.begin() + 1, IsMostDerived);
686 else
687 Params.push_back(IsMostDerived);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000688 getStructorImplicitParamDecl(CGF) = IsMostDerived;
689 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000690 ImplicitParamDecl *ShouldDelete
691 = ImplicitParamDecl::Create(Context, 0,
692 CGF.CurGD.getDecl()->getLocation(),
693 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000694 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000695 Params.push_back(ShouldDelete);
696 getStructorImplicitParamDecl(CGF) = ShouldDelete;
697 }
John McCall0f999f32012-09-25 08:00:39 +0000698}
699
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000700llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
701 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
702 GD = GD.getCanonicalDecl();
703 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000704
705 GlobalDecl LookupGD = GD;
706 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
707 // Complete destructors take a pointer to the complete object as a
708 // parameter, thus don't need this adjustment.
709 if (GD.getDtorType() == Dtor_Complete)
710 return This;
711
712 // There's no Dtor_Base in vftable but it shares the this adjustment with
713 // the deleting one, so look it up instead.
714 LookupGD = GlobalDecl(DD, Dtor_Deleting);
715 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000716
717 // In this ABI, every virtual function takes a pointer to one of the
718 // subobjects that first defines it as the 'this' parameter, rather than a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000719 // pointer to the final overrider subobject. Thus, we need to adjust it back
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000720 // to the final overrider subobject before use.
721 // See comments in the MicrosoftVFTableContext implementation for the details.
722
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000723 MicrosoftVTableContext::MethodVFTableLocation ML =
724 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000725 CharUnits Adjustment = ML.VFPtrOffset;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000726 if (ML.VBase) {
727 const ASTRecordLayout &DerivedLayout =
728 CGF.getContext().getASTRecordLayout(MD->getParent());
729 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
730 }
731
732 if (Adjustment.isZero())
733 return This;
734
735 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
736 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
737 *thisTy = This->getType();
738
739 This = CGF.Builder.CreateBitCast(This, charPtrTy);
740 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000741 This =
742 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000743 return CGF.Builder.CreateBitCast(This, thisTy);
744}
745
John McCall0f999f32012-09-25 08:00:39 +0000746void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
747 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000748
749 /// If this is a function that the ABI specifies returns 'this', initialize
750 /// the return slot to 'this' at the start of the function.
751 ///
752 /// Unlike the setting of return types, this is done within the ABI
753 /// implementation instead of by clients of CGCXXABI because:
754 /// 1) getThisValue is currently protected
755 /// 2) in theory, an ABI could implement 'this' returns some other way;
756 /// HasThisReturn only specifies a contract, not the implementation
757 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000758 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000759
760 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
761 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
762 assert(getStructorImplicitParamDecl(CGF) &&
763 "no implicit parameter for a constructor with virtual bases?");
764 getStructorImplicitParamValue(CGF)
765 = CGF.Builder.CreateLoad(
766 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
767 "is_most_derived");
768 }
769
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000770 if (IsDeletingDtor(CGF.CurGD)) {
771 assert(getStructorImplicitParamDecl(CGF) &&
772 "no implicit parameter for a deleting destructor?");
773 getStructorImplicitParamValue(CGF)
774 = CGF.Builder.CreateLoad(
775 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
776 "should_call_delete");
777 }
John McCall0f999f32012-09-25 08:00:39 +0000778}
779
Reid Kleckner89077a12013-12-17 19:46:40 +0000780unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
781 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
782 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000783 assert(Type == Ctor_Complete || Type == Ctor_Base);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000784
Reid Kleckner89077a12013-12-17 19:46:40 +0000785 // Check if we need a 'most_derived' parameter.
786 if (!D->getParent()->getNumVBases())
787 return 0;
788
789 // Add the 'most_derived' argument second if we are variadic or last if not.
790 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
791 llvm::Value *MostDerivedArg =
792 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
793 RValue RV = RValue::get(MostDerivedArg);
794 if (MostDerivedArg) {
795 if (FPT->isVariadic())
796 Args.insert(Args.begin() + 1,
797 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
798 else
799 Args.add(RV, getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000800 }
801
Reid Kleckner89077a12013-12-17 19:46:40 +0000802 return 1; // Added one arg.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000803}
804
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000805void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
806 const CXXDestructorDecl *DD,
807 CXXDtorType Type, bool ForVirtualBase,
808 bool Delegating, llvm::Value *This) {
809 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
810
811 if (DD->isVirtual())
812 This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This);
813
814 // FIXME: Provide a source location here.
815 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
816 /*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0);
817}
818
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000819void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
820 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000821 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
822 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000823 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
824
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000825 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000826 E = VFPtrs.end(); I != E; ++I) {
827 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
828 if (VTable->hasInitializer())
829 continue;
830
831 const VTableLayout &VTLayout =
832 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
833 llvm::Constant *Init = CGVT.CreateVTableInitializer(
834 RD, VTLayout.vtable_component_begin(),
835 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
836 VTLayout.getNumVTableThunks());
837 VTable->setInitializer(Init);
838
839 VTable->setLinkage(Linkage);
840 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
841 }
842}
843
844llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
845 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
846 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
847 NeedsVirtualOffset = (NearestVBase != 0);
848
849 llvm::Value *VTableAddressPoint =
850 getAddrOfVTable(VTableClass, Base.getBaseOffset());
851 if (!VTableAddressPoint) {
852 assert(Base.getBase()->getNumVBases() &&
853 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
854 }
855 return VTableAddressPoint;
856}
857
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000858static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
859 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
860 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000861 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000862 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000863}
864
865llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
866 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
867 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
868 assert(VTable && "Couldn't find a vftable for the given base?");
869 return VTable;
870}
871
872llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
873 CharUnits VPtrOffset) {
874 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
875 // shouldn't be used in the given record type. We want to cache this result in
876 // VFTablesMap, thus a simple zero check is not sufficient.
877 VFTableIdTy ID(RD, VPtrOffset);
878 VFTablesMapTy::iterator I;
879 bool Inserted;
880 llvm::tie(I, Inserted) = VFTablesMap.insert(
881 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
882 if (!Inserted)
883 return I->second;
884
885 llvm::GlobalVariable *&VTable = I->second;
886
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000887 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
888 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
889 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000890
891 if (DeferredVFTables.insert(RD)) {
892 // We haven't processed this record type before.
893 // Queue up this v-table for possible deferred emission.
894 CGM.addDeferredVTable(RD);
895
896#ifndef NDEBUG
897 // Create all the vftables at once in order to make sure each vftable has
898 // a unique mangled name.
899 llvm::StringSet<> ObservedMangledNames;
900 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
901 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000902 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000903 if (!ObservedMangledNames.insert(Name.str()))
904 llvm_unreachable("Already saw this mangling before?");
905 }
906#endif
907 }
908
909 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
910 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
911 continue;
912
913 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
914 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000915 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000916 .getNumVTableComponents());
917
918 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000919 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000920 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
921 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
922 VTable->setUnnamedAddr(true);
923 break;
924 }
925
926 return VTable;
927}
928
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000929llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
930 GlobalDecl GD,
931 llvm::Value *This,
932 llvm::Type *Ty) {
933 GD = GD.getCanonicalDecl();
934 CGBuilderTy &Builder = CGF.Builder;
935
936 Ty = Ty->getPointerTo()->getPointerTo();
937 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
938 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
939
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000940 MicrosoftVTableContext::MethodVFTableLocation ML =
941 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000942 llvm::Value *VFuncPtr =
943 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
944 return Builder.CreateLoad(VFuncPtr);
945}
946
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000947void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
948 const CXXDestructorDecl *Dtor,
949 CXXDtorType DtorType,
950 SourceLocation CallLoc,
951 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000952 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
953
954 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000955 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000956 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000957 const CGFunctionInfo *FInfo =
958 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000959 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000960 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000961
962 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000963 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000964 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000965 DtorType == Dtor_Deleting);
966
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000967 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000968 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000969 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000970}
971
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000972const VBTableGlobals &
973MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +0000974 // At this layer, we can key the cache off of a single class, which is much
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000975 // easier than caching each vbtable individually.
976 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
977 bool Added;
978 llvm::tie(Entry, Added) = VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
979 VBTableGlobals &VBGlobals = Entry->second;
980 if (!Added)
981 return VBGlobals;
Reid Kleckner7810af02013-06-19 15:20:38 +0000982
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000983 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
984 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000985
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000986 // Cache the globals for all vbtables so we don't have to recompute the
987 // mangled names.
988 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
989 for (VBTableVector::const_iterator I = VBGlobals.VBTables->begin(),
990 E = VBGlobals.VBTables->end();
991 I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +0000992 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000993 }
994
995 return VBGlobals;
Reid Kleckner7810af02013-06-19 15:20:38 +0000996}
997
Hans Wennborg88497d62013-11-15 17:24:45 +0000998llvm::Function *
999MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1000 StringRef ThunkName) {
1001 // If the thunk has been generated previously, just return it.
1002 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1003 return cast<llvm::Function>(GV);
1004
1005 // Create the llvm::Function.
1006 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1007 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1008 llvm::Function *ThunkFn =
1009 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1010 ThunkName.str(), &CGM.getModule());
1011 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1012
Hans Wennborg88497d62013-11-15 17:24:45 +00001013 ThunkFn->setLinkage(MD->isExternallyVisible()
1014 ? llvm::GlobalValue::LinkOnceODRLinkage
1015 : llvm::GlobalValue::InternalLinkage);
1016
1017 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1018 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1019
1020 // Start codegen.
1021 CodeGenFunction CGF(CGM);
1022 CGF.StartThunk(ThunkFn, MD, FnInfo);
1023
1024 // Get to the Callee.
1025 llvm::Value *This = CGF.LoadCXXThis();
1026 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1027
1028 // Make the call and return the result.
1029 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1030
1031 return ThunkFn;
1032}
1033
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001034void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001035 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1036 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +00001037 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001038 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
Reid Kleckner5f080942014-01-03 23:42:00 +00001039 emitVBTableDefinition(*VBT, RD, GV);
Reid Kleckner7810af02013-06-19 15:20:38 +00001040 }
1041}
1042
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001043llvm::GlobalVariable *
1044MicrosoftCXXABI::getAddrOfVBTable(const VBTableInfo &VBT,
1045 const CXXRecordDecl *RD,
1046 llvm::GlobalVariable::LinkageTypes Linkage) {
1047 SmallString<256> OutName;
1048 llvm::raw_svector_ostream Out(OutName);
1049 MicrosoftMangleContext &Mangler =
1050 cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext());
1051 Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out);
1052 Out.flush();
1053 StringRef Name = OutName.str();
1054
1055 llvm::ArrayType *VBTableType =
1056 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1057
1058 assert(!CGM.getModule().getNamedGlobal(Name) &&
1059 "vbtable with this name already exists: mangling bug?");
1060 llvm::GlobalVariable *GV =
1061 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1062 GV->setUnnamedAddr(true);
1063 return GV;
1064}
1065
1066void MicrosoftCXXABI::emitVBTableDefinition(const VBTableInfo &VBT,
1067 const CXXRecordDecl *RD,
1068 llvm::GlobalVariable *GV) const {
1069 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1070
1071 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1072 "should only emit vbtables for classes with vbtables");
1073
1074 const ASTRecordLayout &BaseLayout =
Reid Kleckner5f080942014-01-03 23:42:00 +00001075 CGM.getContext().getASTRecordLayout(VBT.BaseWithVBPtr);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001076 const ASTRecordLayout &DerivedLayout =
1077 CGM.getContext().getASTRecordLayout(RD);
1078
1079 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 0);
1080
1081 // The offset from ReusingBase's vbptr to itself always leads.
1082 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1083 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1084
1085 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1086 for (CXXRecordDecl::base_class_const_iterator I = ReusingBase->vbases_begin(),
1087 E = ReusingBase->vbases_end();
1088 I != E; ++I) {
1089 const CXXRecordDecl *VBase = I->getType()->getAsCXXRecordDecl();
1090 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1091 assert(!Offset.isNegative());
Reid Kleckner5f080942014-01-03 23:42:00 +00001092
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001093 // Make it relative to the subobject vbptr.
Reid Kleckner5f080942014-01-03 23:42:00 +00001094 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1095 if (VBT.getVBaseWithVBPtr())
1096 CompleteVBPtrOffset +=
1097 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVBPtr());
1098 Offset -= CompleteVBPtrOffset;
1099
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001100 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1101 assert(Offsets[VBIndex] == 0 && "The same vbindex seen twice?");
1102 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1103 }
1104
1105 assert(Offsets.size() ==
1106 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1107 ->getElementType())->getNumElements());
1108 llvm::ArrayType *VBTableType =
1109 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1110 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1111 GV->setInitializer(Init);
1112
1113 // Set the right visibility.
1114 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForVTable);
1115}
1116
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001117llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1118 llvm::Value *This,
1119 const ThisAdjustment &TA) {
1120 if (TA.isEmpty())
1121 return This;
1122
1123 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1124
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001125 if (!TA.Virtual.isEmpty()) {
1126 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1127 // Adjust the this argument based on the vtordisp value.
1128 llvm::Value *VtorDispPtr =
1129 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1130 VtorDispPtr =
1131 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1132 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1133 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1134
1135 if (TA.Virtual.Microsoft.VBPtrOffset) {
1136 // If the final overrider is defined in a virtual base other than the one
1137 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1138 // the vbtable of the derived class.
1139 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1140 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1141 llvm::Value *VBPtr;
1142 llvm::Value *VBaseOffset =
1143 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1144 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1145 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1146 }
1147 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001148
1149 if (TA.NonVirtual) {
1150 // Non-virtual adjustment might result in a pointer outside the allocated
1151 // object, e.g. if the final overrider class is laid out after the virtual
1152 // base that declares a method in the most derived class.
1153 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1154 }
1155
1156 // Don't need to bitcast back, the call CodeGen will handle this.
1157 return V;
1158}
1159
1160llvm::Value *
1161MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1162 const ReturnAdjustment &RA) {
1163 if (RA.isEmpty())
1164 return Ret;
1165
1166 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1167
1168 if (RA.Virtual.Microsoft.VBIndex) {
1169 assert(RA.Virtual.Microsoft.VBIndex > 0);
1170 int32_t IntSize =
1171 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1172 llvm::Value *VBPtr;
1173 llvm::Value *VBaseOffset =
1174 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1175 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1176 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1177 }
1178
1179 if (RA.NonVirtual)
1180 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1181
1182 // Cast back to the original type.
1183 return CGF.Builder.CreateBitCast(V, Ret->getType());
1184}
1185
John McCallb91cd662012-05-01 05:23:51 +00001186bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1187 QualType elementType) {
1188 // Microsoft seems to completely ignore the possibility of a
1189 // two-argument usual deallocation function.
1190 return elementType.isDestructedType();
1191}
1192
1193bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1194 // Microsoft seems to completely ignore the possibility of a
1195 // two-argument usual deallocation function.
1196 return expr->getAllocatedType().isDestructedType();
1197}
1198
1199CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1200 // The array cookie is always a size_t; we then pad that out to the
1201 // alignment of the element type.
1202 ASTContext &Ctx = getContext();
1203 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1204 Ctx.getTypeAlignInChars(type));
1205}
1206
1207llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1208 llvm::Value *allocPtr,
1209 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001210 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001211 llvm::Value *numElementsPtr =
1212 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1213 return CGF.Builder.CreateLoad(numElementsPtr);
1214}
1215
1216llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1217 llvm::Value *newPtr,
1218 llvm::Value *numElements,
1219 const CXXNewExpr *expr,
1220 QualType elementType) {
1221 assert(requiresArrayCookie(expr));
1222
1223 // The size of the cookie.
1224 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1225
1226 // Compute an offset to the cookie.
1227 llvm::Value *cookiePtr = newPtr;
1228
1229 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001230 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001231 llvm::Value *numElementsPtr
1232 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1233 CGF.Builder.CreateStore(numElements, numElementsPtr);
1234
1235 // Finally, compute a pointer to the actual data buffer by skipping
1236 // over the cookie completely.
1237 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1238 cookieSize.getQuantity());
1239}
1240
John McCallc84ed6a2012-05-01 06:13:13 +00001241void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001242 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001243 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001244 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1245 // threadsafe. Since the user may be linking in inline functions compiled by
1246 // cl.exe, there's no reason to provide a false sense of security by using
1247 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001248
Richard Smithdbf74ba2013-04-14 23:01:42 +00001249 if (D.getTLSKind())
1250 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1251
Reid Klecknerd8110b62013-09-10 20:14:30 +00001252 CGBuilderTy &Builder = CGF.Builder;
1253 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1254 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1255
1256 // Get the guard variable for this function if we have one already.
1257 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1258
1259 unsigned BitIndex;
1260 if (D.isExternallyVisible()) {
1261 // Externally visible variables have to be numbered in Sema to properly
1262 // handle unreachable VarDecls.
1263 BitIndex = getContext().getManglingNumber(&D);
1264 assert(BitIndex > 0);
1265 BitIndex--;
1266 } else {
1267 // Non-externally visible variables are numbered here in CodeGen.
1268 BitIndex = GI.BitIndex++;
1269 }
1270
1271 if (BitIndex >= 32) {
1272 if (D.isExternallyVisible())
1273 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1274 BitIndex %= 32;
1275 GI.Guard = 0;
1276 }
1277
1278 // Lazily create the i32 bitfield for this function.
1279 if (!GI.Guard) {
1280 // Mangle the name for the guard.
1281 SmallString<256> GuardName;
1282 {
1283 llvm::raw_svector_ostream Out(GuardName);
1284 getMangleContext().mangleStaticGuardVariable(&D, Out);
1285 Out.flush();
1286 }
1287
1288 // Create the guard variable with a zero-initializer. Just absorb linkage
1289 // and visibility from the guarded variable.
1290 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1291 GV->getLinkage(), Zero, GuardName.str());
1292 GI.Guard->setVisibility(GV->getVisibility());
1293 } else {
1294 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1295 "static local from the same function had different linkage");
1296 }
1297
1298 // Pseudo code for the test:
1299 // if (!(GuardVar & MyGuardBit)) {
1300 // GuardVar |= MyGuardBit;
1301 // ... initialize the object ...;
1302 // }
1303
1304 // Test our bit from the guard variable.
1305 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1306 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1307 llvm::Value *IsInitialized =
1308 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1309 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1310 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1311 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1312
1313 // Set our bit in the guard variable and emit the initializer and add a global
1314 // destructor if appropriate.
1315 CGF.EmitBlock(InitBlock);
1316 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1317 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1318 Builder.CreateBr(EndBlock);
1319
1320 // Continue.
1321 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001322}
1323
Reid Kleckner2341ae32013-04-11 18:13:19 +00001324// Member pointer helpers.
1325static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1326 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001327}
1328
Reid Kleckner452abac2013-05-09 21:01:17 +00001329static bool hasOnlyOneField(bool IsMemberFunction,
1330 MSInheritanceModel Inheritance) {
1331 return Inheritance <= MSIM_SinglePolymorphic ||
1332 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001333}
1334
Reid Kleckner2341ae32013-04-11 18:13:19 +00001335// Only member pointers to functions need a this adjustment, since it can be
1336// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001337static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001338 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001339 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001340}
1341
1342static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1343 return Inheritance >= MSIM_Virtual;
1344}
1345
1346// Use zero for the field offset of a null data member pointer if we can
1347// guarantee that zero is not a valid field offset, or if the member pointer has
1348// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1349// use zero for null. If there are multiple fields, we can use zero even if it
1350// is a valid field offset because null-ness testing will check the other
1351// fields.
1352static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1353 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1354}
1355
1356bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1357 // Null-ness for function memptrs only depends on the first field, which is
1358 // the function pointer. The rest don't matter, so we can zero initialize.
1359 if (MPT->isMemberFunctionPointer())
1360 return true;
1361
1362 // The virtual base adjustment field is always -1 for null, so if we have one
1363 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1364 // valid field offset.
1365 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1366 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1367 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1368 nullFieldOffsetIsZero(Inheritance));
1369}
1370
1371llvm::Type *
1372MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1373 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1374 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1375 llvm::SmallVector<llvm::Type *, 4> fields;
1376 if (MPT->isMemberFunctionPointer())
1377 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1378 else
1379 fields.push_back(CGM.IntTy); // FieldOffset
1380
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001381 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1382 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001383 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001384 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001385 fields.push_back(CGM.IntTy);
1386 if (hasVirtualBaseAdjustmentField(Inheritance))
1387 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1388
1389 if (fields.size() == 1)
1390 return fields[0];
1391 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1392}
1393
1394void MicrosoftCXXABI::
1395GetNullMemberPointerFields(const MemberPointerType *MPT,
1396 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1397 assert(fields.empty());
1398 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1399 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1400 if (MPT->isMemberFunctionPointer()) {
1401 // FunctionPointerOrVirtualThunk
1402 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1403 } else {
1404 if (nullFieldOffsetIsZero(Inheritance))
1405 fields.push_back(getZeroInt()); // FieldOffset
1406 else
1407 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001408 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001409
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001410 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1411 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001412 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001413 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001414 fields.push_back(getZeroInt());
1415 if (hasVirtualBaseAdjustmentField(Inheritance))
1416 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001417}
1418
1419llvm::Constant *
1420MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001421 llvm::SmallVector<llvm::Constant *, 4> fields;
1422 GetNullMemberPointerFields(MPT, fields);
1423 if (fields.size() == 1)
1424 return fields[0];
1425 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1426 assert(Res->getType() == ConvertMemberPointerType(MPT));
1427 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001428}
1429
1430llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001431MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1432 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001433 const CXXRecordDecl *RD,
1434 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001435{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001436 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001437
1438 // Single inheritance class member pointer are represented as scalars instead
1439 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001440 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001441 return FirstField;
1442
Reid Kleckner2341ae32013-04-11 18:13:19 +00001443 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001444 fields.push_back(FirstField);
1445
1446 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001447 fields.push_back(llvm::ConstantInt::get(
1448 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001449
Reid Kleckner2341ae32013-04-11 18:13:19 +00001450 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001451 CharUnits Offs = CharUnits::Zero();
1452 if (RD->getNumVBases())
Reid Kleckner5b1b5d52014-01-14 00:50:39 +00001453 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
Reid Kleckneraec44092013-10-15 01:18:02 +00001454 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001455 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001456
1457 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001458 if (hasVirtualBaseAdjustmentField(Inheritance))
1459 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001460
Reid Kleckner2341ae32013-04-11 18:13:19 +00001461 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001462}
1463
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001464llvm::Constant *
1465MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1466 CharUnits offset) {
1467 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1468 llvm::Constant *FirstField =
1469 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001470 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1471 CharUnits::Zero());
1472}
1473
1474llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1475 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1476}
1477
1478llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1479 QualType MPType) {
1480 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1481 const ValueDecl *MPD = MP.getMemberPointerDecl();
1482 if (!MPD)
1483 return EmitNullMemberPointer(MPT);
1484
1485 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1486
1487 // FIXME PR15713: Support virtual inheritance paths.
1488
1489 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1490 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1491 MD, ThisAdjustment);
1492
1493 CharUnits FieldOffset =
1494 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1495 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001496}
1497
1498llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001499MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1500 const CXXMethodDecl *MD,
1501 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001502 assert(MD->isInstance() && "Member function must not be static!");
1503 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001504 CodeGenTypes &Types = CGM.getTypes();
1505
1506 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001507 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001508 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1509 llvm::Type *Ty;
1510 // Check whether the function has a computable LLVM signature.
1511 if (Types.isFuncTypeConvertible(FPT)) {
1512 // The function has a computable LLVM signature; use the correct type.
1513 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1514 } else {
1515 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1516 // function type is incomplete.
1517 Ty = CGM.PtrDiffTy;
1518 }
1519 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1520 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001521 } else {
1522 MicrosoftVTableContext::MethodVFTableLocation ML =
1523 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1524 if (MD->isVariadic()) {
1525 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1526 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1527 } else if (!CGM.getTypes().isFuncTypeConvertible(
1528 MD->getType()->castAs<FunctionType>())) {
1529 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1530 "incomplete return or parameter type");
1531 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1532 } else if (ML.VBase) {
1533 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1534 "member function in virtual base class");
1535 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1536 } else {
1537 SmallString<256> ThunkName;
David Majnemer2a816452013-12-09 10:44:32 +00001538 CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1539 getContext().getTargetInfo().getPointerWidth(0));
1540 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
Hans Wennborg88497d62013-11-15 17:24:45 +00001541 llvm::raw_svector_ostream Out(ThunkName);
1542 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1543 Out.flush();
1544
1545 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1546 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1547 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001548 }
1549
1550 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001551 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1552 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001553}
1554
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001555/// Member pointers are the same if they're either bitwise identical *or* both
1556/// null. Null-ness for function members is determined by the first field,
1557/// while for data member pointers we must compare all fields.
1558llvm::Value *
1559MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1560 llvm::Value *L,
1561 llvm::Value *R,
1562 const MemberPointerType *MPT,
1563 bool Inequality) {
1564 CGBuilderTy &Builder = CGF.Builder;
1565
1566 // Handle != comparisons by switching the sense of all boolean operations.
1567 llvm::ICmpInst::Predicate Eq;
1568 llvm::Instruction::BinaryOps And, Or;
1569 if (Inequality) {
1570 Eq = llvm::ICmpInst::ICMP_NE;
1571 And = llvm::Instruction::Or;
1572 Or = llvm::Instruction::And;
1573 } else {
1574 Eq = llvm::ICmpInst::ICMP_EQ;
1575 And = llvm::Instruction::And;
1576 Or = llvm::Instruction::Or;
1577 }
1578
1579 // If this is a single field member pointer (single inheritance), this is a
1580 // single icmp.
1581 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1582 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001583 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001584 return Builder.CreateICmp(Eq, L, R);
1585
1586 // Compare the first field.
1587 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1588 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1589 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1590
1591 // Compare everything other than the first field.
1592 llvm::Value *Res = 0;
1593 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1594 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1595 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1596 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1597 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1598 if (Res)
1599 Res = Builder.CreateBinOp(And, Res, Cmp);
1600 else
1601 Res = Cmp;
1602 }
1603
1604 // Check if the first field is 0 if this is a function pointer.
1605 if (MPT->isMemberFunctionPointer()) {
1606 // (l1 == r1 && ...) || l0 == 0
1607 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1608 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1609 Res = Builder.CreateBinOp(Or, Res, IsZero);
1610 }
1611
1612 // Combine the comparison of the first field, which must always be true for
1613 // this comparison to succeeed.
1614 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1615}
1616
Reid Kleckner407e8b62013-03-22 19:02:54 +00001617llvm::Value *
1618MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1619 llvm::Value *MemPtr,
1620 const MemberPointerType *MPT) {
1621 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001622 llvm::SmallVector<llvm::Constant *, 4> fields;
1623 // We only need one field for member functions.
1624 if (MPT->isMemberFunctionPointer())
1625 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1626 else
1627 GetNullMemberPointerFields(MPT, fields);
1628 assert(!fields.empty());
1629 llvm::Value *FirstField = MemPtr;
1630 if (MemPtr->getType()->isStructTy())
1631 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1632 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001633
Reid Kleckner2341ae32013-04-11 18:13:19 +00001634 // For function member pointers, we only need to test the function pointer
1635 // field. The other fields if any can be garbage.
1636 if (MPT->isMemberFunctionPointer())
1637 return Res;
1638
1639 // Otherwise, emit a series of compares and combine the results.
1640 for (int I = 1, E = fields.size(); I < E; ++I) {
1641 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1642 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1643 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1644 }
1645 return Res;
1646}
1647
Reid Kleckner452abac2013-05-09 21:01:17 +00001648bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1649 llvm::Constant *Val) {
1650 // Function pointers are null if the pointer in the first field is null.
1651 if (MPT->isMemberFunctionPointer()) {
1652 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1653 Val->getAggregateElement(0U) : Val;
1654 return FirstField->isNullValue();
1655 }
1656
1657 // If it's not a function pointer and it's zero initializable, we can easily
1658 // check zero.
1659 if (isZeroInitializable(MPT) && Val->isNullValue())
1660 return true;
1661
1662 // Otherwise, break down all the fields for comparison. Hopefully these
1663 // little Constants are reused, while a big null struct might not be.
1664 llvm::SmallVector<llvm::Constant *, 4> Fields;
1665 GetNullMemberPointerFields(MPT, Fields);
1666 if (Fields.size() == 1) {
1667 assert(Val->getType()->isIntegerTy());
1668 return Val == Fields[0];
1669 }
1670
1671 unsigned I, E;
1672 for (I = 0, E = Fields.size(); I != E; ++I) {
1673 if (Val->getAggregateElement(I) != Fields[I])
1674 break;
1675 }
1676 return I == E;
1677}
1678
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001679llvm::Value *
1680MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1681 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001682 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001683 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001684 llvm::Value **VBPtrOut) {
1685 CGBuilderTy &Builder = CGF.Builder;
1686 // Load the vbtable pointer from the vbptr in the instance.
1687 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1688 llvm::Value *VBPtr =
1689 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1690 if (VBPtrOut) *VBPtrOut = VBPtr;
1691 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1692 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1693
1694 // Load an i32 offset from the vb-table.
1695 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1696 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1697 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1698}
1699
Reid Kleckner2341ae32013-04-11 18:13:19 +00001700// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1701// it.
1702llvm::Value *
1703MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1704 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001705 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001706 llvm::Value *VBPtrOffset) {
1707 CGBuilderTy &Builder = CGF.Builder;
1708 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1709 llvm::BasicBlock *OriginalBB = 0;
1710 llvm::BasicBlock *SkipAdjustBB = 0;
1711 llvm::BasicBlock *VBaseAdjustBB = 0;
1712
1713 // In the unspecified inheritance model, there might not be a vbtable at all,
1714 // in which case we need to skip the virtual base lookup. If there is a
1715 // vbtable, the first entry is a no-op entry that gives back the original
1716 // base, so look for a virtual base adjustment offset of zero.
1717 if (VBPtrOffset) {
1718 OriginalBB = Builder.GetInsertBlock();
1719 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1720 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1721 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001722 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001723 "memptr.is_vbase");
1724 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1725 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001726 }
1727
Reid Kleckner2341ae32013-04-11 18:13:19 +00001728 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1729 // know the vbptr offset.
1730 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001731 CharUnits offs = CharUnits::Zero();
Reid Kleckner5b1b5d52014-01-14 00:50:39 +00001732 if (RD->getNumVBases())
1733 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001734 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1735 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001736 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001737 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001738 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001739 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1740
1741 // Merge control flow with the case where we didn't have to adjust.
1742 if (VBaseAdjustBB) {
1743 Builder.CreateBr(SkipAdjustBB);
1744 CGF.EmitBlock(SkipAdjustBB);
1745 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1746 Phi->addIncoming(Base, OriginalBB);
1747 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1748 return Phi;
1749 }
1750 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001751}
1752
1753llvm::Value *
1754MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1755 llvm::Value *Base,
1756 llvm::Value *MemPtr,
1757 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001758 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001759 unsigned AS = Base->getType()->getPointerAddressSpace();
1760 llvm::Type *PType =
1761 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1762 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001763 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1764 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001765
Reid Kleckner2341ae32013-04-11 18:13:19 +00001766 // Extract the fields we need, regardless of model. We'll apply them if we
1767 // have them.
1768 llvm::Value *FieldOffset = MemPtr;
1769 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1770 llvm::Value *VBPtrOffset = 0;
1771 if (MemPtr->getType()->isStructTy()) {
1772 // We need to extract values.
1773 unsigned I = 0;
1774 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1775 if (hasVBPtrOffsetField(Inheritance))
1776 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1777 if (hasVirtualBaseAdjustmentField(Inheritance))
1778 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001779 }
1780
Reid Kleckner2341ae32013-04-11 18:13:19 +00001781 if (VirtualBaseAdjustmentOffset) {
1782 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1783 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001784 }
Reid Klecknerae945122013-12-05 22:44:07 +00001785
1786 // Cast to char*.
1787 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1788
1789 // Apply the offset, which we assume is non-null.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001790 llvm::Value *Addr =
1791 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001792
1793 // Cast the address to the appropriate pointer type, adopting the address
1794 // space of the base pointer.
1795 return Builder.CreateBitCast(Addr, PType);
1796}
1797
Reid Kleckner452abac2013-05-09 21:01:17 +00001798static MSInheritanceModel
1799getInheritanceFromMemptr(const MemberPointerType *MPT) {
1800 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1801}
1802
1803llvm::Value *
1804MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1805 const CastExpr *E,
1806 llvm::Value *Src) {
1807 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1808 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1809 E->getCastKind() == CK_ReinterpretMemberPointer);
1810
1811 // Use constant emission if we can.
1812 if (isa<llvm::Constant>(Src))
1813 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1814
1815 // We may be adding or dropping fields from the member pointer, so we need
1816 // both types and the inheritance models of both records.
1817 const MemberPointerType *SrcTy =
1818 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1819 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1820 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1821 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1822 bool IsFunc = SrcTy->isMemberFunctionPointer();
1823
1824 // If the classes use the same null representation, reinterpret_cast is a nop.
1825 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1826 if (IsReinterpret && (IsFunc ||
1827 nullFieldOffsetIsZero(SrcInheritance) ==
1828 nullFieldOffsetIsZero(DstInheritance)))
1829 return Src;
1830
1831 CGBuilderTy &Builder = CGF.Builder;
1832
1833 // Branch past the conversion if Src is null.
1834 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1835 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1836
1837 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1838 // pointer value of the destination type.
1839 if (IsReinterpret) {
1840 // For reinterpret casts, sema ensures that src and dst are both functions
1841 // or data and have the same size, which means the LLVM types should match.
1842 assert(Src->getType() == DstNull->getType());
1843 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1844 }
1845
1846 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1847 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1848 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1849 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1850 CGF.EmitBlock(ConvertBB);
1851
1852 // Decompose src.
1853 llvm::Value *FirstField = Src;
1854 llvm::Value *NonVirtualBaseAdjustment = 0;
1855 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1856 llvm::Value *VBPtrOffset = 0;
1857 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1858 // We need to extract values.
1859 unsigned I = 0;
1860 FirstField = Builder.CreateExtractValue(Src, I++);
1861 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1862 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1863 if (hasVBPtrOffsetField(SrcInheritance))
1864 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1865 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1866 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1867 }
1868
1869 // For data pointers, we adjust the field offset directly. For functions, we
1870 // have a separate field.
1871 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1872 if (Adj) {
1873 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1874 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1875 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1876 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1877 NVAdjustField = getZeroInt();
1878 if (isDerivedToBase)
1879 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1880 else
1881 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1882 }
1883
1884 // FIXME PR15713: Support conversions through virtually derived classes.
1885
1886 // Recompose dst from the null struct and the adjusted fields from src.
1887 llvm::Value *Dst;
1888 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1889 Dst = FirstField;
1890 } else {
1891 Dst = llvm::UndefValue::get(DstNull->getType());
1892 unsigned Idx = 0;
1893 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1894 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1895 Dst = Builder.CreateInsertValue(
1896 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1897 if (hasVBPtrOffsetField(DstInheritance))
1898 Dst = Builder.CreateInsertValue(
1899 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1900 if (hasVirtualBaseAdjustmentField(DstInheritance))
1901 Dst = Builder.CreateInsertValue(
1902 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1903 }
1904 Builder.CreateBr(ContinueBB);
1905
1906 // In the continuation, choose between DstNull and Dst.
1907 CGF.EmitBlock(ContinueBB);
1908 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1909 Phi->addIncoming(DstNull, OriginalBB);
1910 Phi->addIncoming(Dst, ConvertBB);
1911 return Phi;
1912}
1913
1914llvm::Constant *
1915MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1916 llvm::Constant *Src) {
1917 const MemberPointerType *SrcTy =
1918 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1919 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1920
1921 // If src is null, emit a new null for dst. We can't return src because dst
1922 // might have a new representation.
1923 if (MemberPointerConstantIsNull(SrcTy, Src))
1924 return EmitNullMemberPointer(DstTy);
1925
1926 // We don't need to do anything for reinterpret_casts of non-null member
1927 // pointers. We should only get here when the two type representations have
1928 // the same size.
1929 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1930 return Src;
1931
1932 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1933 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1934
1935 // Decompose src.
1936 llvm::Constant *FirstField = Src;
1937 llvm::Constant *NonVirtualBaseAdjustment = 0;
1938 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1939 llvm::Constant *VBPtrOffset = 0;
1940 bool IsFunc = SrcTy->isMemberFunctionPointer();
1941 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1942 // We need to extract values.
1943 unsigned I = 0;
1944 FirstField = Src->getAggregateElement(I++);
1945 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1946 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1947 if (hasVBPtrOffsetField(SrcInheritance))
1948 VBPtrOffset = Src->getAggregateElement(I++);
1949 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1950 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1951 }
1952
1953 // For data pointers, we adjust the field offset directly. For functions, we
1954 // have a separate field.
1955 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1956 if (Adj) {
1957 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1958 llvm::Constant *&NVAdjustField =
1959 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1960 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1961 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1962 NVAdjustField = getZeroInt();
1963 if (IsDerivedToBase)
1964 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1965 else
1966 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1967 }
1968
1969 // FIXME PR15713: Support conversions through virtually derived classes.
1970
1971 // Recompose dst from the null struct and the adjusted fields from src.
1972 if (hasOnlyOneField(IsFunc, DstInheritance))
1973 return FirstField;
1974
1975 llvm::SmallVector<llvm::Constant *, 4> Fields;
1976 Fields.push_back(FirstField);
1977 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1978 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1979 if (hasVBPtrOffsetField(DstInheritance))
1980 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1981 if (hasVirtualBaseAdjustmentField(DstInheritance))
1982 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1983 return llvm::ConstantStruct::getAnon(Fields);
1984}
1985
Reid Kleckner2341ae32013-04-11 18:13:19 +00001986llvm::Value *
1987MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1988 llvm::Value *&This,
1989 llvm::Value *MemPtr,
1990 const MemberPointerType *MPT) {
1991 assert(MPT->isMemberFunctionPointer());
1992 const FunctionProtoType *FPT =
1993 MPT->getPointeeType()->castAs<FunctionProtoType>();
1994 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1995 llvm::FunctionType *FTy =
1996 CGM.getTypes().GetFunctionType(
1997 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1998 CGBuilderTy &Builder = CGF.Builder;
1999
2000 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2001
2002 // Extract the fields we need, regardless of model. We'll apply them if we
2003 // have them.
2004 llvm::Value *FunctionPointer = MemPtr;
2005 llvm::Value *NonVirtualBaseAdjustment = NULL;
2006 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
2007 llvm::Value *VBPtrOffset = NULL;
2008 if (MemPtr->getType()->isStructTy()) {
2009 // We need to extract values.
2010 unsigned I = 0;
2011 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002012 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
2013 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00002014 if (hasVBPtrOffsetField(Inheritance))
2015 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002016 if (hasVirtualBaseAdjustmentField(Inheritance))
2017 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2018 }
2019
2020 if (VirtualBaseAdjustmentOffset) {
2021 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
2022 VBPtrOffset);
2023 }
2024
2025 if (NonVirtualBaseAdjustment) {
2026 // Apply the adjustment and cast back to the original struct type.
2027 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2028 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2029 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2030 }
2031
2032 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2033}
2034
Charles Davis53c59df2010-08-16 03:33:14 +00002035CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00002036 return new MicrosoftCXXABI(CGM);
2037}