blob: 1d73b213b7d8130dd68c4d0952a9c27a0fd5edac [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 Iskhodzhanova53d7a02013-09-27 14:48:01 +0000176 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner90633022013-06-19 15:20:38 +0000177
John McCall20bb1752012-05-01 06:13:13 +0000178 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
179 llvm::GlobalVariable *DeclPtr,
180 bool PerformInit);
181
John McCallfd708262011-01-27 02:46:02 +0000182 // ==== Notes on array cookies =========
183 //
184 // MSVC seems to only use cookies when the class has a destructor; a
185 // two-argument usual array deallocation function isn't sufficient.
186 //
187 // For example, this code prints "100" and "1":
188 // struct A {
189 // char x;
190 // void *operator new[](size_t sz) {
191 // printf("%u\n", sz);
192 // return malloc(sz);
193 // }
194 // void operator delete[](void *p, size_t sz) {
195 // printf("%u\n", sz);
196 // free(p);
197 // }
198 // };
199 // int main() {
200 // A *p = new A[100];
201 // delete[] p;
202 // }
203 // Whereas it prints "104" and "104" if you give A a destructor.
John McCalle2b45e22012-05-01 05:23:51 +0000204
205 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
206 bool requiresArrayCookie(const CXXNewExpr *expr);
207 CharUnits getArrayCookieSizeImpl(QualType type);
208 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
209 llvm::Value *NewPtr,
210 llvm::Value *NumElements,
211 const CXXNewExpr *expr,
212 QualType ElementType);
213 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
214 llvm::Value *allocPtr,
215 CharUnits cookieSize);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000216
217private:
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000218 MicrosoftMangleContext &getMangleContext() {
219 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
220 }
221
Reid Klecknera3609b02013-04-11 18:13:19 +0000222 llvm::Constant *getZeroInt() {
223 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000224 }
225
Reid Klecknera3609b02013-04-11 18:13:19 +0000226 llvm::Constant *getAllOnesInt() {
227 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000228 }
229
Reid Klecknerf6327302013-05-09 21:01:17 +0000230 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
231 return C ? C : getZeroInt();
232 }
233
234 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
235 return C ? C : getZeroInt();
236 }
237
Reid Klecknera3609b02013-04-11 18:13:19 +0000238 void
239 GetNullMemberPointerFields(const MemberPointerType *MPT,
240 llvm::SmallVectorImpl<llvm::Constant *> &fields);
241
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000242 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
243 /// it is reusing a vbptr from a non-virtual base. RD must have morally
244 /// virtual bases.
245 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
246
247 /// \brief Shared code for virtual base adjustment. Returns the offset from
248 /// the vbptr to the virtual base. Optionally returns the address of the
249 /// vbptr itself.
250 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
251 llvm::Value *Base,
252 llvm::Value *VBPtrOffset,
253 llvm::Value *VBTableOffset,
254 llvm::Value **VBPtr = 0);
255
256 /// \brief Performs a full virtual base adjustment. Used to dereference
257 /// pointers to members of virtual bases.
Reid Klecknera3609b02013-04-11 18:13:19 +0000258 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
259 llvm::Value *Base,
260 llvm::Value *VirtualBaseAdjustmentOffset,
261 llvm::Value *VBPtrOffset /* optional */);
262
Reid Kleckner79e02912013-05-03 01:15:11 +0000263 /// \brief Emits a full member pointer with the fields common to data and
264 /// function member pointers.
265 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
266 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000267 const CXXRecordDecl *RD,
268 CharUnits NonVirtualBaseAdjustment);
269
270 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
271 const CXXMethodDecl *MD,
272 CharUnits NonVirtualBaseAdjustment);
273
274 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
275 llvm::Constant *MP);
Reid Kleckner79e02912013-05-03 01:15:11 +0000276
Reid Kleckner90633022013-06-19 15:20:38 +0000277 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
278 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
279
280 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
281 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
282
Reid Klecknera8a0f762013-03-22 19:02:54 +0000283public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000284 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
285
286 virtual bool isZeroInitializable(const MemberPointerType *MPT);
287
Reid Klecknera8a0f762013-03-22 19:02:54 +0000288 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
289
290 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
291 CharUnits offset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000292 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
293 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000294
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000295 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
296 llvm::Value *L,
297 llvm::Value *R,
298 const MemberPointerType *MPT,
299 bool Inequality);
300
Reid Klecknera8a0f762013-03-22 19:02:54 +0000301 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
302 llvm::Value *MemPtr,
303 const MemberPointerType *MPT);
304
305 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
306 llvm::Value *Base,
307 llvm::Value *MemPtr,
308 const MemberPointerType *MPT);
309
Reid Klecknerf6327302013-05-09 21:01:17 +0000310 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
311 const CastExpr *E,
312 llvm::Value *Src);
313
314 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
315 llvm::Constant *Src);
316
Reid Klecknera3609b02013-04-11 18:13:19 +0000317 virtual llvm::Value *
318 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
319 llvm::Value *&This,
320 llvm::Value *MemPtr,
321 const MemberPointerType *MPT);
322
Reid Kleckner90633022013-06-19 15:20:38 +0000323private:
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000324 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
325 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
326 /// \brief All the vftables that have been referenced.
327 VFTablesMapTy VFTablesMap;
328
329 /// \brief This set holds the record decls we've deferred vtable emission for.
330 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
331
332
333 /// \brief All the vbtables which have been referenced.
Reid Kleckner90633022013-06-19 15:20:38 +0000334 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000335
336 /// Info on the global variable used to guard initialization of static locals.
337 /// The BitIndex field is only used for externally invisible declarations.
338 struct GuardInfo {
339 GuardInfo() : Guard(0), BitIndex(0) {}
340 llvm::GlobalVariable *Guard;
341 unsigned BitIndex;
342 };
343
344 /// Map from DeclContext to the current guard variable. We assume that the
345 /// AST is visited in source code order.
346 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davisc3926642010-06-09 23:25:41 +0000347};
348
349}
350
John McCallecd03b42012-09-25 10:10:39 +0000351llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
352 llvm::Value *ptr,
353 QualType type) {
354 // FIXME: implement
355 return ptr;
356}
357
Reid Kleckner8c474322013-06-04 21:32:29 +0000358/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
359/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
360static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
361 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
362 E = RD->bases_end(); I != E; ++I) {
363 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
364 if (!I->isVirtual() && Base->getNumVBases() > 0)
365 return Base;
366 }
367 llvm_unreachable("RD must have an nv base with vbases");
368}
369
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000370CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
371 assert(RD->getNumVBases());
372 CharUnits Total = CharUnits::Zero();
373 while (RD) {
374 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
375 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
376 // -1 is the sentinel for no vbptr.
377 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
378 Total += VBPtrOffset;
379 break;
380 }
Reid Kleckner8c474322013-06-04 21:32:29 +0000381 RD = FindFirstNVBaseWithVBases(RD);
382 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000383 }
384 return Total;
385}
386
387llvm::Value *
388MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
389 llvm::Value *This,
390 const CXXRecordDecl *ClassDecl,
391 const CXXRecordDecl *BaseClassDecl) {
392 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
393 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000394 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner8c474322013-06-04 21:32:29 +0000395 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000396 llvm::Value *VBTableOffset =
397 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
398
399 llvm::Value *VBPtrToNewBase =
400 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
401 VBPtrToNewBase =
402 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
403 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
404}
405
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000406bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
407 return isa<CXXConstructorDecl>(GD.getDecl());
John McCallbd315742012-09-25 08:00:39 +0000408}
409
410void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
411 CXXCtorType Type,
412 CanQualType &ResTy,
413 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000414 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000415
416 const CXXRecordDecl *Class = Ctor->getParent();
417 if (Class->getNumVBases()) {
418 // Constructors of classes with virtual bases take an implicit parameter.
419 ArgTys.push_back(CGM.getContext().IntTy);
420 }
421}
422
Reid Kleckner90633022013-06-19 15:20:38 +0000423llvm::BasicBlock *
424MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
425 const CXXRecordDecl *RD) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000426 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
427 assert(IsMostDerivedClass &&
428 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner90633022013-06-19 15:20:38 +0000429 llvm::Value *IsCompleteObject =
430 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000431
432 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
433 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
434 CGF.Builder.CreateCondBr(IsCompleteObject,
435 CallVbaseCtorsBB, SkipVbaseCtorsBB);
436
437 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner90633022013-06-19 15:20:38 +0000438
439 // Fill in the vbtable pointers here.
440 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000441
442 // CGF will put the base ctor calls in this basic block for us later.
443
444 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000445}
446
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000447void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
448 // There's only one constructor type in this ABI.
449 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
450}
451
Reid Kleckner90633022013-06-19 15:20:38 +0000452void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
453 const CXXRecordDecl *RD) {
454 llvm::Value *ThisInt8Ptr =
455 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
456
457 const VBTableVector &VBTables = EnumerateVBTables(RD);
458 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
459 I != E; ++I) {
460 const ASTRecordLayout &SubobjectLayout =
461 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
462 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
463 SubobjectLayout.getVBPtrOffset()).getQuantity();
464 llvm::Value *VBPtr =
465 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
466 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
467 "vbptr." + I->ReusingBase->getName());
468 CGF.Builder.CreateStore(I->GV, VBPtr);
469 }
470}
471
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000472void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
473 CXXDtorType Type,
474 CanQualType &ResTy,
475 SmallVectorImpl<CanQualType> &ArgTys) {
476 // 'this' is already in place
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000477
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000478 // TODO: 'for base' flag
479
480 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000481 // The scalar deleting destructor takes an implicit int parameter.
482 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000483 }
484}
485
Reid Klecknera4130ba2013-07-22 13:51:44 +0000486void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
487 // The TU defining a dtor is only guaranteed to emit a base destructor. All
488 // other destructor variants are delegating thunks.
489 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
490}
491
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000492llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
493 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
494 GD = GD.getCanonicalDecl();
495 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
496 if (isa<CXXDestructorDecl>(MD))
497 return This;
498
499 MicrosoftVFTableContext::MethodVFTableLocation ML =
500 CGM.getVFTableContext().getMethodVFTableLocation(GD);
501
502 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
503 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
504 if (ML.VBase) {
505 This = CGF.Builder.CreateBitCast(This, charPtrTy);
506 llvm::Value *VBaseOffset = CGM.getCXXABI()
507 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
508 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
509 }
510 CharUnits StaticOffset = ML.VFTableOffset;
511 if (!StaticOffset.isZero()) {
512 assert(StaticOffset.isPositive());
513 This = CGF.Builder.CreateBitCast(This, charPtrTy);
514 This = CGF.Builder
515 .CreateConstInBoundsGEP1_64(This, StaticOffset.getQuantity());
516 }
517 return This;
518}
519
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000520static bool IsDeletingDtor(GlobalDecl GD) {
521 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
522 if (isa<CXXDestructorDecl>(MD)) {
523 return GD.getDtorType() == Dtor_Deleting;
524 }
525 return false;
526}
527
John McCallbd315742012-09-25 08:00:39 +0000528void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
529 QualType &ResTy,
530 FunctionArgList &Params) {
531 BuildThisParam(CGF, Params);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000532
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000533 ASTContext &Context = getContext();
534 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
535 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
536 ImplicitParamDecl *IsMostDerived
537 = ImplicitParamDecl::Create(Context, 0,
538 CGF.CurGD.getDecl()->getLocation(),
539 &Context.Idents.get("is_most_derived"),
540 Context.IntTy);
541 Params.push_back(IsMostDerived);
542 getStructorImplicitParamDecl(CGF) = IsMostDerived;
543 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000544 ImplicitParamDecl *ShouldDelete
545 = ImplicitParamDecl::Create(Context, 0,
546 CGF.CurGD.getDecl()->getLocation(),
547 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000548 Context.IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000549 Params.push_back(ShouldDelete);
550 getStructorImplicitParamDecl(CGF) = ShouldDelete;
551 }
John McCallbd315742012-09-25 08:00:39 +0000552}
553
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000554llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
555 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
556 GD = GD.getCanonicalDecl();
557 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
558 if (isa<CXXDestructorDecl>(MD))
559 return This;
560
561 // In this ABI, every virtual function takes a pointer to one of the
562 // subobjects that first defines it as the 'this' parameter, rather than a
563 // pointer to ther final overrider subobject. Thus, we need to adjust it back
564 // to the final overrider subobject before use.
565 // See comments in the MicrosoftVFTableContext implementation for the details.
566
567 MicrosoftVFTableContext::MethodVFTableLocation ML =
568 CGM.getVFTableContext().getMethodVFTableLocation(GD);
569 CharUnits Adjustment = ML.VFTableOffset;
570 if (ML.VBase) {
571 const ASTRecordLayout &DerivedLayout =
572 CGF.getContext().getASTRecordLayout(MD->getParent());
573 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
574 }
575
576 if (Adjustment.isZero())
577 return This;
578
579 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
580 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
581 *thisTy = This->getType();
582
583 This = CGF.Builder.CreateBitCast(This, charPtrTy);
584 assert(Adjustment.isPositive());
585 This = CGF.Builder.CreateConstGEP1_64(This, -Adjustment.getQuantity());
586 return CGF.Builder.CreateBitCast(This, thisTy);
587}
588
John McCallbd315742012-09-25 08:00:39 +0000589void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
590 EmitThisParam(CGF);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000591
592 /// If this is a function that the ABI specifies returns 'this', initialize
593 /// the return slot to 'this' at the start of the function.
594 ///
595 /// Unlike the setting of return types, this is done within the ABI
596 /// implementation instead of by clients of CGCXXABI because:
597 /// 1) getThisValue is currently protected
598 /// 2) in theory, an ABI could implement 'this' returns some other way;
599 /// HasThisReturn only specifies a contract, not the implementation
600 if (HasThisReturn(CGF.CurGD))
John McCallbd315742012-09-25 08:00:39 +0000601 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000602
603 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
604 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
605 assert(getStructorImplicitParamDecl(CGF) &&
606 "no implicit parameter for a constructor with virtual bases?");
607 getStructorImplicitParamValue(CGF)
608 = CGF.Builder.CreateLoad(
609 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
610 "is_most_derived");
611 }
612
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000613 if (IsDeletingDtor(CGF.CurGD)) {
614 assert(getStructorImplicitParamDecl(CGF) &&
615 "no implicit parameter for a deleting destructor?");
616 getStructorImplicitParamValue(CGF)
617 = CGF.Builder.CreateLoad(
618 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
619 "should_call_delete");
620 }
John McCallbd315742012-09-25 08:00:39 +0000621}
622
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000623void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000624 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000625 CXXCtorType Type,
626 bool ForVirtualBase,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000627 bool Delegating,
628 llvm::Value *This,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000629 CallExpr::const_arg_iterator ArgBeg,
630 CallExpr::const_arg_iterator ArgEnd) {
631 assert(Type == Ctor_Complete || Type == Ctor_Base);
632 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
633
634 llvm::Value *ImplicitParam = 0;
635 QualType ImplicitParamTy;
636 if (D->getParent()->getNumVBases()) {
637 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
638 ImplicitParamTy = getContext().IntTy;
639 }
640
641 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000642 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000643 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000644}
645
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000646void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
647 const CXXRecordDecl *RD) {
648 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
649 MicrosoftVFTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
650 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
651
652 for (MicrosoftVFTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
653 E = VFPtrs.end(); I != E; ++I) {
654 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
655 if (VTable->hasInitializer())
656 continue;
657
658 const VTableLayout &VTLayout =
659 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
660 llvm::Constant *Init = CGVT.CreateVTableInitializer(
661 RD, VTLayout.vtable_component_begin(),
662 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
663 VTLayout.getNumVTableThunks());
664 VTable->setInitializer(Init);
665
666 VTable->setLinkage(Linkage);
667 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
668 }
669}
670
671llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
672 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
673 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
674 NeedsVirtualOffset = (NearestVBase != 0);
675
676 llvm::Value *VTableAddressPoint =
677 getAddrOfVTable(VTableClass, Base.getBaseOffset());
678 if (!VTableAddressPoint) {
679 assert(Base.getBase()->getNumVBases() &&
680 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
681 }
682 return VTableAddressPoint;
683}
684
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000685static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
686 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
687 SmallString<256> &Name) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000688 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000689 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000690}
691
692llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
693 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
694 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
695 assert(VTable && "Couldn't find a vftable for the given base?");
696 return VTable;
697}
698
699llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
700 CharUnits VPtrOffset) {
701 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
702 // shouldn't be used in the given record type. We want to cache this result in
703 // VFTablesMap, thus a simple zero check is not sufficient.
704 VFTableIdTy ID(RD, VPtrOffset);
705 VFTablesMapTy::iterator I;
706 bool Inserted;
707 llvm::tie(I, Inserted) = VFTablesMap.insert(
708 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
709 if (!Inserted)
710 return I->second;
711
712 llvm::GlobalVariable *&VTable = I->second;
713
714 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
715 const MicrosoftVFTableContext::VFPtrListTy &VFPtrs =
716 VFTContext.getVFPtrOffsets(RD);
717
718 if (DeferredVFTables.insert(RD)) {
719 // We haven't processed this record type before.
720 // Queue up this v-table for possible deferred emission.
721 CGM.addDeferredVTable(RD);
722
723#ifndef NDEBUG
724 // Create all the vftables at once in order to make sure each vftable has
725 // a unique mangled name.
726 llvm::StringSet<> ObservedMangledNames;
727 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
728 SmallString<256> Name;
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000729 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000730 if (!ObservedMangledNames.insert(Name.str()))
731 llvm_unreachable("Already saw this mangling before?");
732 }
733#endif
734 }
735
736 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
737 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
738 continue;
739
740 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
741 CGM.Int8PtrTy,
742 VFTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
743 .getNumVTableComponents());
744
745 SmallString<256> Name;
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000746 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000747 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
748 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
749 VTable->setUnnamedAddr(true);
750 break;
751 }
752
753 return VTable;
754}
755
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000756llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
757 GlobalDecl GD,
758 llvm::Value *This,
759 llvm::Type *Ty) {
760 GD = GD.getCanonicalDecl();
761 CGBuilderTy &Builder = CGF.Builder;
762
763 Ty = Ty->getPointerTo()->getPointerTo();
764 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
765 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
766
767 MicrosoftVFTableContext::MethodVFTableLocation ML =
768 CGM.getVFTableContext().getMethodVFTableLocation(GD);
769 llvm::Value *VFuncPtr =
770 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
771 return Builder.CreateLoad(VFuncPtr);
772}
773
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000774void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
775 const CXXDestructorDecl *Dtor,
776 CXXDtorType DtorType,
777 SourceLocation CallLoc,
778 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000779 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
780
781 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000782 // by passing an implicit int parameter.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000783 const CGFunctionInfo *FInfo =
784 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000785 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000786 llvm::Value *Callee =
787 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, Dtor_Deleting), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000788
789 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000790 llvm::Value *ImplicitParam =
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000791 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000792 DtorType == Dtor_Deleting);
793
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000794 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000795 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000796}
797
Reid Kleckner90633022013-06-19 15:20:38 +0000798const VBTableVector &
799MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
800 // At this layer, we can key the cache off of a single class, which is much
801 // easier than caching at the GlobalVariable layer.
802 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
803 bool added;
804 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
805 VBTableVector &VBTables = I->second;
806 if (!added)
807 return VBTables;
808
809 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
810
811 return VBTables;
812}
813
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000814void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner90633022013-06-19 15:20:38 +0000815 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000816 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
817
Reid Kleckner90633022013-06-19 15:20:38 +0000818 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
819 I != E; ++I) {
820 I->EmitVBTableDefinition(CGM, RD, Linkage);
821 }
822}
823
John McCalle2b45e22012-05-01 05:23:51 +0000824bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
825 QualType elementType) {
826 // Microsoft seems to completely ignore the possibility of a
827 // two-argument usual deallocation function.
828 return elementType.isDestructedType();
829}
830
831bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
832 // Microsoft seems to completely ignore the possibility of a
833 // two-argument usual deallocation function.
834 return expr->getAllocatedType().isDestructedType();
835}
836
837CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
838 // The array cookie is always a size_t; we then pad that out to the
839 // alignment of the element type.
840 ASTContext &Ctx = getContext();
841 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
842 Ctx.getTypeAlignInChars(type));
843}
844
845llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
846 llvm::Value *allocPtr,
847 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +0000848 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000849 llvm::Value *numElementsPtr =
850 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
851 return CGF.Builder.CreateLoad(numElementsPtr);
852}
853
854llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
855 llvm::Value *newPtr,
856 llvm::Value *numElements,
857 const CXXNewExpr *expr,
858 QualType elementType) {
859 assert(requiresArrayCookie(expr));
860
861 // The size of the cookie.
862 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
863
864 // Compute an offset to the cookie.
865 llvm::Value *cookiePtr = newPtr;
866
867 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +0000868 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000869 llvm::Value *numElementsPtr
870 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
871 CGF.Builder.CreateStore(numElements, numElementsPtr);
872
873 // Finally, compute a pointer to the actual data buffer by skipping
874 // over the cookie completely.
875 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
876 cookieSize.getQuantity());
877}
878
John McCall20bb1752012-05-01 06:13:13 +0000879void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000880 llvm::GlobalVariable *GV,
John McCall20bb1752012-05-01 06:13:13 +0000881 bool PerformInit) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000882 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
883 // threadsafe. Since the user may be linking in inline functions compiled by
884 // cl.exe, there's no reason to provide a false sense of security by using
885 // critical sections here.
John McCall20bb1752012-05-01 06:13:13 +0000886
Richard Smith04e51762013-04-14 23:01:42 +0000887 if (D.getTLSKind())
888 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
889
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000890 CGBuilderTy &Builder = CGF.Builder;
891 llvm::IntegerType *GuardTy = CGF.Int32Ty;
892 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
893
894 // Get the guard variable for this function if we have one already.
895 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
896
897 unsigned BitIndex;
898 if (D.isExternallyVisible()) {
899 // Externally visible variables have to be numbered in Sema to properly
900 // handle unreachable VarDecls.
901 BitIndex = getContext().getManglingNumber(&D);
902 assert(BitIndex > 0);
903 BitIndex--;
904 } else {
905 // Non-externally visible variables are numbered here in CodeGen.
906 BitIndex = GI.BitIndex++;
907 }
908
909 if (BitIndex >= 32) {
910 if (D.isExternallyVisible())
911 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
912 BitIndex %= 32;
913 GI.Guard = 0;
914 }
915
916 // Lazily create the i32 bitfield for this function.
917 if (!GI.Guard) {
918 // Mangle the name for the guard.
919 SmallString<256> GuardName;
920 {
921 llvm::raw_svector_ostream Out(GuardName);
922 getMangleContext().mangleStaticGuardVariable(&D, Out);
923 Out.flush();
924 }
925
926 // Create the guard variable with a zero-initializer. Just absorb linkage
927 // and visibility from the guarded variable.
928 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
929 GV->getLinkage(), Zero, GuardName.str());
930 GI.Guard->setVisibility(GV->getVisibility());
931 } else {
932 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
933 "static local from the same function had different linkage");
934 }
935
936 // Pseudo code for the test:
937 // if (!(GuardVar & MyGuardBit)) {
938 // GuardVar |= MyGuardBit;
939 // ... initialize the object ...;
940 // }
941
942 // Test our bit from the guard variable.
943 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
944 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
945 llvm::Value *IsInitialized =
946 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
947 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
948 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
949 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
950
951 // Set our bit in the guard variable and emit the initializer and add a global
952 // destructor if appropriate.
953 CGF.EmitBlock(InitBlock);
954 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
955 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
956 Builder.CreateBr(EndBlock);
957
958 // Continue.
959 CGF.EmitBlock(EndBlock);
John McCall20bb1752012-05-01 06:13:13 +0000960}
961
Reid Klecknera3609b02013-04-11 18:13:19 +0000962// Member pointer helpers.
963static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
964 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000965}
966
Reid Klecknerf6327302013-05-09 21:01:17 +0000967static bool hasOnlyOneField(bool IsMemberFunction,
968 MSInheritanceModel Inheritance) {
969 return Inheritance <= MSIM_SinglePolymorphic ||
970 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000971}
972
Reid Klecknera3609b02013-04-11 18:13:19 +0000973// Only member pointers to functions need a this adjustment, since it can be
974// combined with the field offset for data pointers.
Reid Kleckner79e02912013-05-03 01:15:11 +0000975static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Klecknera3609b02013-04-11 18:13:19 +0000976 MSInheritanceModel Inheritance) {
Reid Kleckner79e02912013-05-03 01:15:11 +0000977 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Klecknera3609b02013-04-11 18:13:19 +0000978}
979
980static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
981 return Inheritance >= MSIM_Virtual;
982}
983
984// Use zero for the field offset of a null data member pointer if we can
985// guarantee that zero is not a valid field offset, or if the member pointer has
986// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
987// use zero for null. If there are multiple fields, we can use zero even if it
988// is a valid field offset because null-ness testing will check the other
989// fields.
990static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
991 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
992}
993
994bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
995 // Null-ness for function memptrs only depends on the first field, which is
996 // the function pointer. The rest don't matter, so we can zero initialize.
997 if (MPT->isMemberFunctionPointer())
998 return true;
999
1000 // The virtual base adjustment field is always -1 for null, so if we have one
1001 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1002 // valid field offset.
1003 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1004 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1005 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1006 nullFieldOffsetIsZero(Inheritance));
1007}
1008
1009llvm::Type *
1010MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1011 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1012 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1013 llvm::SmallVector<llvm::Type *, 4> fields;
1014 if (MPT->isMemberFunctionPointer())
1015 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1016 else
1017 fields.push_back(CGM.IntTy); // FieldOffset
1018
Reid Kleckner79e02912013-05-03 01:15:11 +00001019 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1020 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001021 fields.push_back(CGM.IntTy);
Reid Kleckner79e02912013-05-03 01:15:11 +00001022 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001023 fields.push_back(CGM.IntTy);
1024 if (hasVirtualBaseAdjustmentField(Inheritance))
1025 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1026
1027 if (fields.size() == 1)
1028 return fields[0];
1029 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1030}
1031
1032void MicrosoftCXXABI::
1033GetNullMemberPointerFields(const MemberPointerType *MPT,
1034 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1035 assert(fields.empty());
1036 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1037 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1038 if (MPT->isMemberFunctionPointer()) {
1039 // FunctionPointerOrVirtualThunk
1040 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1041 } else {
1042 if (nullFieldOffsetIsZero(Inheritance))
1043 fields.push_back(getZeroInt()); // FieldOffset
1044 else
1045 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +00001046 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001047
Reid Kleckner79e02912013-05-03 01:15:11 +00001048 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1049 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001050 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001051 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001052 fields.push_back(getZeroInt());
1053 if (hasVirtualBaseAdjustmentField(Inheritance))
1054 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001055}
1056
1057llvm::Constant *
1058MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001059 llvm::SmallVector<llvm::Constant *, 4> fields;
1060 GetNullMemberPointerFields(MPT, fields);
1061 if (fields.size() == 1)
1062 return fields[0];
1063 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1064 assert(Res->getType() == ConvertMemberPointerType(MPT));
1065 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001066}
1067
1068llvm::Constant *
Reid Kleckner79e02912013-05-03 01:15:11 +00001069MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1070 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +00001071 const CXXRecordDecl *RD,
1072 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner79e02912013-05-03 01:15:11 +00001073{
Reid Klecknera3609b02013-04-11 18:13:19 +00001074 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner79e02912013-05-03 01:15:11 +00001075
1076 // Single inheritance class member pointer are represented as scalars instead
1077 // of aggregates.
Reid Klecknerf6327302013-05-09 21:01:17 +00001078 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner79e02912013-05-03 01:15:11 +00001079 return FirstField;
1080
Reid Klecknera3609b02013-04-11 18:13:19 +00001081 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner79e02912013-05-03 01:15:11 +00001082 fields.push_back(FirstField);
1083
1084 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Klecknerf6327302013-05-09 21:01:17 +00001085 fields.push_back(llvm::ConstantInt::get(
1086 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner79e02912013-05-03 01:15:11 +00001087
Reid Klecknera3609b02013-04-11 18:13:19 +00001088 if (hasVBPtrOffsetField(Inheritance)) {
Reid Klecknera06d5852013-06-05 15:58:29 +00001089 fields.push_back(llvm::ConstantInt::get(
1090 CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity()));
Reid Klecknera3609b02013-04-11 18:13:19 +00001091 }
Reid Kleckner79e02912013-05-03 01:15:11 +00001092
1093 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Klecknera3609b02013-04-11 18:13:19 +00001094 if (hasVirtualBaseAdjustmentField(Inheritance))
1095 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001096
Reid Klecknera3609b02013-04-11 18:13:19 +00001097 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001098}
1099
Reid Kleckner79e02912013-05-03 01:15:11 +00001100llvm::Constant *
1101MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1102 CharUnits offset) {
1103 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1104 llvm::Constant *FirstField =
1105 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Klecknerf6327302013-05-09 21:01:17 +00001106 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1107 CharUnits::Zero());
1108}
1109
1110llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1111 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1112}
1113
1114llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1115 QualType MPType) {
1116 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1117 const ValueDecl *MPD = MP.getMemberPointerDecl();
1118 if (!MPD)
1119 return EmitNullMemberPointer(MPT);
1120
1121 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1122
1123 // FIXME PR15713: Support virtual inheritance paths.
1124
1125 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1126 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1127 MD, ThisAdjustment);
1128
1129 CharUnits FieldOffset =
1130 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1131 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner79e02912013-05-03 01:15:11 +00001132}
1133
1134llvm::Constant *
Reid Klecknerf6327302013-05-09 21:01:17 +00001135MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1136 const CXXMethodDecl *MD,
1137 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner79e02912013-05-03 01:15:11 +00001138 assert(MD->isInstance() && "Member function must not be static!");
1139 MD = MD->getCanonicalDecl();
Reid Kleckner79e02912013-05-03 01:15:11 +00001140 CodeGenTypes &Types = CGM.getTypes();
1141
1142 llvm::Constant *FirstField;
1143 if (MD->isVirtual()) {
1144 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1145 // the right offset.
1146 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1147 } else {
1148 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1149 llvm::Type *Ty;
1150 // Check whether the function has a computable LLVM signature.
1151 if (Types.isFuncTypeConvertible(FPT)) {
1152 // The function has a computable LLVM signature; use the correct type.
1153 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1154 } else {
1155 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1156 // function type is incomplete.
1157 Ty = CGM.PtrDiffTy;
1158 }
1159 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1160 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1161 }
1162
1163 // The rest of the fields are common with data member pointers.
Reid Klecknerf6327302013-05-09 21:01:17 +00001164 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1165 NonVirtualBaseAdjustment);
Reid Kleckner79e02912013-05-03 01:15:11 +00001166}
1167
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001168/// Member pointers are the same if they're either bitwise identical *or* both
1169/// null. Null-ness for function members is determined by the first field,
1170/// while for data member pointers we must compare all fields.
1171llvm::Value *
1172MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1173 llvm::Value *L,
1174 llvm::Value *R,
1175 const MemberPointerType *MPT,
1176 bool Inequality) {
1177 CGBuilderTy &Builder = CGF.Builder;
1178
1179 // Handle != comparisons by switching the sense of all boolean operations.
1180 llvm::ICmpInst::Predicate Eq;
1181 llvm::Instruction::BinaryOps And, Or;
1182 if (Inequality) {
1183 Eq = llvm::ICmpInst::ICMP_NE;
1184 And = llvm::Instruction::Or;
1185 Or = llvm::Instruction::And;
1186 } else {
1187 Eq = llvm::ICmpInst::ICMP_EQ;
1188 And = llvm::Instruction::And;
1189 Or = llvm::Instruction::Or;
1190 }
1191
1192 // If this is a single field member pointer (single inheritance), this is a
1193 // single icmp.
1194 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1195 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknerf6327302013-05-09 21:01:17 +00001196 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001197 return Builder.CreateICmp(Eq, L, R);
1198
1199 // Compare the first field.
1200 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1201 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1202 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1203
1204 // Compare everything other than the first field.
1205 llvm::Value *Res = 0;
1206 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1207 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1208 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1209 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1210 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1211 if (Res)
1212 Res = Builder.CreateBinOp(And, Res, Cmp);
1213 else
1214 Res = Cmp;
1215 }
1216
1217 // Check if the first field is 0 if this is a function pointer.
1218 if (MPT->isMemberFunctionPointer()) {
1219 // (l1 == r1 && ...) || l0 == 0
1220 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1221 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1222 Res = Builder.CreateBinOp(Or, Res, IsZero);
1223 }
1224
1225 // Combine the comparison of the first field, which must always be true for
1226 // this comparison to succeeed.
1227 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1228}
1229
Reid Klecknera8a0f762013-03-22 19:02:54 +00001230llvm::Value *
1231MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1232 llvm::Value *MemPtr,
1233 const MemberPointerType *MPT) {
1234 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001235 llvm::SmallVector<llvm::Constant *, 4> fields;
1236 // We only need one field for member functions.
1237 if (MPT->isMemberFunctionPointer())
1238 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1239 else
1240 GetNullMemberPointerFields(MPT, fields);
1241 assert(!fields.empty());
1242 llvm::Value *FirstField = MemPtr;
1243 if (MemPtr->getType()->isStructTy())
1244 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1245 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001246
Reid Klecknera3609b02013-04-11 18:13:19 +00001247 // For function member pointers, we only need to test the function pointer
1248 // field. The other fields if any can be garbage.
1249 if (MPT->isMemberFunctionPointer())
1250 return Res;
1251
1252 // Otherwise, emit a series of compares and combine the results.
1253 for (int I = 1, E = fields.size(); I < E; ++I) {
1254 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1255 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1256 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1257 }
1258 return Res;
1259}
1260
Reid Klecknerf6327302013-05-09 21:01:17 +00001261bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1262 llvm::Constant *Val) {
1263 // Function pointers are null if the pointer in the first field is null.
1264 if (MPT->isMemberFunctionPointer()) {
1265 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1266 Val->getAggregateElement(0U) : Val;
1267 return FirstField->isNullValue();
1268 }
1269
1270 // If it's not a function pointer and it's zero initializable, we can easily
1271 // check zero.
1272 if (isZeroInitializable(MPT) && Val->isNullValue())
1273 return true;
1274
1275 // Otherwise, break down all the fields for comparison. Hopefully these
1276 // little Constants are reused, while a big null struct might not be.
1277 llvm::SmallVector<llvm::Constant *, 4> Fields;
1278 GetNullMemberPointerFields(MPT, Fields);
1279 if (Fields.size() == 1) {
1280 assert(Val->getType()->isIntegerTy());
1281 return Val == Fields[0];
1282 }
1283
1284 unsigned I, E;
1285 for (I = 0, E = Fields.size(); I != E; ++I) {
1286 if (Val->getAggregateElement(I) != Fields[I])
1287 break;
1288 }
1289 return I == E;
1290}
1291
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001292llvm::Value *
1293MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1294 llvm::Value *This,
1295 llvm::Value *VBTableOffset,
1296 llvm::Value *VBPtrOffset,
1297 llvm::Value **VBPtrOut) {
1298 CGBuilderTy &Builder = CGF.Builder;
1299 // Load the vbtable pointer from the vbptr in the instance.
1300 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1301 llvm::Value *VBPtr =
1302 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1303 if (VBPtrOut) *VBPtrOut = VBPtr;
1304 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1305 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1306
1307 // Load an i32 offset from the vb-table.
1308 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1309 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1310 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1311}
1312
Reid Klecknera3609b02013-04-11 18:13:19 +00001313// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1314// it.
1315llvm::Value *
1316MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1317 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001318 llvm::Value *VBTableOffset,
Reid Klecknera3609b02013-04-11 18:13:19 +00001319 llvm::Value *VBPtrOffset) {
1320 CGBuilderTy &Builder = CGF.Builder;
1321 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1322 llvm::BasicBlock *OriginalBB = 0;
1323 llvm::BasicBlock *SkipAdjustBB = 0;
1324 llvm::BasicBlock *VBaseAdjustBB = 0;
1325
1326 // In the unspecified inheritance model, there might not be a vbtable at all,
1327 // in which case we need to skip the virtual base lookup. If there is a
1328 // vbtable, the first entry is a no-op entry that gives back the original
1329 // base, so look for a virtual base adjustment offset of zero.
1330 if (VBPtrOffset) {
1331 OriginalBB = Builder.GetInsertBlock();
1332 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1333 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1334 llvm::Value *IsVirtual =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001335 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Klecknera3609b02013-04-11 18:13:19 +00001336 "memptr.is_vbase");
1337 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1338 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001339 }
1340
Reid Klecknera3609b02013-04-11 18:13:19 +00001341 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1342 // know the vbptr offset.
1343 if (!VBPtrOffset) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001344 CharUnits offs = CharUnits::Zero();
1345 if (RD->getNumVBases()) {
1346 offs = GetVBPtrOffsetFromBases(RD);
1347 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001348 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1349 }
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001350 llvm::Value *VBPtr = 0;
Reid Klecknera3609b02013-04-11 18:13:19 +00001351 llvm::Value *VBaseOffs =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001352 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Klecknera3609b02013-04-11 18:13:19 +00001353 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1354
1355 // Merge control flow with the case where we didn't have to adjust.
1356 if (VBaseAdjustBB) {
1357 Builder.CreateBr(SkipAdjustBB);
1358 CGF.EmitBlock(SkipAdjustBB);
1359 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1360 Phi->addIncoming(Base, OriginalBB);
1361 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1362 return Phi;
1363 }
1364 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001365}
1366
1367llvm::Value *
1368MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1369 llvm::Value *Base,
1370 llvm::Value *MemPtr,
1371 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001372 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001373 unsigned AS = Base->getType()->getPointerAddressSpace();
1374 llvm::Type *PType =
1375 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1376 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001377 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1378 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +00001379
Reid Klecknera3609b02013-04-11 18:13:19 +00001380 // Extract the fields we need, regardless of model. We'll apply them if we
1381 // have them.
1382 llvm::Value *FieldOffset = MemPtr;
1383 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1384 llvm::Value *VBPtrOffset = 0;
1385 if (MemPtr->getType()->isStructTy()) {
1386 // We need to extract values.
1387 unsigned I = 0;
1388 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1389 if (hasVBPtrOffsetField(Inheritance))
1390 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1391 if (hasVirtualBaseAdjustmentField(Inheritance))
1392 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001393 }
1394
Reid Klecknera3609b02013-04-11 18:13:19 +00001395 if (VirtualBaseAdjustmentOffset) {
1396 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1397 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001398 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001399 llvm::Value *Addr =
1400 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001401
1402 // Cast the address to the appropriate pointer type, adopting the address
1403 // space of the base pointer.
1404 return Builder.CreateBitCast(Addr, PType);
1405}
1406
Reid Klecknerf6327302013-05-09 21:01:17 +00001407static MSInheritanceModel
1408getInheritanceFromMemptr(const MemberPointerType *MPT) {
1409 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1410}
1411
1412llvm::Value *
1413MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1414 const CastExpr *E,
1415 llvm::Value *Src) {
1416 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1417 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1418 E->getCastKind() == CK_ReinterpretMemberPointer);
1419
1420 // Use constant emission if we can.
1421 if (isa<llvm::Constant>(Src))
1422 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1423
1424 // We may be adding or dropping fields from the member pointer, so we need
1425 // both types and the inheritance models of both records.
1426 const MemberPointerType *SrcTy =
1427 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1428 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1429 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1430 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1431 bool IsFunc = SrcTy->isMemberFunctionPointer();
1432
1433 // If the classes use the same null representation, reinterpret_cast is a nop.
1434 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1435 if (IsReinterpret && (IsFunc ||
1436 nullFieldOffsetIsZero(SrcInheritance) ==
1437 nullFieldOffsetIsZero(DstInheritance)))
1438 return Src;
1439
1440 CGBuilderTy &Builder = CGF.Builder;
1441
1442 // Branch past the conversion if Src is null.
1443 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1444 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1445
1446 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1447 // pointer value of the destination type.
1448 if (IsReinterpret) {
1449 // For reinterpret casts, sema ensures that src and dst are both functions
1450 // or data and have the same size, which means the LLVM types should match.
1451 assert(Src->getType() == DstNull->getType());
1452 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1453 }
1454
1455 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1456 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1457 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1458 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1459 CGF.EmitBlock(ConvertBB);
1460
1461 // Decompose src.
1462 llvm::Value *FirstField = Src;
1463 llvm::Value *NonVirtualBaseAdjustment = 0;
1464 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1465 llvm::Value *VBPtrOffset = 0;
1466 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1467 // We need to extract values.
1468 unsigned I = 0;
1469 FirstField = Builder.CreateExtractValue(Src, I++);
1470 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1471 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1472 if (hasVBPtrOffsetField(SrcInheritance))
1473 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1474 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1475 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1476 }
1477
1478 // For data pointers, we adjust the field offset directly. For functions, we
1479 // have a separate field.
1480 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1481 if (Adj) {
1482 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1483 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1484 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1485 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1486 NVAdjustField = getZeroInt();
1487 if (isDerivedToBase)
1488 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1489 else
1490 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1491 }
1492
1493 // FIXME PR15713: Support conversions through virtually derived classes.
1494
1495 // Recompose dst from the null struct and the adjusted fields from src.
1496 llvm::Value *Dst;
1497 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1498 Dst = FirstField;
1499 } else {
1500 Dst = llvm::UndefValue::get(DstNull->getType());
1501 unsigned Idx = 0;
1502 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1503 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1504 Dst = Builder.CreateInsertValue(
1505 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1506 if (hasVBPtrOffsetField(DstInheritance))
1507 Dst = Builder.CreateInsertValue(
1508 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1509 if (hasVirtualBaseAdjustmentField(DstInheritance))
1510 Dst = Builder.CreateInsertValue(
1511 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1512 }
1513 Builder.CreateBr(ContinueBB);
1514
1515 // In the continuation, choose between DstNull and Dst.
1516 CGF.EmitBlock(ContinueBB);
1517 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1518 Phi->addIncoming(DstNull, OriginalBB);
1519 Phi->addIncoming(Dst, ConvertBB);
1520 return Phi;
1521}
1522
1523llvm::Constant *
1524MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1525 llvm::Constant *Src) {
1526 const MemberPointerType *SrcTy =
1527 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1528 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1529
1530 // If src is null, emit a new null for dst. We can't return src because dst
1531 // might have a new representation.
1532 if (MemberPointerConstantIsNull(SrcTy, Src))
1533 return EmitNullMemberPointer(DstTy);
1534
1535 // We don't need to do anything for reinterpret_casts of non-null member
1536 // pointers. We should only get here when the two type representations have
1537 // the same size.
1538 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1539 return Src;
1540
1541 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1542 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1543
1544 // Decompose src.
1545 llvm::Constant *FirstField = Src;
1546 llvm::Constant *NonVirtualBaseAdjustment = 0;
1547 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1548 llvm::Constant *VBPtrOffset = 0;
1549 bool IsFunc = SrcTy->isMemberFunctionPointer();
1550 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1551 // We need to extract values.
1552 unsigned I = 0;
1553 FirstField = Src->getAggregateElement(I++);
1554 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1555 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1556 if (hasVBPtrOffsetField(SrcInheritance))
1557 VBPtrOffset = Src->getAggregateElement(I++);
1558 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1559 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1560 }
1561
1562 // For data pointers, we adjust the field offset directly. For functions, we
1563 // have a separate field.
1564 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1565 if (Adj) {
1566 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1567 llvm::Constant *&NVAdjustField =
1568 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1569 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1570 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1571 NVAdjustField = getZeroInt();
1572 if (IsDerivedToBase)
1573 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1574 else
1575 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1576 }
1577
1578 // FIXME PR15713: Support conversions through virtually derived classes.
1579
1580 // Recompose dst from the null struct and the adjusted fields from src.
1581 if (hasOnlyOneField(IsFunc, DstInheritance))
1582 return FirstField;
1583
1584 llvm::SmallVector<llvm::Constant *, 4> Fields;
1585 Fields.push_back(FirstField);
1586 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1587 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1588 if (hasVBPtrOffsetField(DstInheritance))
1589 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1590 if (hasVirtualBaseAdjustmentField(DstInheritance))
1591 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1592 return llvm::ConstantStruct::getAnon(Fields);
1593}
1594
Reid Klecknera3609b02013-04-11 18:13:19 +00001595llvm::Value *
1596MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1597 llvm::Value *&This,
1598 llvm::Value *MemPtr,
1599 const MemberPointerType *MPT) {
1600 assert(MPT->isMemberFunctionPointer());
1601 const FunctionProtoType *FPT =
1602 MPT->getPointeeType()->castAs<FunctionProtoType>();
1603 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1604 llvm::FunctionType *FTy =
1605 CGM.getTypes().GetFunctionType(
1606 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1607 CGBuilderTy &Builder = CGF.Builder;
1608
1609 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1610
1611 // Extract the fields we need, regardless of model. We'll apply them if we
1612 // have them.
1613 llvm::Value *FunctionPointer = MemPtr;
1614 llvm::Value *NonVirtualBaseAdjustment = NULL;
1615 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1616 llvm::Value *VBPtrOffset = NULL;
1617 if (MemPtr->getType()->isStructTy()) {
1618 // We need to extract values.
1619 unsigned I = 0;
1620 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001621 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1622 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner79e02912013-05-03 01:15:11 +00001623 if (hasVBPtrOffsetField(Inheritance))
1624 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001625 if (hasVirtualBaseAdjustmentField(Inheritance))
1626 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1627 }
1628
1629 if (VirtualBaseAdjustmentOffset) {
1630 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1631 VBPtrOffset);
1632 }
1633
1634 if (NonVirtualBaseAdjustment) {
1635 // Apply the adjustment and cast back to the original struct type.
1636 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1637 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1638 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1639 }
1640
1641 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1642}
1643
Charles Davis071cc7d2010-08-16 03:33:14 +00001644CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +00001645 return new MicrosoftCXXABI(CGM);
1646}
1647