blob: 7452c860d0be0e92e985760dec928b2d6a7854c5 [file] [log] [blame]
Charles Davisc3926642010-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davisc3926642010-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"
18#include "CodeGenModule.h"
Reid Kleckner90633022013-06-19 15:20:38 +000019#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
Charles Davisc3926642010-06-09 23:25:41 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanov635de282013-07-30 09:46:19 +000023#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +000024#include "llvm/ADT/StringSet.h"
Charles Davisc3926642010-06-09 23:25:41 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
Charles Davis071cc7d2010-08-16 03:33:14 +000031class MicrosoftCXXABI : public CGCXXABI {
Charles Davisc3926642010-06-09 23:25:41 +000032public:
Peter Collingbourne14110472011-01-13 18:57:25 +000033 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall4c40d982010-08-31 07:33:07 +000034
Stephen Lin3b50e8d2013-06-30 20:40:16 +000035 bool HasThisReturn(GlobalDecl GD) const;
36
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000037 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
38 // Structures that are not C++03 PODs are always indirect.
39 return !RD->isPOD();
40 }
41
42 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner9b601952013-06-21 12:45:15 +000043 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000044 return RAA_DirectInMemory;
45 return RAA_Default;
46 }
47
Joao Matos285baac2012-07-17 17:10:11 +000048 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikie2eb9a952012-10-16 22:56:05 +000049 // No known support for deleted functions in MSVC yet, so this choice is
50 // arbitrary.
51 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos285baac2012-07-17 17:10:11 +000052
John McCallecd03b42012-09-25 10:10:39 +000053 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
54 llvm::Value *ptr,
55 QualType type);
56
Reid Klecknerb0f533e2013-05-29 18:02:47 +000057 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
58 llvm::Value *This,
59 const CXXRecordDecl *ClassDecl,
60 const CXXRecordDecl *BaseClassDecl);
61
John McCall4c40d982010-08-31 07:33:07 +000062 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
63 CXXCtorType Type,
64 CanQualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +000065 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +000066
Reid Kleckner90633022013-06-19 15:20:38 +000067 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
68 const CXXRecordDecl *RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000069
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +000070 void EmitCXXConstructors(const CXXConstructorDecl *D);
71
Reid Klecknera4130ba2013-07-22 13:51:44 +000072 // Background on MSVC destructors
73 // ==============================
74 //
75 // Both Itanium and MSVC ABIs have destructor variants. The variant names
76 // roughly correspond in the following way:
77 // Itanium Microsoft
78 // Base -> no name, just ~Class
79 // Complete -> vbase destructor
80 // Deleting -> scalar deleting destructor
81 // vector deleting destructor
82 //
83 // The base and complete destructors are the same as in Itanium, although the
84 // complete destructor does not accept a VTT parameter when there are virtual
85 // bases. A separate mechanism involving vtordisps is used to ensure that
86 // virtual methods of destroyed subobjects are not called.
87 //
88 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
89 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
90 // pointer points to an array. The scalar deleting destructor assumes that
91 // bit 2 is zero, and therefore does not contain a loop.
92 //
93 // For virtual destructors, only one entry is reserved in the vftable, and it
94 // always points to the vector deleting destructor. The vector deleting
95 // destructor is the most general, so it can be used to destroy objects in
96 // place, delete single heap objects, or delete arrays.
97 //
98 // A TU defining a non-inline destructor is only guaranteed to emit a base
99 // destructor, and all of the other variants are emitted on an as-needed basis
100 // in COMDATs. Because a non-base destructor can be emitted in a TU that
101 // lacks a definition for the destructor, non-base destructors must always
102 // delegate to or alias the base destructor.
103
104 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall4c40d982010-08-31 07:33:07 +0000105 CXXDtorType Type,
106 CanQualType &ResTy,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000107 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000108
Reid Klecknera4130ba2013-07-22 13:51:44 +0000109 /// Non-base dtors should be emitted as delegating thunks in this ABI.
110 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
111 CXXDtorType DT) const {
112 return DT != Dtor_Base;
113 }
114
115 void EmitCXXDestructors(const CXXDestructorDecl *D);
116
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000117 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
118 MD = MD->getCanonicalDecl();
119 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
120 MicrosoftVFTableContext::MethodVFTableLocation ML =
121 CGM.getVFTableContext().getMethodVFTableLocation(MD);
122 // The vbases might be ordered differently in the final overrider object
123 // and the complete object, so the "this" argument may sometimes point to
124 // memory that has no particular type (e.g. past the complete object).
125 // In this case, we just use a generic pointer type.
126 // FIXME: might want to have a more precise type in the non-virtual
127 // multiple inheritance case.
128 if (ML.VBase || !ML.VFTableOffset.isZero())
129 return 0;
130 }
131 return MD->getParent();
132 }
133
134 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
135 GlobalDecl GD,
136 llvm::Value *This);
137
John McCall4c40d982010-08-31 07:33:07 +0000138 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
139 QualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +0000140 FunctionArgList &Params);
John McCall4c40d982010-08-31 07:33:07 +0000141
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000142 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
143 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
144
John McCallbd315742012-09-25 08:00:39 +0000145 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCallfd708262011-01-27 02:46:02 +0000146
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000147 void EmitConstructorCall(CodeGenFunction &CGF,
148 const CXXConstructorDecl *D, CXXCtorType Type,
149 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000150 llvm::Value *This,
151 CallExpr::const_arg_iterator ArgBeg,
152 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000153
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000154 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
155
156 llvm::Value *getVTableAddressPointInStructor(
157 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
158 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
159 bool &NeedsVirtualOffset);
160
161 llvm::Constant *
162 getVTableAddressPointForConstExpr(BaseSubobject Base,
163 const CXXRecordDecl *VTableClass);
164
165 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
166 CharUnits VPtrOffset);
167
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000168 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
169 llvm::Value *This, llvm::Type *Ty);
170
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000171 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
172 const CXXDestructorDecl *Dtor,
173 CXXDtorType DtorType, SourceLocation CallLoc,
174 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000175
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000176 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
177 CallArgList &CallArgs) {
178 assert(GD.getDtorType() == Dtor_Deleting &&
179 "Only deleting destructor thunks are available in this ABI");
180 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
181 CGM.getContext().IntTy);
182 }
183
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000184 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner90633022013-06-19 15:20:38 +0000185
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000186 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
187 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
188 }
189
John McCall20bb1752012-05-01 06:13:13 +0000190 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
191 llvm::GlobalVariable *DeclPtr,
192 bool PerformInit);
193
John McCallfd708262011-01-27 02:46:02 +0000194 // ==== Notes on array cookies =========
195 //
196 // MSVC seems to only use cookies when the class has a destructor; a
197 // two-argument usual array deallocation function isn't sufficient.
198 //
199 // For example, this code prints "100" and "1":
200 // struct A {
201 // char x;
202 // void *operator new[](size_t sz) {
203 // printf("%u\n", sz);
204 // return malloc(sz);
205 // }
206 // void operator delete[](void *p, size_t sz) {
207 // printf("%u\n", sz);
208 // free(p);
209 // }
210 // };
211 // int main() {
212 // A *p = new A[100];
213 // delete[] p;
214 // }
215 // Whereas it prints "104" and "104" if you give A a destructor.
John McCalle2b45e22012-05-01 05:23:51 +0000216
217 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
218 bool requiresArrayCookie(const CXXNewExpr *expr);
219 CharUnits getArrayCookieSizeImpl(QualType type);
220 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
221 llvm::Value *NewPtr,
222 llvm::Value *NumElements,
223 const CXXNewExpr *expr,
224 QualType ElementType);
225 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
226 llvm::Value *allocPtr,
227 CharUnits cookieSize);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000228
229private:
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000230 MicrosoftMangleContext &getMangleContext() {
231 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
232 }
233
Reid Klecknera3609b02013-04-11 18:13:19 +0000234 llvm::Constant *getZeroInt() {
235 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000236 }
237
Reid Klecknera3609b02013-04-11 18:13:19 +0000238 llvm::Constant *getAllOnesInt() {
239 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000240 }
241
Reid Klecknerf6327302013-05-09 21:01:17 +0000242 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
243 return C ? C : getZeroInt();
244 }
245
246 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
247 return C ? C : getZeroInt();
248 }
249
Reid Klecknera3609b02013-04-11 18:13:19 +0000250 void
251 GetNullMemberPointerFields(const MemberPointerType *MPT,
252 llvm::SmallVectorImpl<llvm::Constant *> &fields);
253
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000254 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
255 /// it is reusing a vbptr from a non-virtual base. RD must have morally
256 /// virtual bases.
257 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
258
259 /// \brief Shared code for virtual base adjustment. Returns the offset from
260 /// the vbptr to the virtual base. Optionally returns the address of the
261 /// vbptr itself.
262 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
263 llvm::Value *Base,
264 llvm::Value *VBPtrOffset,
265 llvm::Value *VBTableOffset,
266 llvm::Value **VBPtr = 0);
267
268 /// \brief Performs a full virtual base adjustment. Used to dereference
269 /// pointers to members of virtual bases.
Reid Klecknera3609b02013-04-11 18:13:19 +0000270 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
271 llvm::Value *Base,
272 llvm::Value *VirtualBaseAdjustmentOffset,
273 llvm::Value *VBPtrOffset /* optional */);
274
Reid Kleckner79e02912013-05-03 01:15:11 +0000275 /// \brief Emits a full member pointer with the fields common to data and
276 /// function member pointers.
277 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
278 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000279 const CXXRecordDecl *RD,
280 CharUnits NonVirtualBaseAdjustment);
281
282 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
283 const CXXMethodDecl *MD,
284 CharUnits NonVirtualBaseAdjustment);
285
286 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
287 llvm::Constant *MP);
Reid Kleckner79e02912013-05-03 01:15:11 +0000288
Reid Kleckner90633022013-06-19 15:20:38 +0000289 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
290 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
291
292 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
293 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
294
Reid Klecknera8a0f762013-03-22 19:02:54 +0000295public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000296 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
297
298 virtual bool isZeroInitializable(const MemberPointerType *MPT);
299
Reid Klecknera8a0f762013-03-22 19:02:54 +0000300 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
301
302 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
303 CharUnits offset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000304 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
305 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000306
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000307 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
308 llvm::Value *L,
309 llvm::Value *R,
310 const MemberPointerType *MPT,
311 bool Inequality);
312
Reid Klecknera8a0f762013-03-22 19:02:54 +0000313 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
314 llvm::Value *MemPtr,
315 const MemberPointerType *MPT);
316
317 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
318 llvm::Value *Base,
319 llvm::Value *MemPtr,
320 const MemberPointerType *MPT);
321
Reid Klecknerf6327302013-05-09 21:01:17 +0000322 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
323 const CastExpr *E,
324 llvm::Value *Src);
325
326 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
327 llvm::Constant *Src);
328
Reid Klecknera3609b02013-04-11 18:13:19 +0000329 virtual llvm::Value *
330 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
331 llvm::Value *&This,
332 llvm::Value *MemPtr,
333 const MemberPointerType *MPT);
334
Reid Kleckner90633022013-06-19 15:20:38 +0000335private:
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000336 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
337 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
338 /// \brief All the vftables that have been referenced.
339 VFTablesMapTy VFTablesMap;
340
341 /// \brief This set holds the record decls we've deferred vtable emission for.
342 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
343
344
345 /// \brief All the vbtables which have been referenced.
Reid Kleckner90633022013-06-19 15:20:38 +0000346 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000347
348 /// Info on the global variable used to guard initialization of static locals.
349 /// The BitIndex field is only used for externally invisible declarations.
350 struct GuardInfo {
351 GuardInfo() : Guard(0), BitIndex(0) {}
352 llvm::GlobalVariable *Guard;
353 unsigned BitIndex;
354 };
355
356 /// Map from DeclContext to the current guard variable. We assume that the
357 /// AST is visited in source code order.
358 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davisc3926642010-06-09 23:25:41 +0000359};
360
361}
362
John McCallecd03b42012-09-25 10:10:39 +0000363llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
364 llvm::Value *ptr,
365 QualType type) {
366 // FIXME: implement
367 return ptr;
368}
369
Reid Kleckner8c474322013-06-04 21:32:29 +0000370/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
371/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
372static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
373 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
374 E = RD->bases_end(); I != E; ++I) {
375 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
376 if (!I->isVirtual() && Base->getNumVBases() > 0)
377 return Base;
378 }
379 llvm_unreachable("RD must have an nv base with vbases");
380}
381
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000382CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
383 assert(RD->getNumVBases());
384 CharUnits Total = CharUnits::Zero();
385 while (RD) {
386 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
387 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
388 // -1 is the sentinel for no vbptr.
389 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
390 Total += VBPtrOffset;
391 break;
392 }
Reid Kleckner8c474322013-06-04 21:32:29 +0000393 RD = FindFirstNVBaseWithVBases(RD);
394 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000395 }
396 return Total;
397}
398
399llvm::Value *
400MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
401 llvm::Value *This,
402 const CXXRecordDecl *ClassDecl,
403 const CXXRecordDecl *BaseClassDecl) {
404 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
405 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000406 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner8c474322013-06-04 21:32:29 +0000407 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000408 llvm::Value *VBTableOffset =
409 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
410
411 llvm::Value *VBPtrToNewBase =
412 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
413 VBPtrToNewBase =
414 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
415 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
416}
417
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000418bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
419 return isa<CXXConstructorDecl>(GD.getDecl());
John McCallbd315742012-09-25 08:00:39 +0000420}
421
422void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
423 CXXCtorType Type,
424 CanQualType &ResTy,
425 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000426 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000427
428 const CXXRecordDecl *Class = Ctor->getParent();
429 if (Class->getNumVBases()) {
430 // Constructors of classes with virtual bases take an implicit parameter.
431 ArgTys.push_back(CGM.getContext().IntTy);
432 }
433}
434
Reid Kleckner90633022013-06-19 15:20:38 +0000435llvm::BasicBlock *
436MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
437 const CXXRecordDecl *RD) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000438 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
439 assert(IsMostDerivedClass &&
440 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner90633022013-06-19 15:20:38 +0000441 llvm::Value *IsCompleteObject =
442 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000443
444 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
445 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
446 CGF.Builder.CreateCondBr(IsCompleteObject,
447 CallVbaseCtorsBB, SkipVbaseCtorsBB);
448
449 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner90633022013-06-19 15:20:38 +0000450
451 // Fill in the vbtable pointers here.
452 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000453
454 // CGF will put the base ctor calls in this basic block for us later.
455
456 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000457}
458
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000459void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
460 // There's only one constructor type in this ABI.
461 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
462}
463
Reid Kleckner90633022013-06-19 15:20:38 +0000464void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
465 const CXXRecordDecl *RD) {
466 llvm::Value *ThisInt8Ptr =
467 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
468
469 const VBTableVector &VBTables = EnumerateVBTables(RD);
470 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
471 I != E; ++I) {
472 const ASTRecordLayout &SubobjectLayout =
473 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
474 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
475 SubobjectLayout.getVBPtrOffset()).getQuantity();
476 llvm::Value *VBPtr =
477 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
478 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
479 "vbptr." + I->ReusingBase->getName());
480 CGF.Builder.CreateStore(I->GV, VBPtr);
481 }
482}
483
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000484void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
485 CXXDtorType Type,
486 CanQualType &ResTy,
487 SmallVectorImpl<CanQualType> &ArgTys) {
488 // 'this' is already in place
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000489
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000490 // TODO: 'for base' flag
491
492 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000493 // The scalar deleting destructor takes an implicit int parameter.
494 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000495 }
496}
497
Reid Klecknera4130ba2013-07-22 13:51:44 +0000498void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
499 // The TU defining a dtor is only guaranteed to emit a base destructor. All
500 // other destructor variants are delegating thunks.
501 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
502}
503
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000504llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
505 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
506 GD = GD.getCanonicalDecl();
507 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
508 if (isa<CXXDestructorDecl>(MD))
509 return This;
510
511 MicrosoftVFTableContext::MethodVFTableLocation ML =
512 CGM.getVFTableContext().getMethodVFTableLocation(GD);
513
514 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
515 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
516 if (ML.VBase) {
517 This = CGF.Builder.CreateBitCast(This, charPtrTy);
518 llvm::Value *VBaseOffset = CGM.getCXXABI()
519 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
520 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
521 }
522 CharUnits StaticOffset = ML.VFTableOffset;
523 if (!StaticOffset.isZero()) {
524 assert(StaticOffset.isPositive());
525 This = CGF.Builder.CreateBitCast(This, charPtrTy);
526 This = CGF.Builder
527 .CreateConstInBoundsGEP1_64(This, StaticOffset.getQuantity());
528 }
529 return This;
530}
531
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000532static bool IsDeletingDtor(GlobalDecl GD) {
533 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
534 if (isa<CXXDestructorDecl>(MD)) {
535 return GD.getDtorType() == Dtor_Deleting;
536 }
537 return false;
538}
539
John McCallbd315742012-09-25 08:00:39 +0000540void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
541 QualType &ResTy,
542 FunctionArgList &Params) {
543 BuildThisParam(CGF, Params);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000544
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000545 ASTContext &Context = getContext();
546 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
547 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
548 ImplicitParamDecl *IsMostDerived
549 = ImplicitParamDecl::Create(Context, 0,
550 CGF.CurGD.getDecl()->getLocation(),
551 &Context.Idents.get("is_most_derived"),
552 Context.IntTy);
553 Params.push_back(IsMostDerived);
554 getStructorImplicitParamDecl(CGF) = IsMostDerived;
555 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000556 ImplicitParamDecl *ShouldDelete
557 = ImplicitParamDecl::Create(Context, 0,
558 CGF.CurGD.getDecl()->getLocation(),
559 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000560 Context.IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000561 Params.push_back(ShouldDelete);
562 getStructorImplicitParamDecl(CGF) = ShouldDelete;
563 }
John McCallbd315742012-09-25 08:00:39 +0000564}
565
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000566llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
567 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
568 GD = GD.getCanonicalDecl();
569 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
570 if (isa<CXXDestructorDecl>(MD))
571 return This;
572
573 // In this ABI, every virtual function takes a pointer to one of the
574 // subobjects that first defines it as the 'this' parameter, rather than a
575 // pointer to ther final overrider subobject. Thus, we need to adjust it back
576 // to the final overrider subobject before use.
577 // See comments in the MicrosoftVFTableContext implementation for the details.
578
579 MicrosoftVFTableContext::MethodVFTableLocation ML =
580 CGM.getVFTableContext().getMethodVFTableLocation(GD);
581 CharUnits Adjustment = ML.VFTableOffset;
582 if (ML.VBase) {
583 const ASTRecordLayout &DerivedLayout =
584 CGF.getContext().getASTRecordLayout(MD->getParent());
585 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
586 }
587
588 if (Adjustment.isZero())
589 return This;
590
591 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
592 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
593 *thisTy = This->getType();
594
595 This = CGF.Builder.CreateBitCast(This, charPtrTy);
596 assert(Adjustment.isPositive());
597 This = CGF.Builder.CreateConstGEP1_64(This, -Adjustment.getQuantity());
598 return CGF.Builder.CreateBitCast(This, thisTy);
599}
600
John McCallbd315742012-09-25 08:00:39 +0000601void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
602 EmitThisParam(CGF);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000603
604 /// If this is a function that the ABI specifies returns 'this', initialize
605 /// the return slot to 'this' at the start of the function.
606 ///
607 /// Unlike the setting of return types, this is done within the ABI
608 /// implementation instead of by clients of CGCXXABI because:
609 /// 1) getThisValue is currently protected
610 /// 2) in theory, an ABI could implement 'this' returns some other way;
611 /// HasThisReturn only specifies a contract, not the implementation
612 if (HasThisReturn(CGF.CurGD))
John McCallbd315742012-09-25 08:00:39 +0000613 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000614
615 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
616 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
617 assert(getStructorImplicitParamDecl(CGF) &&
618 "no implicit parameter for a constructor with virtual bases?");
619 getStructorImplicitParamValue(CGF)
620 = CGF.Builder.CreateLoad(
621 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
622 "is_most_derived");
623 }
624
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000625 if (IsDeletingDtor(CGF.CurGD)) {
626 assert(getStructorImplicitParamDecl(CGF) &&
627 "no implicit parameter for a deleting destructor?");
628 getStructorImplicitParamValue(CGF)
629 = CGF.Builder.CreateLoad(
630 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
631 "should_call_delete");
632 }
John McCallbd315742012-09-25 08:00:39 +0000633}
634
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000635void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000636 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000637 CXXCtorType Type,
638 bool ForVirtualBase,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000639 bool Delegating,
640 llvm::Value *This,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000641 CallExpr::const_arg_iterator ArgBeg,
642 CallExpr::const_arg_iterator ArgEnd) {
643 assert(Type == Ctor_Complete || Type == Ctor_Base);
644 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
645
646 llvm::Value *ImplicitParam = 0;
647 QualType ImplicitParamTy;
648 if (D->getParent()->getNumVBases()) {
649 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
650 ImplicitParamTy = getContext().IntTy;
651 }
652
653 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000654 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000655 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000656}
657
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000658void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
659 const CXXRecordDecl *RD) {
660 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
661 MicrosoftVFTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
662 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
663
664 for (MicrosoftVFTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
665 E = VFPtrs.end(); I != E; ++I) {
666 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
667 if (VTable->hasInitializer())
668 continue;
669
670 const VTableLayout &VTLayout =
671 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
672 llvm::Constant *Init = CGVT.CreateVTableInitializer(
673 RD, VTLayout.vtable_component_begin(),
674 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
675 VTLayout.getNumVTableThunks());
676 VTable->setInitializer(Init);
677
678 VTable->setLinkage(Linkage);
679 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
680 }
681}
682
683llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
684 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
685 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
686 NeedsVirtualOffset = (NearestVBase != 0);
687
688 llvm::Value *VTableAddressPoint =
689 getAddrOfVTable(VTableClass, Base.getBaseOffset());
690 if (!VTableAddressPoint) {
691 assert(Base.getBase()->getNumVBases() &&
692 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
693 }
694 return VTableAddressPoint;
695}
696
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000697static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
698 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
699 SmallString<256> &Name) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000700 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000701 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000702}
703
704llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
705 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
706 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
707 assert(VTable && "Couldn't find a vftable for the given base?");
708 return VTable;
709}
710
711llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
712 CharUnits VPtrOffset) {
713 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
714 // shouldn't be used in the given record type. We want to cache this result in
715 // VFTablesMap, thus a simple zero check is not sufficient.
716 VFTableIdTy ID(RD, VPtrOffset);
717 VFTablesMapTy::iterator I;
718 bool Inserted;
719 llvm::tie(I, Inserted) = VFTablesMap.insert(
720 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
721 if (!Inserted)
722 return I->second;
723
724 llvm::GlobalVariable *&VTable = I->second;
725
726 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
727 const MicrosoftVFTableContext::VFPtrListTy &VFPtrs =
728 VFTContext.getVFPtrOffsets(RD);
729
730 if (DeferredVFTables.insert(RD)) {
731 // We haven't processed this record type before.
732 // Queue up this v-table for possible deferred emission.
733 CGM.addDeferredVTable(RD);
734
735#ifndef NDEBUG
736 // Create all the vftables at once in order to make sure each vftable has
737 // a unique mangled name.
738 llvm::StringSet<> ObservedMangledNames;
739 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
740 SmallString<256> Name;
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000741 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000742 if (!ObservedMangledNames.insert(Name.str()))
743 llvm_unreachable("Already saw this mangling before?");
744 }
745#endif
746 }
747
748 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
749 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
750 continue;
751
752 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
753 CGM.Int8PtrTy,
754 VFTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
755 .getNumVTableComponents());
756
757 SmallString<256> Name;
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000758 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000759 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
760 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
761 VTable->setUnnamedAddr(true);
762 break;
763 }
764
765 return VTable;
766}
767
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000768llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
769 GlobalDecl GD,
770 llvm::Value *This,
771 llvm::Type *Ty) {
772 GD = GD.getCanonicalDecl();
773 CGBuilderTy &Builder = CGF.Builder;
774
775 Ty = Ty->getPointerTo()->getPointerTo();
776 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
777 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
778
779 MicrosoftVFTableContext::MethodVFTableLocation ML =
780 CGM.getVFTableContext().getMethodVFTableLocation(GD);
781 llvm::Value *VFuncPtr =
782 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
783 return Builder.CreateLoad(VFuncPtr);
784}
785
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000786void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
787 const CXXDestructorDecl *Dtor,
788 CXXDtorType DtorType,
789 SourceLocation CallLoc,
790 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000791 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
792
793 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000794 // by passing an implicit int parameter.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000795 const CGFunctionInfo *FInfo =
796 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000797 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000798 llvm::Value *Callee =
799 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, Dtor_Deleting), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000800
801 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000802 llvm::Value *ImplicitParam =
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000803 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000804 DtorType == Dtor_Deleting);
805
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000806 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000807 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000808}
809
Reid Kleckner90633022013-06-19 15:20:38 +0000810const VBTableVector &
811MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
812 // At this layer, we can key the cache off of a single class, which is much
813 // easier than caching at the GlobalVariable layer.
814 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
815 bool added;
816 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
817 VBTableVector &VBTables = I->second;
818 if (!added)
819 return VBTables;
820
821 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
822
823 return VBTables;
824}
825
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000826void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner90633022013-06-19 15:20:38 +0000827 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000828 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
829
Reid Kleckner90633022013-06-19 15:20:38 +0000830 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
831 I != E; ++I) {
832 I->EmitVBTableDefinition(CGM, RD, Linkage);
833 }
834}
835
John McCalle2b45e22012-05-01 05:23:51 +0000836bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
837 QualType elementType) {
838 // Microsoft seems to completely ignore the possibility of a
839 // two-argument usual deallocation function.
840 return elementType.isDestructedType();
841}
842
843bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
844 // Microsoft seems to completely ignore the possibility of a
845 // two-argument usual deallocation function.
846 return expr->getAllocatedType().isDestructedType();
847}
848
849CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
850 // The array cookie is always a size_t; we then pad that out to the
851 // alignment of the element type.
852 ASTContext &Ctx = getContext();
853 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
854 Ctx.getTypeAlignInChars(type));
855}
856
857llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
858 llvm::Value *allocPtr,
859 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +0000860 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000861 llvm::Value *numElementsPtr =
862 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
863 return CGF.Builder.CreateLoad(numElementsPtr);
864}
865
866llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
867 llvm::Value *newPtr,
868 llvm::Value *numElements,
869 const CXXNewExpr *expr,
870 QualType elementType) {
871 assert(requiresArrayCookie(expr));
872
873 // The size of the cookie.
874 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
875
876 // Compute an offset to the cookie.
877 llvm::Value *cookiePtr = newPtr;
878
879 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +0000880 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000881 llvm::Value *numElementsPtr
882 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
883 CGF.Builder.CreateStore(numElements, numElementsPtr);
884
885 // Finally, compute a pointer to the actual data buffer by skipping
886 // over the cookie completely.
887 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
888 cookieSize.getQuantity());
889}
890
John McCall20bb1752012-05-01 06:13:13 +0000891void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000892 llvm::GlobalVariable *GV,
John McCall20bb1752012-05-01 06:13:13 +0000893 bool PerformInit) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000894 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
895 // threadsafe. Since the user may be linking in inline functions compiled by
896 // cl.exe, there's no reason to provide a false sense of security by using
897 // critical sections here.
John McCall20bb1752012-05-01 06:13:13 +0000898
Richard Smith04e51762013-04-14 23:01:42 +0000899 if (D.getTLSKind())
900 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
901
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000902 CGBuilderTy &Builder = CGF.Builder;
903 llvm::IntegerType *GuardTy = CGF.Int32Ty;
904 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
905
906 // Get the guard variable for this function if we have one already.
907 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
908
909 unsigned BitIndex;
910 if (D.isExternallyVisible()) {
911 // Externally visible variables have to be numbered in Sema to properly
912 // handle unreachable VarDecls.
913 BitIndex = getContext().getManglingNumber(&D);
914 assert(BitIndex > 0);
915 BitIndex--;
916 } else {
917 // Non-externally visible variables are numbered here in CodeGen.
918 BitIndex = GI.BitIndex++;
919 }
920
921 if (BitIndex >= 32) {
922 if (D.isExternallyVisible())
923 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
924 BitIndex %= 32;
925 GI.Guard = 0;
926 }
927
928 // Lazily create the i32 bitfield for this function.
929 if (!GI.Guard) {
930 // Mangle the name for the guard.
931 SmallString<256> GuardName;
932 {
933 llvm::raw_svector_ostream Out(GuardName);
934 getMangleContext().mangleStaticGuardVariable(&D, Out);
935 Out.flush();
936 }
937
938 // Create the guard variable with a zero-initializer. Just absorb linkage
939 // and visibility from the guarded variable.
940 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
941 GV->getLinkage(), Zero, GuardName.str());
942 GI.Guard->setVisibility(GV->getVisibility());
943 } else {
944 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
945 "static local from the same function had different linkage");
946 }
947
948 // Pseudo code for the test:
949 // if (!(GuardVar & MyGuardBit)) {
950 // GuardVar |= MyGuardBit;
951 // ... initialize the object ...;
952 // }
953
954 // Test our bit from the guard variable.
955 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
956 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
957 llvm::Value *IsInitialized =
958 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
959 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
960 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
961 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
962
963 // Set our bit in the guard variable and emit the initializer and add a global
964 // destructor if appropriate.
965 CGF.EmitBlock(InitBlock);
966 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
967 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
968 Builder.CreateBr(EndBlock);
969
970 // Continue.
971 CGF.EmitBlock(EndBlock);
John McCall20bb1752012-05-01 06:13:13 +0000972}
973
Reid Klecknera3609b02013-04-11 18:13:19 +0000974// Member pointer helpers.
975static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
976 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000977}
978
Reid Klecknerf6327302013-05-09 21:01:17 +0000979static bool hasOnlyOneField(bool IsMemberFunction,
980 MSInheritanceModel Inheritance) {
981 return Inheritance <= MSIM_SinglePolymorphic ||
982 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000983}
984
Reid Klecknera3609b02013-04-11 18:13:19 +0000985// Only member pointers to functions need a this adjustment, since it can be
986// combined with the field offset for data pointers.
Reid Kleckner79e02912013-05-03 01:15:11 +0000987static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Klecknera3609b02013-04-11 18:13:19 +0000988 MSInheritanceModel Inheritance) {
Reid Kleckner79e02912013-05-03 01:15:11 +0000989 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Klecknera3609b02013-04-11 18:13:19 +0000990}
991
992static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
993 return Inheritance >= MSIM_Virtual;
994}
995
996// Use zero for the field offset of a null data member pointer if we can
997// guarantee that zero is not a valid field offset, or if the member pointer has
998// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
999// use zero for null. If there are multiple fields, we can use zero even if it
1000// is a valid field offset because null-ness testing will check the other
1001// fields.
1002static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1003 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1004}
1005
1006bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1007 // Null-ness for function memptrs only depends on the first field, which is
1008 // the function pointer. The rest don't matter, so we can zero initialize.
1009 if (MPT->isMemberFunctionPointer())
1010 return true;
1011
1012 // The virtual base adjustment field is always -1 for null, so if we have one
1013 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1014 // valid field offset.
1015 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1016 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1017 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1018 nullFieldOffsetIsZero(Inheritance));
1019}
1020
1021llvm::Type *
1022MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1023 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1024 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1025 llvm::SmallVector<llvm::Type *, 4> fields;
1026 if (MPT->isMemberFunctionPointer())
1027 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1028 else
1029 fields.push_back(CGM.IntTy); // FieldOffset
1030
Reid Kleckner79e02912013-05-03 01:15:11 +00001031 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1032 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001033 fields.push_back(CGM.IntTy);
Reid Kleckner79e02912013-05-03 01:15:11 +00001034 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001035 fields.push_back(CGM.IntTy);
1036 if (hasVirtualBaseAdjustmentField(Inheritance))
1037 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1038
1039 if (fields.size() == 1)
1040 return fields[0];
1041 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1042}
1043
1044void MicrosoftCXXABI::
1045GetNullMemberPointerFields(const MemberPointerType *MPT,
1046 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1047 assert(fields.empty());
1048 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1049 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1050 if (MPT->isMemberFunctionPointer()) {
1051 // FunctionPointerOrVirtualThunk
1052 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1053 } else {
1054 if (nullFieldOffsetIsZero(Inheritance))
1055 fields.push_back(getZeroInt()); // FieldOffset
1056 else
1057 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +00001058 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001059
Reid Kleckner79e02912013-05-03 01:15:11 +00001060 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1061 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001062 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001063 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001064 fields.push_back(getZeroInt());
1065 if (hasVirtualBaseAdjustmentField(Inheritance))
1066 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001067}
1068
1069llvm::Constant *
1070MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001071 llvm::SmallVector<llvm::Constant *, 4> fields;
1072 GetNullMemberPointerFields(MPT, fields);
1073 if (fields.size() == 1)
1074 return fields[0];
1075 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1076 assert(Res->getType() == ConvertMemberPointerType(MPT));
1077 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001078}
1079
1080llvm::Constant *
Reid Kleckner79e02912013-05-03 01:15:11 +00001081MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1082 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +00001083 const CXXRecordDecl *RD,
1084 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner79e02912013-05-03 01:15:11 +00001085{
Reid Klecknera3609b02013-04-11 18:13:19 +00001086 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner79e02912013-05-03 01:15:11 +00001087
1088 // Single inheritance class member pointer are represented as scalars instead
1089 // of aggregates.
Reid Klecknerf6327302013-05-09 21:01:17 +00001090 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner79e02912013-05-03 01:15:11 +00001091 return FirstField;
1092
Reid Klecknera3609b02013-04-11 18:13:19 +00001093 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner79e02912013-05-03 01:15:11 +00001094 fields.push_back(FirstField);
1095
1096 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Klecknerf6327302013-05-09 21:01:17 +00001097 fields.push_back(llvm::ConstantInt::get(
1098 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner79e02912013-05-03 01:15:11 +00001099
Reid Klecknera3609b02013-04-11 18:13:19 +00001100 if (hasVBPtrOffsetField(Inheritance)) {
Reid Klecknera06d5852013-06-05 15:58:29 +00001101 fields.push_back(llvm::ConstantInt::get(
1102 CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity()));
Reid Klecknera3609b02013-04-11 18:13:19 +00001103 }
Reid Kleckner79e02912013-05-03 01:15:11 +00001104
1105 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Klecknera3609b02013-04-11 18:13:19 +00001106 if (hasVirtualBaseAdjustmentField(Inheritance))
1107 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001108
Reid Klecknera3609b02013-04-11 18:13:19 +00001109 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001110}
1111
Reid Kleckner79e02912013-05-03 01:15:11 +00001112llvm::Constant *
1113MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1114 CharUnits offset) {
1115 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1116 llvm::Constant *FirstField =
1117 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Klecknerf6327302013-05-09 21:01:17 +00001118 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1119 CharUnits::Zero());
1120}
1121
1122llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1123 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1124}
1125
1126llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1127 QualType MPType) {
1128 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1129 const ValueDecl *MPD = MP.getMemberPointerDecl();
1130 if (!MPD)
1131 return EmitNullMemberPointer(MPT);
1132
1133 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1134
1135 // FIXME PR15713: Support virtual inheritance paths.
1136
1137 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1138 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1139 MD, ThisAdjustment);
1140
1141 CharUnits FieldOffset =
1142 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1143 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner79e02912013-05-03 01:15:11 +00001144}
1145
1146llvm::Constant *
Reid Klecknerf6327302013-05-09 21:01:17 +00001147MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1148 const CXXMethodDecl *MD,
1149 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner79e02912013-05-03 01:15:11 +00001150 assert(MD->isInstance() && "Member function must not be static!");
1151 MD = MD->getCanonicalDecl();
Reid Kleckner79e02912013-05-03 01:15:11 +00001152 CodeGenTypes &Types = CGM.getTypes();
1153
1154 llvm::Constant *FirstField;
1155 if (MD->isVirtual()) {
1156 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1157 // the right offset.
1158 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1159 } else {
1160 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1161 llvm::Type *Ty;
1162 // Check whether the function has a computable LLVM signature.
1163 if (Types.isFuncTypeConvertible(FPT)) {
1164 // The function has a computable LLVM signature; use the correct type.
1165 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1166 } else {
1167 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1168 // function type is incomplete.
1169 Ty = CGM.PtrDiffTy;
1170 }
1171 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1172 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1173 }
1174
1175 // The rest of the fields are common with data member pointers.
Reid Klecknerf6327302013-05-09 21:01:17 +00001176 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1177 NonVirtualBaseAdjustment);
Reid Kleckner79e02912013-05-03 01:15:11 +00001178}
1179
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001180/// Member pointers are the same if they're either bitwise identical *or* both
1181/// null. Null-ness for function members is determined by the first field,
1182/// while for data member pointers we must compare all fields.
1183llvm::Value *
1184MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1185 llvm::Value *L,
1186 llvm::Value *R,
1187 const MemberPointerType *MPT,
1188 bool Inequality) {
1189 CGBuilderTy &Builder = CGF.Builder;
1190
1191 // Handle != comparisons by switching the sense of all boolean operations.
1192 llvm::ICmpInst::Predicate Eq;
1193 llvm::Instruction::BinaryOps And, Or;
1194 if (Inequality) {
1195 Eq = llvm::ICmpInst::ICMP_NE;
1196 And = llvm::Instruction::Or;
1197 Or = llvm::Instruction::And;
1198 } else {
1199 Eq = llvm::ICmpInst::ICMP_EQ;
1200 And = llvm::Instruction::And;
1201 Or = llvm::Instruction::Or;
1202 }
1203
1204 // If this is a single field member pointer (single inheritance), this is a
1205 // single icmp.
1206 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1207 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknerf6327302013-05-09 21:01:17 +00001208 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001209 return Builder.CreateICmp(Eq, L, R);
1210
1211 // Compare the first field.
1212 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1213 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1214 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1215
1216 // Compare everything other than the first field.
1217 llvm::Value *Res = 0;
1218 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1219 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1220 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1221 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1222 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1223 if (Res)
1224 Res = Builder.CreateBinOp(And, Res, Cmp);
1225 else
1226 Res = Cmp;
1227 }
1228
1229 // Check if the first field is 0 if this is a function pointer.
1230 if (MPT->isMemberFunctionPointer()) {
1231 // (l1 == r1 && ...) || l0 == 0
1232 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1233 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1234 Res = Builder.CreateBinOp(Or, Res, IsZero);
1235 }
1236
1237 // Combine the comparison of the first field, which must always be true for
1238 // this comparison to succeeed.
1239 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1240}
1241
Reid Klecknera8a0f762013-03-22 19:02:54 +00001242llvm::Value *
1243MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1244 llvm::Value *MemPtr,
1245 const MemberPointerType *MPT) {
1246 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001247 llvm::SmallVector<llvm::Constant *, 4> fields;
1248 // We only need one field for member functions.
1249 if (MPT->isMemberFunctionPointer())
1250 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1251 else
1252 GetNullMemberPointerFields(MPT, fields);
1253 assert(!fields.empty());
1254 llvm::Value *FirstField = MemPtr;
1255 if (MemPtr->getType()->isStructTy())
1256 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1257 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001258
Reid Klecknera3609b02013-04-11 18:13:19 +00001259 // For function member pointers, we only need to test the function pointer
1260 // field. The other fields if any can be garbage.
1261 if (MPT->isMemberFunctionPointer())
1262 return Res;
1263
1264 // Otherwise, emit a series of compares and combine the results.
1265 for (int I = 1, E = fields.size(); I < E; ++I) {
1266 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1267 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1268 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1269 }
1270 return Res;
1271}
1272
Reid Klecknerf6327302013-05-09 21:01:17 +00001273bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1274 llvm::Constant *Val) {
1275 // Function pointers are null if the pointer in the first field is null.
1276 if (MPT->isMemberFunctionPointer()) {
1277 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1278 Val->getAggregateElement(0U) : Val;
1279 return FirstField->isNullValue();
1280 }
1281
1282 // If it's not a function pointer and it's zero initializable, we can easily
1283 // check zero.
1284 if (isZeroInitializable(MPT) && Val->isNullValue())
1285 return true;
1286
1287 // Otherwise, break down all the fields for comparison. Hopefully these
1288 // little Constants are reused, while a big null struct might not be.
1289 llvm::SmallVector<llvm::Constant *, 4> Fields;
1290 GetNullMemberPointerFields(MPT, Fields);
1291 if (Fields.size() == 1) {
1292 assert(Val->getType()->isIntegerTy());
1293 return Val == Fields[0];
1294 }
1295
1296 unsigned I, E;
1297 for (I = 0, E = Fields.size(); I != E; ++I) {
1298 if (Val->getAggregateElement(I) != Fields[I])
1299 break;
1300 }
1301 return I == E;
1302}
1303
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001304llvm::Value *
1305MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1306 llvm::Value *This,
1307 llvm::Value *VBTableOffset,
1308 llvm::Value *VBPtrOffset,
1309 llvm::Value **VBPtrOut) {
1310 CGBuilderTy &Builder = CGF.Builder;
1311 // Load the vbtable pointer from the vbptr in the instance.
1312 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1313 llvm::Value *VBPtr =
1314 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1315 if (VBPtrOut) *VBPtrOut = VBPtr;
1316 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1317 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1318
1319 // Load an i32 offset from the vb-table.
1320 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1321 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1322 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1323}
1324
Reid Klecknera3609b02013-04-11 18:13:19 +00001325// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1326// it.
1327llvm::Value *
1328MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1329 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001330 llvm::Value *VBTableOffset,
Reid Klecknera3609b02013-04-11 18:13:19 +00001331 llvm::Value *VBPtrOffset) {
1332 CGBuilderTy &Builder = CGF.Builder;
1333 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1334 llvm::BasicBlock *OriginalBB = 0;
1335 llvm::BasicBlock *SkipAdjustBB = 0;
1336 llvm::BasicBlock *VBaseAdjustBB = 0;
1337
1338 // In the unspecified inheritance model, there might not be a vbtable at all,
1339 // in which case we need to skip the virtual base lookup. If there is a
1340 // vbtable, the first entry is a no-op entry that gives back the original
1341 // base, so look for a virtual base adjustment offset of zero.
1342 if (VBPtrOffset) {
1343 OriginalBB = Builder.GetInsertBlock();
1344 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1345 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1346 llvm::Value *IsVirtual =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001347 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Klecknera3609b02013-04-11 18:13:19 +00001348 "memptr.is_vbase");
1349 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1350 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001351 }
1352
Reid Klecknera3609b02013-04-11 18:13:19 +00001353 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1354 // know the vbptr offset.
1355 if (!VBPtrOffset) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001356 CharUnits offs = CharUnits::Zero();
1357 if (RD->getNumVBases()) {
1358 offs = GetVBPtrOffsetFromBases(RD);
1359 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001360 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1361 }
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001362 llvm::Value *VBPtr = 0;
Reid Klecknera3609b02013-04-11 18:13:19 +00001363 llvm::Value *VBaseOffs =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001364 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Klecknera3609b02013-04-11 18:13:19 +00001365 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1366
1367 // Merge control flow with the case where we didn't have to adjust.
1368 if (VBaseAdjustBB) {
1369 Builder.CreateBr(SkipAdjustBB);
1370 CGF.EmitBlock(SkipAdjustBB);
1371 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1372 Phi->addIncoming(Base, OriginalBB);
1373 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1374 return Phi;
1375 }
1376 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001377}
1378
1379llvm::Value *
1380MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1381 llvm::Value *Base,
1382 llvm::Value *MemPtr,
1383 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001384 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001385 unsigned AS = Base->getType()->getPointerAddressSpace();
1386 llvm::Type *PType =
1387 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1388 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001389 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1390 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +00001391
Reid Klecknera3609b02013-04-11 18:13:19 +00001392 // Extract the fields we need, regardless of model. We'll apply them if we
1393 // have them.
1394 llvm::Value *FieldOffset = MemPtr;
1395 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1396 llvm::Value *VBPtrOffset = 0;
1397 if (MemPtr->getType()->isStructTy()) {
1398 // We need to extract values.
1399 unsigned I = 0;
1400 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1401 if (hasVBPtrOffsetField(Inheritance))
1402 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1403 if (hasVirtualBaseAdjustmentField(Inheritance))
1404 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001405 }
1406
Reid Klecknera3609b02013-04-11 18:13:19 +00001407 if (VirtualBaseAdjustmentOffset) {
1408 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1409 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001410 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001411 llvm::Value *Addr =
1412 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001413
1414 // Cast the address to the appropriate pointer type, adopting the address
1415 // space of the base pointer.
1416 return Builder.CreateBitCast(Addr, PType);
1417}
1418
Reid Klecknerf6327302013-05-09 21:01:17 +00001419static MSInheritanceModel
1420getInheritanceFromMemptr(const MemberPointerType *MPT) {
1421 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1422}
1423
1424llvm::Value *
1425MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1426 const CastExpr *E,
1427 llvm::Value *Src) {
1428 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1429 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1430 E->getCastKind() == CK_ReinterpretMemberPointer);
1431
1432 // Use constant emission if we can.
1433 if (isa<llvm::Constant>(Src))
1434 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1435
1436 // We may be adding or dropping fields from the member pointer, so we need
1437 // both types and the inheritance models of both records.
1438 const MemberPointerType *SrcTy =
1439 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1440 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1441 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1442 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1443 bool IsFunc = SrcTy->isMemberFunctionPointer();
1444
1445 // If the classes use the same null representation, reinterpret_cast is a nop.
1446 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1447 if (IsReinterpret && (IsFunc ||
1448 nullFieldOffsetIsZero(SrcInheritance) ==
1449 nullFieldOffsetIsZero(DstInheritance)))
1450 return Src;
1451
1452 CGBuilderTy &Builder = CGF.Builder;
1453
1454 // Branch past the conversion if Src is null.
1455 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1456 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1457
1458 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1459 // pointer value of the destination type.
1460 if (IsReinterpret) {
1461 // For reinterpret casts, sema ensures that src and dst are both functions
1462 // or data and have the same size, which means the LLVM types should match.
1463 assert(Src->getType() == DstNull->getType());
1464 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1465 }
1466
1467 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1468 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1469 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1470 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1471 CGF.EmitBlock(ConvertBB);
1472
1473 // Decompose src.
1474 llvm::Value *FirstField = Src;
1475 llvm::Value *NonVirtualBaseAdjustment = 0;
1476 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1477 llvm::Value *VBPtrOffset = 0;
1478 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1479 // We need to extract values.
1480 unsigned I = 0;
1481 FirstField = Builder.CreateExtractValue(Src, I++);
1482 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1483 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1484 if (hasVBPtrOffsetField(SrcInheritance))
1485 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1486 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1487 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1488 }
1489
1490 // For data pointers, we adjust the field offset directly. For functions, we
1491 // have a separate field.
1492 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1493 if (Adj) {
1494 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1495 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1496 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1497 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1498 NVAdjustField = getZeroInt();
1499 if (isDerivedToBase)
1500 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1501 else
1502 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1503 }
1504
1505 // FIXME PR15713: Support conversions through virtually derived classes.
1506
1507 // Recompose dst from the null struct and the adjusted fields from src.
1508 llvm::Value *Dst;
1509 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1510 Dst = FirstField;
1511 } else {
1512 Dst = llvm::UndefValue::get(DstNull->getType());
1513 unsigned Idx = 0;
1514 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1515 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1516 Dst = Builder.CreateInsertValue(
1517 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1518 if (hasVBPtrOffsetField(DstInheritance))
1519 Dst = Builder.CreateInsertValue(
1520 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1521 if (hasVirtualBaseAdjustmentField(DstInheritance))
1522 Dst = Builder.CreateInsertValue(
1523 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1524 }
1525 Builder.CreateBr(ContinueBB);
1526
1527 // In the continuation, choose between DstNull and Dst.
1528 CGF.EmitBlock(ContinueBB);
1529 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1530 Phi->addIncoming(DstNull, OriginalBB);
1531 Phi->addIncoming(Dst, ConvertBB);
1532 return Phi;
1533}
1534
1535llvm::Constant *
1536MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1537 llvm::Constant *Src) {
1538 const MemberPointerType *SrcTy =
1539 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1540 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1541
1542 // If src is null, emit a new null for dst. We can't return src because dst
1543 // might have a new representation.
1544 if (MemberPointerConstantIsNull(SrcTy, Src))
1545 return EmitNullMemberPointer(DstTy);
1546
1547 // We don't need to do anything for reinterpret_casts of non-null member
1548 // pointers. We should only get here when the two type representations have
1549 // the same size.
1550 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1551 return Src;
1552
1553 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1554 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1555
1556 // Decompose src.
1557 llvm::Constant *FirstField = Src;
1558 llvm::Constant *NonVirtualBaseAdjustment = 0;
1559 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1560 llvm::Constant *VBPtrOffset = 0;
1561 bool IsFunc = SrcTy->isMemberFunctionPointer();
1562 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1563 // We need to extract values.
1564 unsigned I = 0;
1565 FirstField = Src->getAggregateElement(I++);
1566 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1567 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1568 if (hasVBPtrOffsetField(SrcInheritance))
1569 VBPtrOffset = Src->getAggregateElement(I++);
1570 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1571 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1572 }
1573
1574 // For data pointers, we adjust the field offset directly. For functions, we
1575 // have a separate field.
1576 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1577 if (Adj) {
1578 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1579 llvm::Constant *&NVAdjustField =
1580 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1581 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1582 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1583 NVAdjustField = getZeroInt();
1584 if (IsDerivedToBase)
1585 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1586 else
1587 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1588 }
1589
1590 // FIXME PR15713: Support conversions through virtually derived classes.
1591
1592 // Recompose dst from the null struct and the adjusted fields from src.
1593 if (hasOnlyOneField(IsFunc, DstInheritance))
1594 return FirstField;
1595
1596 llvm::SmallVector<llvm::Constant *, 4> Fields;
1597 Fields.push_back(FirstField);
1598 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1599 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1600 if (hasVBPtrOffsetField(DstInheritance))
1601 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1602 if (hasVirtualBaseAdjustmentField(DstInheritance))
1603 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1604 return llvm::ConstantStruct::getAnon(Fields);
1605}
1606
Reid Klecknera3609b02013-04-11 18:13:19 +00001607llvm::Value *
1608MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1609 llvm::Value *&This,
1610 llvm::Value *MemPtr,
1611 const MemberPointerType *MPT) {
1612 assert(MPT->isMemberFunctionPointer());
1613 const FunctionProtoType *FPT =
1614 MPT->getPointeeType()->castAs<FunctionProtoType>();
1615 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1616 llvm::FunctionType *FTy =
1617 CGM.getTypes().GetFunctionType(
1618 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1619 CGBuilderTy &Builder = CGF.Builder;
1620
1621 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1622
1623 // Extract the fields we need, regardless of model. We'll apply them if we
1624 // have them.
1625 llvm::Value *FunctionPointer = MemPtr;
1626 llvm::Value *NonVirtualBaseAdjustment = NULL;
1627 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1628 llvm::Value *VBPtrOffset = NULL;
1629 if (MemPtr->getType()->isStructTy()) {
1630 // We need to extract values.
1631 unsigned I = 0;
1632 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001633 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1634 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner79e02912013-05-03 01:15:11 +00001635 if (hasVBPtrOffsetField(Inheritance))
1636 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001637 if (hasVirtualBaseAdjustmentField(Inheritance))
1638 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1639 }
1640
1641 if (VirtualBaseAdjustmentOffset) {
1642 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1643 VBPtrOffset);
1644 }
1645
1646 if (NonVirtualBaseAdjustment) {
1647 // Apply the adjustment and cast back to the original struct type.
1648 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1649 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1650 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1651 }
1652
1653 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1654}
1655
Charles Davis071cc7d2010-08-16 03:33:14 +00001656CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +00001657 return new MicrosoftCXXABI(CGM);
1658}
1659