blob: 875591d0df9c1ac1917a1bbfe8c848019beb61bc [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.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001325static bool hasVBPtrOffsetField(MSInheritanceAttr::Spelling Inheritance) {
1326 return Inheritance == MSInheritanceAttr::Keyword_unspecified_inheritance;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001327}
1328
Reid Kleckner452abac2013-05-09 21:01:17 +00001329static bool hasOnlyOneField(bool IsMemberFunction,
David Majnemer1cdd96d2014-01-17 09:01:00 +00001330 MSInheritanceAttr::Spelling Inheritance) {
1331 if (IsMemberFunction)
1332 return Inheritance <= MSInheritanceAttr::Keyword_single_inheritance;
1333 return Inheritance <= MSInheritanceAttr::Keyword_multiple_inheritance;
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001334}
1335
Reid Kleckner2341ae32013-04-11 18:13:19 +00001336// Only member pointers to functions need a this adjustment, since it can be
1337// combined with the field offset for data pointers.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001338static bool
1339hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
1340 MSInheritanceAttr::Spelling Inheritance) {
1341 return IsMemberFunction &&
1342 Inheritance >= MSInheritanceAttr::Keyword_multiple_inheritance;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001343}
1344
David Majnemer1cdd96d2014-01-17 09:01:00 +00001345static bool
1346hasVirtualBaseAdjustmentField(MSInheritanceAttr::Spelling Inheritance) {
1347 return Inheritance >= MSInheritanceAttr::Keyword_virtual_inheritance;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001348}
1349
1350// Use zero for the field offset of a null data member pointer if we can
1351// guarantee that zero is not a valid field offset, or if the member pointer has
1352// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1353// use zero for null. If there are multiple fields, we can use zero even if it
1354// is a valid field offset because null-ness testing will check the other
1355// fields.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001356static bool nullFieldOffsetIsZero(const CXXRecordDecl *RD) {
1357 return RD->getMSInheritanceModel() >=
1358 MSInheritanceAttr::Keyword_virtual_inheritance ||
1359 (RD->hasDefinition() && RD->isPolymorphic());
Reid Kleckner2341ae32013-04-11 18:13:19 +00001360}
1361
1362bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1363 // Null-ness for function memptrs only depends on the first field, which is
1364 // the function pointer. The rest don't matter, so we can zero initialize.
1365 if (MPT->isMemberFunctionPointer())
1366 return true;
1367
1368 // The virtual base adjustment field is always -1 for null, so if we have one
1369 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1370 // valid field offset.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001371 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1372 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001373 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
David Majnemer1cdd96d2014-01-17 09:01:00 +00001374 nullFieldOffsetIsZero(RD));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001375}
1376
1377llvm::Type *
1378MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001379 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1380 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001381 llvm::SmallVector<llvm::Type *, 4> fields;
1382 if (MPT->isMemberFunctionPointer())
1383 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1384 else
1385 fields.push_back(CGM.IntTy); // FieldOffset
1386
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001387 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1388 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001389 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001390 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001391 fields.push_back(CGM.IntTy);
1392 if (hasVirtualBaseAdjustmentField(Inheritance))
1393 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1394
1395 if (fields.size() == 1)
1396 return fields[0];
1397 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1398}
1399
1400void MicrosoftCXXABI::
1401GetNullMemberPointerFields(const MemberPointerType *MPT,
1402 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1403 assert(fields.empty());
David Majnemer1cdd96d2014-01-17 09:01:00 +00001404 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1405 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001406 if (MPT->isMemberFunctionPointer()) {
1407 // FunctionPointerOrVirtualThunk
1408 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1409 } else {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001410 if (nullFieldOffsetIsZero(RD))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001411 fields.push_back(getZeroInt()); // FieldOffset
1412 else
1413 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001414 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001415
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001416 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1417 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001418 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001419 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001420 fields.push_back(getZeroInt());
1421 if (hasVirtualBaseAdjustmentField(Inheritance))
1422 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001423}
1424
1425llvm::Constant *
1426MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001427 llvm::SmallVector<llvm::Constant *, 4> fields;
1428 GetNullMemberPointerFields(MPT, fields);
1429 if (fields.size() == 1)
1430 return fields[0];
1431 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1432 assert(Res->getType() == ConvertMemberPointerType(MPT));
1433 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001434}
1435
1436llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001437MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1438 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001439 const CXXRecordDecl *RD,
1440 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001441{
David Majnemer1cdd96d2014-01-17 09:01:00 +00001442 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001443
1444 // Single inheritance class member pointer are represented as scalars instead
1445 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001446 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001447 return FirstField;
1448
Reid Kleckner2341ae32013-04-11 18:13:19 +00001449 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001450 fields.push_back(FirstField);
1451
1452 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001453 fields.push_back(llvm::ConstantInt::get(
1454 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001455
Reid Kleckner2341ae32013-04-11 18:13:19 +00001456 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001457 CharUnits Offs = CharUnits::Zero();
1458 if (RD->getNumVBases())
Reid Kleckner5b1b5d52014-01-14 00:50:39 +00001459 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
Reid Kleckneraec44092013-10-15 01:18:02 +00001460 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001461 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001462
1463 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001464 if (hasVirtualBaseAdjustmentField(Inheritance))
1465 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001466
Reid Kleckner2341ae32013-04-11 18:13:19 +00001467 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001468}
1469
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001470llvm::Constant *
1471MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1472 CharUnits offset) {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001473 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001474 llvm::Constant *FirstField =
1475 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001476 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1477 CharUnits::Zero());
1478}
1479
1480llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1481 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1482}
1483
1484llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1485 QualType MPType) {
1486 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1487 const ValueDecl *MPD = MP.getMemberPointerDecl();
1488 if (!MPD)
1489 return EmitNullMemberPointer(MPT);
1490
1491 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1492
1493 // FIXME PR15713: Support virtual inheritance paths.
1494
1495 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
David Majnemer1cdd96d2014-01-17 09:01:00 +00001496 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
1497 ThisAdjustment);
Reid Kleckner452abac2013-05-09 21:01:17 +00001498
1499 CharUnits FieldOffset =
1500 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1501 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001502}
1503
1504llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001505MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1506 const CXXMethodDecl *MD,
1507 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001508 assert(MD->isInstance() && "Member function must not be static!");
1509 MD = MD->getCanonicalDecl();
David Majnemer1cdd96d2014-01-17 09:01:00 +00001510 RD = RD->getMostRecentDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001511 CodeGenTypes &Types = CGM.getTypes();
1512
1513 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001514 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001515 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1516 llvm::Type *Ty;
1517 // Check whether the function has a computable LLVM signature.
1518 if (Types.isFuncTypeConvertible(FPT)) {
1519 // The function has a computable LLVM signature; use the correct type.
1520 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1521 } else {
1522 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1523 // function type is incomplete.
1524 Ty = CGM.PtrDiffTy;
1525 }
1526 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1527 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001528 } else {
1529 MicrosoftVTableContext::MethodVFTableLocation ML =
1530 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1531 if (MD->isVariadic()) {
1532 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1533 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1534 } else if (!CGM.getTypes().isFuncTypeConvertible(
1535 MD->getType()->castAs<FunctionType>())) {
1536 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1537 "incomplete return or parameter type");
1538 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1539 } else if (ML.VBase) {
1540 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1541 "member function in virtual base class");
1542 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1543 } else {
1544 SmallString<256> ThunkName;
David Majnemer2a816452013-12-09 10:44:32 +00001545 CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1546 getContext().getTargetInfo().getPointerWidth(0));
1547 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
Hans Wennborg88497d62013-11-15 17:24:45 +00001548 llvm::raw_svector_ostream Out(ThunkName);
1549 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1550 Out.flush();
1551
1552 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1553 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1554 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001555 }
1556
1557 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001558 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1559 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001560}
1561
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001562/// Member pointers are the same if they're either bitwise identical *or* both
1563/// null. Null-ness for function members is determined by the first field,
1564/// while for data member pointers we must compare all fields.
1565llvm::Value *
1566MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1567 llvm::Value *L,
1568 llvm::Value *R,
1569 const MemberPointerType *MPT,
1570 bool Inequality) {
1571 CGBuilderTy &Builder = CGF.Builder;
1572
1573 // Handle != comparisons by switching the sense of all boolean operations.
1574 llvm::ICmpInst::Predicate Eq;
1575 llvm::Instruction::BinaryOps And, Or;
1576 if (Inequality) {
1577 Eq = llvm::ICmpInst::ICMP_NE;
1578 And = llvm::Instruction::Or;
1579 Or = llvm::Instruction::And;
1580 } else {
1581 Eq = llvm::ICmpInst::ICMP_EQ;
1582 And = llvm::Instruction::And;
1583 Or = llvm::Instruction::Or;
1584 }
1585
1586 // If this is a single field member pointer (single inheritance), this is a
1587 // single icmp.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001588 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1589 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001590 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001591 return Builder.CreateICmp(Eq, L, R);
1592
1593 // Compare the first field.
1594 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1595 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1596 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1597
1598 // Compare everything other than the first field.
1599 llvm::Value *Res = 0;
1600 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1601 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1602 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1603 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1604 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1605 if (Res)
1606 Res = Builder.CreateBinOp(And, Res, Cmp);
1607 else
1608 Res = Cmp;
1609 }
1610
1611 // Check if the first field is 0 if this is a function pointer.
1612 if (MPT->isMemberFunctionPointer()) {
1613 // (l1 == r1 && ...) || l0 == 0
1614 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1615 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1616 Res = Builder.CreateBinOp(Or, Res, IsZero);
1617 }
1618
1619 // Combine the comparison of the first field, which must always be true for
1620 // this comparison to succeeed.
1621 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1622}
1623
Reid Kleckner407e8b62013-03-22 19:02:54 +00001624llvm::Value *
1625MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1626 llvm::Value *MemPtr,
1627 const MemberPointerType *MPT) {
1628 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001629 llvm::SmallVector<llvm::Constant *, 4> fields;
1630 // We only need one field for member functions.
1631 if (MPT->isMemberFunctionPointer())
1632 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1633 else
1634 GetNullMemberPointerFields(MPT, fields);
1635 assert(!fields.empty());
1636 llvm::Value *FirstField = MemPtr;
1637 if (MemPtr->getType()->isStructTy())
1638 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1639 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001640
Reid Kleckner2341ae32013-04-11 18:13:19 +00001641 // For function member pointers, we only need to test the function pointer
1642 // field. The other fields if any can be garbage.
1643 if (MPT->isMemberFunctionPointer())
1644 return Res;
1645
1646 // Otherwise, emit a series of compares and combine the results.
1647 for (int I = 1, E = fields.size(); I < E; ++I) {
1648 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1649 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1650 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1651 }
1652 return Res;
1653}
1654
Reid Kleckner452abac2013-05-09 21:01:17 +00001655bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1656 llvm::Constant *Val) {
1657 // Function pointers are null if the pointer in the first field is null.
1658 if (MPT->isMemberFunctionPointer()) {
1659 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1660 Val->getAggregateElement(0U) : Val;
1661 return FirstField->isNullValue();
1662 }
1663
1664 // If it's not a function pointer and it's zero initializable, we can easily
1665 // check zero.
1666 if (isZeroInitializable(MPT) && Val->isNullValue())
1667 return true;
1668
1669 // Otherwise, break down all the fields for comparison. Hopefully these
1670 // little Constants are reused, while a big null struct might not be.
1671 llvm::SmallVector<llvm::Constant *, 4> Fields;
1672 GetNullMemberPointerFields(MPT, Fields);
1673 if (Fields.size() == 1) {
1674 assert(Val->getType()->isIntegerTy());
1675 return Val == Fields[0];
1676 }
1677
1678 unsigned I, E;
1679 for (I = 0, E = Fields.size(); I != E; ++I) {
1680 if (Val->getAggregateElement(I) != Fields[I])
1681 break;
1682 }
1683 return I == E;
1684}
1685
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001686llvm::Value *
1687MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1688 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001689 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001690 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001691 llvm::Value **VBPtrOut) {
1692 CGBuilderTy &Builder = CGF.Builder;
1693 // Load the vbtable pointer from the vbptr in the instance.
1694 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1695 llvm::Value *VBPtr =
1696 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1697 if (VBPtrOut) *VBPtrOut = VBPtr;
1698 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1699 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1700
1701 // Load an i32 offset from the vb-table.
1702 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1703 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1704 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1705}
1706
Reid Kleckner2341ae32013-04-11 18:13:19 +00001707// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1708// it.
1709llvm::Value *
1710MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1711 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001712 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001713 llvm::Value *VBPtrOffset) {
1714 CGBuilderTy &Builder = CGF.Builder;
1715 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1716 llvm::BasicBlock *OriginalBB = 0;
1717 llvm::BasicBlock *SkipAdjustBB = 0;
1718 llvm::BasicBlock *VBaseAdjustBB = 0;
1719
1720 // In the unspecified inheritance model, there might not be a vbtable at all,
1721 // in which case we need to skip the virtual base lookup. If there is a
1722 // vbtable, the first entry is a no-op entry that gives back the original
1723 // base, so look for a virtual base adjustment offset of zero.
1724 if (VBPtrOffset) {
1725 OriginalBB = Builder.GetInsertBlock();
1726 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1727 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1728 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001729 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001730 "memptr.is_vbase");
1731 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1732 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001733 }
1734
Reid Kleckner2341ae32013-04-11 18:13:19 +00001735 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1736 // know the vbptr offset.
1737 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001738 CharUnits offs = CharUnits::Zero();
Reid Kleckner5b1b5d52014-01-14 00:50:39 +00001739 if (RD->getNumVBases())
1740 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001741 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1742 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001743 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001744 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001745 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001746 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1747
1748 // Merge control flow with the case where we didn't have to adjust.
1749 if (VBaseAdjustBB) {
1750 Builder.CreateBr(SkipAdjustBB);
1751 CGF.EmitBlock(SkipAdjustBB);
1752 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1753 Phi->addIncoming(Base, OriginalBB);
1754 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1755 return Phi;
1756 }
1757 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001758}
1759
1760llvm::Value *
1761MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1762 llvm::Value *Base,
1763 llvm::Value *MemPtr,
1764 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001765 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001766 unsigned AS = Base->getType()->getPointerAddressSpace();
1767 llvm::Type *PType =
1768 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1769 CGBuilderTy &Builder = CGF.Builder;
David Majnemer1cdd96d2014-01-17 09:01:00 +00001770 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1771 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001772
Reid Kleckner2341ae32013-04-11 18:13:19 +00001773 // Extract the fields we need, regardless of model. We'll apply them if we
1774 // have them.
1775 llvm::Value *FieldOffset = MemPtr;
1776 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1777 llvm::Value *VBPtrOffset = 0;
1778 if (MemPtr->getType()->isStructTy()) {
1779 // We need to extract values.
1780 unsigned I = 0;
1781 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1782 if (hasVBPtrOffsetField(Inheritance))
1783 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1784 if (hasVirtualBaseAdjustmentField(Inheritance))
1785 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001786 }
1787
Reid Kleckner2341ae32013-04-11 18:13:19 +00001788 if (VirtualBaseAdjustmentOffset) {
1789 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1790 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001791 }
Reid Klecknerae945122013-12-05 22:44:07 +00001792
1793 // Cast to char*.
1794 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1795
1796 // Apply the offset, which we assume is non-null.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001797 llvm::Value *Addr =
1798 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001799
1800 // Cast the address to the appropriate pointer type, adopting the address
1801 // space of the base pointer.
1802 return Builder.CreateBitCast(Addr, PType);
1803}
1804
David Majnemer1cdd96d2014-01-17 09:01:00 +00001805static MSInheritanceAttr::Spelling
Reid Kleckner452abac2013-05-09 21:01:17 +00001806getInheritanceFromMemptr(const MemberPointerType *MPT) {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001807 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001808}
1809
1810llvm::Value *
1811MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1812 const CastExpr *E,
1813 llvm::Value *Src) {
1814 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1815 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1816 E->getCastKind() == CK_ReinterpretMemberPointer);
1817
1818 // Use constant emission if we can.
1819 if (isa<llvm::Constant>(Src))
1820 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1821
1822 // We may be adding or dropping fields from the member pointer, so we need
1823 // both types and the inheritance models of both records.
1824 const MemberPointerType *SrcTy =
1825 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1826 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
Reid Kleckner452abac2013-05-09 21:01:17 +00001827 bool IsFunc = SrcTy->isMemberFunctionPointer();
1828
1829 // If the classes use the same null representation, reinterpret_cast is a nop.
1830 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
David Majnemer1cdd96d2014-01-17 09:01:00 +00001831 if (IsReinterpret && IsFunc)
1832 return Src;
1833
1834 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
1835 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
1836 if (IsReinterpret &&
1837 nullFieldOffsetIsZero(SrcRD) == nullFieldOffsetIsZero(DstRD))
Reid Kleckner452abac2013-05-09 21:01:17 +00001838 return Src;
1839
1840 CGBuilderTy &Builder = CGF.Builder;
1841
1842 // Branch past the conversion if Src is null.
1843 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1844 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1845
1846 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1847 // pointer value of the destination type.
1848 if (IsReinterpret) {
1849 // For reinterpret casts, sema ensures that src and dst are both functions
1850 // or data and have the same size, which means the LLVM types should match.
1851 assert(Src->getType() == DstNull->getType());
1852 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1853 }
1854
1855 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1856 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1857 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1858 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1859 CGF.EmitBlock(ConvertBB);
1860
1861 // Decompose src.
1862 llvm::Value *FirstField = Src;
1863 llvm::Value *NonVirtualBaseAdjustment = 0;
1864 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1865 llvm::Value *VBPtrOffset = 0;
David Majnemer1cdd96d2014-01-17 09:01:00 +00001866 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001867 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1868 // We need to extract values.
1869 unsigned I = 0;
1870 FirstField = Builder.CreateExtractValue(Src, I++);
1871 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1872 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1873 if (hasVBPtrOffsetField(SrcInheritance))
1874 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1875 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1876 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1877 }
1878
1879 // For data pointers, we adjust the field offset directly. For functions, we
1880 // have a separate field.
1881 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1882 if (Adj) {
1883 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1884 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1885 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1886 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1887 NVAdjustField = getZeroInt();
1888 if (isDerivedToBase)
1889 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1890 else
1891 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1892 }
1893
1894 // FIXME PR15713: Support conversions through virtually derived classes.
1895
1896 // Recompose dst from the null struct and the adjusted fields from src.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001897 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001898 llvm::Value *Dst;
1899 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1900 Dst = FirstField;
1901 } else {
1902 Dst = llvm::UndefValue::get(DstNull->getType());
1903 unsigned Idx = 0;
1904 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1905 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1906 Dst = Builder.CreateInsertValue(
1907 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1908 if (hasVBPtrOffsetField(DstInheritance))
1909 Dst = Builder.CreateInsertValue(
1910 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1911 if (hasVirtualBaseAdjustmentField(DstInheritance))
1912 Dst = Builder.CreateInsertValue(
1913 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1914 }
1915 Builder.CreateBr(ContinueBB);
1916
1917 // In the continuation, choose between DstNull and Dst.
1918 CGF.EmitBlock(ContinueBB);
1919 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1920 Phi->addIncoming(DstNull, OriginalBB);
1921 Phi->addIncoming(Dst, ConvertBB);
1922 return Phi;
1923}
1924
1925llvm::Constant *
1926MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1927 llvm::Constant *Src) {
1928 const MemberPointerType *SrcTy =
1929 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1930 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1931
1932 // If src is null, emit a new null for dst. We can't return src because dst
1933 // might have a new representation.
1934 if (MemberPointerConstantIsNull(SrcTy, Src))
1935 return EmitNullMemberPointer(DstTy);
1936
1937 // We don't need to do anything for reinterpret_casts of non-null member
1938 // pointers. We should only get here when the two type representations have
1939 // the same size.
1940 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1941 return Src;
1942
David Majnemer1cdd96d2014-01-17 09:01:00 +00001943 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
1944 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
Reid Kleckner452abac2013-05-09 21:01:17 +00001945
1946 // Decompose src.
1947 llvm::Constant *FirstField = Src;
1948 llvm::Constant *NonVirtualBaseAdjustment = 0;
1949 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1950 llvm::Constant *VBPtrOffset = 0;
1951 bool IsFunc = SrcTy->isMemberFunctionPointer();
1952 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1953 // We need to extract values.
1954 unsigned I = 0;
1955 FirstField = Src->getAggregateElement(I++);
1956 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1957 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1958 if (hasVBPtrOffsetField(SrcInheritance))
1959 VBPtrOffset = Src->getAggregateElement(I++);
1960 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1961 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1962 }
1963
1964 // For data pointers, we adjust the field offset directly. For functions, we
1965 // have a separate field.
1966 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1967 if (Adj) {
1968 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1969 llvm::Constant *&NVAdjustField =
1970 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1971 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1972 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1973 NVAdjustField = getZeroInt();
1974 if (IsDerivedToBase)
1975 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1976 else
1977 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1978 }
1979
1980 // FIXME PR15713: Support conversions through virtually derived classes.
1981
1982 // Recompose dst from the null struct and the adjusted fields from src.
1983 if (hasOnlyOneField(IsFunc, DstInheritance))
1984 return FirstField;
1985
1986 llvm::SmallVector<llvm::Constant *, 4> Fields;
1987 Fields.push_back(FirstField);
1988 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1989 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1990 if (hasVBPtrOffsetField(DstInheritance))
1991 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1992 if (hasVirtualBaseAdjustmentField(DstInheritance))
1993 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1994 return llvm::ConstantStruct::getAnon(Fields);
1995}
1996
Reid Kleckner2341ae32013-04-11 18:13:19 +00001997llvm::Value *
1998MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1999 llvm::Value *&This,
2000 llvm::Value *MemPtr,
2001 const MemberPointerType *MPT) {
2002 assert(MPT->isMemberFunctionPointer());
2003 const FunctionProtoType *FPT =
2004 MPT->getPointeeType()->castAs<FunctionProtoType>();
David Majnemer1cdd96d2014-01-17 09:01:00 +00002005 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
Reid Kleckner2341ae32013-04-11 18:13:19 +00002006 llvm::FunctionType *FTy =
2007 CGM.getTypes().GetFunctionType(
2008 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2009 CGBuilderTy &Builder = CGF.Builder;
2010
David Majnemer1cdd96d2014-01-17 09:01:00 +00002011 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00002012
2013 // Extract the fields we need, regardless of model. We'll apply them if we
2014 // have them.
2015 llvm::Value *FunctionPointer = MemPtr;
2016 llvm::Value *NonVirtualBaseAdjustment = NULL;
2017 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
2018 llvm::Value *VBPtrOffset = NULL;
2019 if (MemPtr->getType()->isStructTy()) {
2020 // We need to extract values.
2021 unsigned I = 0;
2022 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002023 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
2024 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00002025 if (hasVBPtrOffsetField(Inheritance))
2026 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002027 if (hasVirtualBaseAdjustmentField(Inheritance))
2028 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2029 }
2030
2031 if (VirtualBaseAdjustmentOffset) {
2032 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
2033 VBPtrOffset);
2034 }
2035
2036 if (NonVirtualBaseAdjustment) {
2037 // Apply the adjustment and cast back to the original struct type.
2038 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2039 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2040 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2041 }
2042
2043 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2044}
2045
Charles Davis53c59df2010-08-16 03:33:14 +00002046CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00002047 return new MicrosoftCXXABI(CGM);
2048}