blob: cfdbaa2957f3a655e02535ef7d745452e9dc55d6 [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:
Reid Klecknera3609b02013-04-11 18:13:19 +0000218 llvm::Constant *getZeroInt() {
219 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000220 }
221
Reid Klecknera3609b02013-04-11 18:13:19 +0000222 llvm::Constant *getAllOnesInt() {
223 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000224 }
225
Reid Klecknerf6327302013-05-09 21:01:17 +0000226 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
227 return C ? C : getZeroInt();
228 }
229
230 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
231 return C ? C : getZeroInt();
232 }
233
Reid Klecknera3609b02013-04-11 18:13:19 +0000234 void
235 GetNullMemberPointerFields(const MemberPointerType *MPT,
236 llvm::SmallVectorImpl<llvm::Constant *> &fields);
237
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000238 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
239 /// it is reusing a vbptr from a non-virtual base. RD must have morally
240 /// virtual bases.
241 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
242
243 /// \brief Shared code for virtual base adjustment. Returns the offset from
244 /// the vbptr to the virtual base. Optionally returns the address of the
245 /// vbptr itself.
246 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
247 llvm::Value *Base,
248 llvm::Value *VBPtrOffset,
249 llvm::Value *VBTableOffset,
250 llvm::Value **VBPtr = 0);
251
252 /// \brief Performs a full virtual base adjustment. Used to dereference
253 /// pointers to members of virtual bases.
Reid Klecknera3609b02013-04-11 18:13:19 +0000254 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
255 llvm::Value *Base,
256 llvm::Value *VirtualBaseAdjustmentOffset,
257 llvm::Value *VBPtrOffset /* optional */);
258
Reid Kleckner79e02912013-05-03 01:15:11 +0000259 /// \brief Emits a full member pointer with the fields common to data and
260 /// function member pointers.
261 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
262 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000263 const CXXRecordDecl *RD,
264 CharUnits NonVirtualBaseAdjustment);
265
266 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
267 const CXXMethodDecl *MD,
268 CharUnits NonVirtualBaseAdjustment);
269
270 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
271 llvm::Constant *MP);
Reid Kleckner79e02912013-05-03 01:15:11 +0000272
Reid Kleckner90633022013-06-19 15:20:38 +0000273 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
274 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
275
276 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
277 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
278
Reid Klecknera8a0f762013-03-22 19:02:54 +0000279public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000280 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
281
282 virtual bool isZeroInitializable(const MemberPointerType *MPT);
283
Reid Klecknera8a0f762013-03-22 19:02:54 +0000284 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
285
286 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
287 CharUnits offset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000288 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
289 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000290
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000291 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
292 llvm::Value *L,
293 llvm::Value *R,
294 const MemberPointerType *MPT,
295 bool Inequality);
296
Reid Klecknera8a0f762013-03-22 19:02:54 +0000297 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
298 llvm::Value *MemPtr,
299 const MemberPointerType *MPT);
300
301 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
302 llvm::Value *Base,
303 llvm::Value *MemPtr,
304 const MemberPointerType *MPT);
305
Reid Klecknerf6327302013-05-09 21:01:17 +0000306 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
307 const CastExpr *E,
308 llvm::Value *Src);
309
310 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
311 llvm::Constant *Src);
312
Reid Klecknera3609b02013-04-11 18:13:19 +0000313 virtual llvm::Value *
314 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
315 llvm::Value *&This,
316 llvm::Value *MemPtr,
317 const MemberPointerType *MPT);
318
Reid Kleckner90633022013-06-19 15:20:38 +0000319private:
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000320 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
321 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
322 /// \brief All the vftables that have been referenced.
323 VFTablesMapTy VFTablesMap;
324
325 /// \brief This set holds the record decls we've deferred vtable emission for.
326 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
327
328
329 /// \brief All the vbtables which have been referenced.
Reid Kleckner90633022013-06-19 15:20:38 +0000330 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000331
332 /// Info on the global variable used to guard initialization of static locals.
333 /// The BitIndex field is only used for externally invisible declarations.
334 struct GuardInfo {
335 GuardInfo() : Guard(0), BitIndex(0) {}
336 llvm::GlobalVariable *Guard;
337 unsigned BitIndex;
338 };
339
340 /// Map from DeclContext to the current guard variable. We assume that the
341 /// AST is visited in source code order.
342 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davisc3926642010-06-09 23:25:41 +0000343};
344
345}
346
John McCallecd03b42012-09-25 10:10:39 +0000347llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
348 llvm::Value *ptr,
349 QualType type) {
350 // FIXME: implement
351 return ptr;
352}
353
Reid Kleckner8c474322013-06-04 21:32:29 +0000354/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
355/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
356static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
357 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
358 E = RD->bases_end(); I != E; ++I) {
359 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
360 if (!I->isVirtual() && Base->getNumVBases() > 0)
361 return Base;
362 }
363 llvm_unreachable("RD must have an nv base with vbases");
364}
365
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000366CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
367 assert(RD->getNumVBases());
368 CharUnits Total = CharUnits::Zero();
369 while (RD) {
370 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
371 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
372 // -1 is the sentinel for no vbptr.
373 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
374 Total += VBPtrOffset;
375 break;
376 }
Reid Kleckner8c474322013-06-04 21:32:29 +0000377 RD = FindFirstNVBaseWithVBases(RD);
378 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000379 }
380 return Total;
381}
382
383llvm::Value *
384MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
385 llvm::Value *This,
386 const CXXRecordDecl *ClassDecl,
387 const CXXRecordDecl *BaseClassDecl) {
388 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
389 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000390 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner8c474322013-06-04 21:32:29 +0000391 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000392 llvm::Value *VBTableOffset =
393 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
394
395 llvm::Value *VBPtrToNewBase =
396 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
397 VBPtrToNewBase =
398 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
399 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
400}
401
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000402bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
403 return isa<CXXConstructorDecl>(GD.getDecl());
John McCallbd315742012-09-25 08:00:39 +0000404}
405
406void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
407 CXXCtorType Type,
408 CanQualType &ResTy,
409 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000410 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000411
412 const CXXRecordDecl *Class = Ctor->getParent();
413 if (Class->getNumVBases()) {
414 // Constructors of classes with virtual bases take an implicit parameter.
415 ArgTys.push_back(CGM.getContext().IntTy);
416 }
417}
418
Reid Kleckner90633022013-06-19 15:20:38 +0000419llvm::BasicBlock *
420MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
421 const CXXRecordDecl *RD) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000422 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
423 assert(IsMostDerivedClass &&
424 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner90633022013-06-19 15:20:38 +0000425 llvm::Value *IsCompleteObject =
426 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000427
428 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
429 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
430 CGF.Builder.CreateCondBr(IsCompleteObject,
431 CallVbaseCtorsBB, SkipVbaseCtorsBB);
432
433 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner90633022013-06-19 15:20:38 +0000434
435 // Fill in the vbtable pointers here.
436 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000437
438 // CGF will put the base ctor calls in this basic block for us later.
439
440 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000441}
442
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000443void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
444 // There's only one constructor type in this ABI.
445 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
446}
447
Reid Kleckner90633022013-06-19 15:20:38 +0000448void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
449 const CXXRecordDecl *RD) {
450 llvm::Value *ThisInt8Ptr =
451 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
452
453 const VBTableVector &VBTables = EnumerateVBTables(RD);
454 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
455 I != E; ++I) {
456 const ASTRecordLayout &SubobjectLayout =
457 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
458 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
459 SubobjectLayout.getVBPtrOffset()).getQuantity();
460 llvm::Value *VBPtr =
461 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
462 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
463 "vbptr." + I->ReusingBase->getName());
464 CGF.Builder.CreateStore(I->GV, VBPtr);
465 }
466}
467
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000468void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
469 CXXDtorType Type,
470 CanQualType &ResTy,
471 SmallVectorImpl<CanQualType> &ArgTys) {
472 // 'this' is already in place
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000473
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000474 // TODO: 'for base' flag
475
476 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000477 // The scalar deleting destructor takes an implicit int parameter.
478 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000479 }
480}
481
Reid Klecknera4130ba2013-07-22 13:51:44 +0000482void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
483 // The TU defining a dtor is only guaranteed to emit a base destructor. All
484 // other destructor variants are delegating thunks.
485 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
486}
487
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000488llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
489 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
490 GD = GD.getCanonicalDecl();
491 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
492 if (isa<CXXDestructorDecl>(MD))
493 return This;
494
495 MicrosoftVFTableContext::MethodVFTableLocation ML =
496 CGM.getVFTableContext().getMethodVFTableLocation(GD);
497
498 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
499 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
500 if (ML.VBase) {
501 This = CGF.Builder.CreateBitCast(This, charPtrTy);
502 llvm::Value *VBaseOffset = CGM.getCXXABI()
503 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
504 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
505 }
506 CharUnits StaticOffset = ML.VFTableOffset;
507 if (!StaticOffset.isZero()) {
508 assert(StaticOffset.isPositive());
509 This = CGF.Builder.CreateBitCast(This, charPtrTy);
510 This = CGF.Builder
511 .CreateConstInBoundsGEP1_64(This, StaticOffset.getQuantity());
512 }
513 return This;
514}
515
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000516static bool IsDeletingDtor(GlobalDecl GD) {
517 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
518 if (isa<CXXDestructorDecl>(MD)) {
519 return GD.getDtorType() == Dtor_Deleting;
520 }
521 return false;
522}
523
John McCallbd315742012-09-25 08:00:39 +0000524void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
525 QualType &ResTy,
526 FunctionArgList &Params) {
527 BuildThisParam(CGF, Params);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000528
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000529 ASTContext &Context = getContext();
530 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
531 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
532 ImplicitParamDecl *IsMostDerived
533 = ImplicitParamDecl::Create(Context, 0,
534 CGF.CurGD.getDecl()->getLocation(),
535 &Context.Idents.get("is_most_derived"),
536 Context.IntTy);
537 Params.push_back(IsMostDerived);
538 getStructorImplicitParamDecl(CGF) = IsMostDerived;
539 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000540 ImplicitParamDecl *ShouldDelete
541 = ImplicitParamDecl::Create(Context, 0,
542 CGF.CurGD.getDecl()->getLocation(),
543 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000544 Context.IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000545 Params.push_back(ShouldDelete);
546 getStructorImplicitParamDecl(CGF) = ShouldDelete;
547 }
John McCallbd315742012-09-25 08:00:39 +0000548}
549
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000550llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
551 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
552 GD = GD.getCanonicalDecl();
553 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
554 if (isa<CXXDestructorDecl>(MD))
555 return This;
556
557 // In this ABI, every virtual function takes a pointer to one of the
558 // subobjects that first defines it as the 'this' parameter, rather than a
559 // pointer to ther final overrider subobject. Thus, we need to adjust it back
560 // to the final overrider subobject before use.
561 // See comments in the MicrosoftVFTableContext implementation for the details.
562
563 MicrosoftVFTableContext::MethodVFTableLocation ML =
564 CGM.getVFTableContext().getMethodVFTableLocation(GD);
565 CharUnits Adjustment = ML.VFTableOffset;
566 if (ML.VBase) {
567 const ASTRecordLayout &DerivedLayout =
568 CGF.getContext().getASTRecordLayout(MD->getParent());
569 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
570 }
571
572 if (Adjustment.isZero())
573 return This;
574
575 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
576 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
577 *thisTy = This->getType();
578
579 This = CGF.Builder.CreateBitCast(This, charPtrTy);
580 assert(Adjustment.isPositive());
581 This = CGF.Builder.CreateConstGEP1_64(This, -Adjustment.getQuantity());
582 return CGF.Builder.CreateBitCast(This, thisTy);
583}
584
John McCallbd315742012-09-25 08:00:39 +0000585void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
586 EmitThisParam(CGF);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000587
588 /// If this is a function that the ABI specifies returns 'this', initialize
589 /// the return slot to 'this' at the start of the function.
590 ///
591 /// Unlike the setting of return types, this is done within the ABI
592 /// implementation instead of by clients of CGCXXABI because:
593 /// 1) getThisValue is currently protected
594 /// 2) in theory, an ABI could implement 'this' returns some other way;
595 /// HasThisReturn only specifies a contract, not the implementation
596 if (HasThisReturn(CGF.CurGD))
John McCallbd315742012-09-25 08:00:39 +0000597 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000598
599 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
600 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
601 assert(getStructorImplicitParamDecl(CGF) &&
602 "no implicit parameter for a constructor with virtual bases?");
603 getStructorImplicitParamValue(CGF)
604 = CGF.Builder.CreateLoad(
605 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
606 "is_most_derived");
607 }
608
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000609 if (IsDeletingDtor(CGF.CurGD)) {
610 assert(getStructorImplicitParamDecl(CGF) &&
611 "no implicit parameter for a deleting destructor?");
612 getStructorImplicitParamValue(CGF)
613 = CGF.Builder.CreateLoad(
614 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
615 "should_call_delete");
616 }
John McCallbd315742012-09-25 08:00:39 +0000617}
618
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000619void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000620 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000621 CXXCtorType Type,
622 bool ForVirtualBase,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000623 bool Delegating,
624 llvm::Value *This,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000625 CallExpr::const_arg_iterator ArgBeg,
626 CallExpr::const_arg_iterator ArgEnd) {
627 assert(Type == Ctor_Complete || Type == Ctor_Base);
628 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
629
630 llvm::Value *ImplicitParam = 0;
631 QualType ImplicitParamTy;
632 if (D->getParent()->getNumVBases()) {
633 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
634 ImplicitParamTy = getContext().IntTy;
635 }
636
637 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000638 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000639 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000640}
641
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000642void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
643 const CXXRecordDecl *RD) {
644 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
645 MicrosoftVFTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
646 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
647
648 for (MicrosoftVFTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
649 E = VFPtrs.end(); I != E; ++I) {
650 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
651 if (VTable->hasInitializer())
652 continue;
653
654 const VTableLayout &VTLayout =
655 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
656 llvm::Constant *Init = CGVT.CreateVTableInitializer(
657 RD, VTLayout.vtable_component_begin(),
658 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
659 VTLayout.getNumVTableThunks());
660 VTable->setInitializer(Init);
661
662 VTable->setLinkage(Linkage);
663 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
664 }
665}
666
667llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
668 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
669 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
670 NeedsVirtualOffset = (NearestVBase != 0);
671
672 llvm::Value *VTableAddressPoint =
673 getAddrOfVTable(VTableClass, Base.getBaseOffset());
674 if (!VTableAddressPoint) {
675 assert(Base.getBase()->getNumVBases() &&
676 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
677 }
678 return VTableAddressPoint;
679}
680
681static void mangleVFTableName(CodeGenModule &CGM, const CXXRecordDecl *RD,
682 const VFPtrInfo &VFPtr, SmallString<256> &Name) {
683 llvm::raw_svector_ostream Out(Name);
684 CGM.getCXXABI().getMangleContext().mangleCXXVFTable(
685 RD, VFPtr.PathToMangle, Out);
686}
687
688llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
689 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
690 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
691 assert(VTable && "Couldn't find a vftable for the given base?");
692 return VTable;
693}
694
695llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
696 CharUnits VPtrOffset) {
697 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
698 // shouldn't be used in the given record type. We want to cache this result in
699 // VFTablesMap, thus a simple zero check is not sufficient.
700 VFTableIdTy ID(RD, VPtrOffset);
701 VFTablesMapTy::iterator I;
702 bool Inserted;
703 llvm::tie(I, Inserted) = VFTablesMap.insert(
704 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
705 if (!Inserted)
706 return I->second;
707
708 llvm::GlobalVariable *&VTable = I->second;
709
710 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
711 const MicrosoftVFTableContext::VFPtrListTy &VFPtrs =
712 VFTContext.getVFPtrOffsets(RD);
713
714 if (DeferredVFTables.insert(RD)) {
715 // We haven't processed this record type before.
716 // Queue up this v-table for possible deferred emission.
717 CGM.addDeferredVTable(RD);
718
719#ifndef NDEBUG
720 // Create all the vftables at once in order to make sure each vftable has
721 // a unique mangled name.
722 llvm::StringSet<> ObservedMangledNames;
723 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
724 SmallString<256> Name;
725 mangleVFTableName(CGM, RD, VFPtrs[J], Name);
726 if (!ObservedMangledNames.insert(Name.str()))
727 llvm_unreachable("Already saw this mangling before?");
728 }
729#endif
730 }
731
732 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
733 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
734 continue;
735
736 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
737 CGM.Int8PtrTy,
738 VFTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
739 .getNumVTableComponents());
740
741 SmallString<256> Name;
742 mangleVFTableName(CGM, RD, VFPtrs[J], Name);
743 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
744 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
745 VTable->setUnnamedAddr(true);
746 break;
747 }
748
749 return VTable;
750}
751
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000752llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
753 GlobalDecl GD,
754 llvm::Value *This,
755 llvm::Type *Ty) {
756 GD = GD.getCanonicalDecl();
757 CGBuilderTy &Builder = CGF.Builder;
758
759 Ty = Ty->getPointerTo()->getPointerTo();
760 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
761 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
762
763 MicrosoftVFTableContext::MethodVFTableLocation ML =
764 CGM.getVFTableContext().getMethodVFTableLocation(GD);
765 llvm::Value *VFuncPtr =
766 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
767 return Builder.CreateLoad(VFuncPtr);
768}
769
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000770void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
771 const CXXDestructorDecl *Dtor,
772 CXXDtorType DtorType,
773 SourceLocation CallLoc,
774 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000775 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
776
777 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000778 // by passing an implicit int parameter.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000779 const CGFunctionInfo *FInfo =
780 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000781 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000782 llvm::Value *Callee =
783 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, Dtor_Deleting), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000784
785 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000786 llvm::Value *ImplicitParam =
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000787 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000788 DtorType == Dtor_Deleting);
789
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000790 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000791 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000792}
793
Reid Kleckner90633022013-06-19 15:20:38 +0000794const VBTableVector &
795MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
796 // At this layer, we can key the cache off of a single class, which is much
797 // easier than caching at the GlobalVariable layer.
798 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
799 bool added;
800 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
801 VBTableVector &VBTables = I->second;
802 if (!added)
803 return VBTables;
804
805 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
806
807 return VBTables;
808}
809
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000810void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner90633022013-06-19 15:20:38 +0000811 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000812 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
813
Reid Kleckner90633022013-06-19 15:20:38 +0000814 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
815 I != E; ++I) {
816 I->EmitVBTableDefinition(CGM, RD, Linkage);
817 }
818}
819
John McCalle2b45e22012-05-01 05:23:51 +0000820bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
821 QualType elementType) {
822 // Microsoft seems to completely ignore the possibility of a
823 // two-argument usual deallocation function.
824 return elementType.isDestructedType();
825}
826
827bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
828 // Microsoft seems to completely ignore the possibility of a
829 // two-argument usual deallocation function.
830 return expr->getAllocatedType().isDestructedType();
831}
832
833CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
834 // The array cookie is always a size_t; we then pad that out to the
835 // alignment of the element type.
836 ASTContext &Ctx = getContext();
837 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
838 Ctx.getTypeAlignInChars(type));
839}
840
841llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
842 llvm::Value *allocPtr,
843 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +0000844 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000845 llvm::Value *numElementsPtr =
846 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
847 return CGF.Builder.CreateLoad(numElementsPtr);
848}
849
850llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
851 llvm::Value *newPtr,
852 llvm::Value *numElements,
853 const CXXNewExpr *expr,
854 QualType elementType) {
855 assert(requiresArrayCookie(expr));
856
857 // The size of the cookie.
858 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
859
860 // Compute an offset to the cookie.
861 llvm::Value *cookiePtr = newPtr;
862
863 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +0000864 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000865 llvm::Value *numElementsPtr
866 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
867 CGF.Builder.CreateStore(numElements, numElementsPtr);
868
869 // Finally, compute a pointer to the actual data buffer by skipping
870 // over the cookie completely.
871 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
872 cookieSize.getQuantity());
873}
874
John McCall20bb1752012-05-01 06:13:13 +0000875void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000876 llvm::GlobalVariable *GV,
John McCall20bb1752012-05-01 06:13:13 +0000877 bool PerformInit) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000878 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
879 // threadsafe. Since the user may be linking in inline functions compiled by
880 // cl.exe, there's no reason to provide a false sense of security by using
881 // critical sections here.
John McCall20bb1752012-05-01 06:13:13 +0000882
Richard Smith04e51762013-04-14 23:01:42 +0000883 if (D.getTLSKind())
884 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
885
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000886 CGBuilderTy &Builder = CGF.Builder;
887 llvm::IntegerType *GuardTy = CGF.Int32Ty;
888 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
889
890 // Get the guard variable for this function if we have one already.
891 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
892
893 unsigned BitIndex;
894 if (D.isExternallyVisible()) {
895 // Externally visible variables have to be numbered in Sema to properly
896 // handle unreachable VarDecls.
897 BitIndex = getContext().getManglingNumber(&D);
898 assert(BitIndex > 0);
899 BitIndex--;
900 } else {
901 // Non-externally visible variables are numbered here in CodeGen.
902 BitIndex = GI.BitIndex++;
903 }
904
905 if (BitIndex >= 32) {
906 if (D.isExternallyVisible())
907 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
908 BitIndex %= 32;
909 GI.Guard = 0;
910 }
911
912 // Lazily create the i32 bitfield for this function.
913 if (!GI.Guard) {
914 // Mangle the name for the guard.
915 SmallString<256> GuardName;
916 {
917 llvm::raw_svector_ostream Out(GuardName);
918 getMangleContext().mangleStaticGuardVariable(&D, Out);
919 Out.flush();
920 }
921
922 // Create the guard variable with a zero-initializer. Just absorb linkage
923 // and visibility from the guarded variable.
924 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
925 GV->getLinkage(), Zero, GuardName.str());
926 GI.Guard->setVisibility(GV->getVisibility());
927 } else {
928 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
929 "static local from the same function had different linkage");
930 }
931
932 // Pseudo code for the test:
933 // if (!(GuardVar & MyGuardBit)) {
934 // GuardVar |= MyGuardBit;
935 // ... initialize the object ...;
936 // }
937
938 // Test our bit from the guard variable.
939 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
940 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
941 llvm::Value *IsInitialized =
942 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
943 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
944 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
945 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
946
947 // Set our bit in the guard variable and emit the initializer and add a global
948 // destructor if appropriate.
949 CGF.EmitBlock(InitBlock);
950 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
951 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
952 Builder.CreateBr(EndBlock);
953
954 // Continue.
955 CGF.EmitBlock(EndBlock);
John McCall20bb1752012-05-01 06:13:13 +0000956}
957
Reid Klecknera3609b02013-04-11 18:13:19 +0000958// Member pointer helpers.
959static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
960 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000961}
962
Reid Klecknerf6327302013-05-09 21:01:17 +0000963static bool hasOnlyOneField(bool IsMemberFunction,
964 MSInheritanceModel Inheritance) {
965 return Inheritance <= MSIM_SinglePolymorphic ||
966 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000967}
968
Reid Klecknera3609b02013-04-11 18:13:19 +0000969// Only member pointers to functions need a this adjustment, since it can be
970// combined with the field offset for data pointers.
Reid Kleckner79e02912013-05-03 01:15:11 +0000971static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Klecknera3609b02013-04-11 18:13:19 +0000972 MSInheritanceModel Inheritance) {
Reid Kleckner79e02912013-05-03 01:15:11 +0000973 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Klecknera3609b02013-04-11 18:13:19 +0000974}
975
976static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
977 return Inheritance >= MSIM_Virtual;
978}
979
980// Use zero for the field offset of a null data member pointer if we can
981// guarantee that zero is not a valid field offset, or if the member pointer has
982// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
983// use zero for null. If there are multiple fields, we can use zero even if it
984// is a valid field offset because null-ness testing will check the other
985// fields.
986static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
987 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
988}
989
990bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
991 // Null-ness for function memptrs only depends on the first field, which is
992 // the function pointer. The rest don't matter, so we can zero initialize.
993 if (MPT->isMemberFunctionPointer())
994 return true;
995
996 // The virtual base adjustment field is always -1 for null, so if we have one
997 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
998 // valid field offset.
999 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1000 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1001 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1002 nullFieldOffsetIsZero(Inheritance));
1003}
1004
1005llvm::Type *
1006MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1007 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1008 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1009 llvm::SmallVector<llvm::Type *, 4> fields;
1010 if (MPT->isMemberFunctionPointer())
1011 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1012 else
1013 fields.push_back(CGM.IntTy); // FieldOffset
1014
Reid Kleckner79e02912013-05-03 01:15:11 +00001015 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1016 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001017 fields.push_back(CGM.IntTy);
Reid Kleckner79e02912013-05-03 01:15:11 +00001018 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001019 fields.push_back(CGM.IntTy);
1020 if (hasVirtualBaseAdjustmentField(Inheritance))
1021 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1022
1023 if (fields.size() == 1)
1024 return fields[0];
1025 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1026}
1027
1028void MicrosoftCXXABI::
1029GetNullMemberPointerFields(const MemberPointerType *MPT,
1030 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1031 assert(fields.empty());
1032 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1033 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1034 if (MPT->isMemberFunctionPointer()) {
1035 // FunctionPointerOrVirtualThunk
1036 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1037 } else {
1038 if (nullFieldOffsetIsZero(Inheritance))
1039 fields.push_back(getZeroInt()); // FieldOffset
1040 else
1041 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +00001042 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001043
Reid Kleckner79e02912013-05-03 01:15:11 +00001044 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1045 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001046 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001047 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001048 fields.push_back(getZeroInt());
1049 if (hasVirtualBaseAdjustmentField(Inheritance))
1050 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001051}
1052
1053llvm::Constant *
1054MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001055 llvm::SmallVector<llvm::Constant *, 4> fields;
1056 GetNullMemberPointerFields(MPT, fields);
1057 if (fields.size() == 1)
1058 return fields[0];
1059 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1060 assert(Res->getType() == ConvertMemberPointerType(MPT));
1061 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001062}
1063
1064llvm::Constant *
Reid Kleckner79e02912013-05-03 01:15:11 +00001065MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1066 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +00001067 const CXXRecordDecl *RD,
1068 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner79e02912013-05-03 01:15:11 +00001069{
Reid Klecknera3609b02013-04-11 18:13:19 +00001070 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner79e02912013-05-03 01:15:11 +00001071
1072 // Single inheritance class member pointer are represented as scalars instead
1073 // of aggregates.
Reid Klecknerf6327302013-05-09 21:01:17 +00001074 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner79e02912013-05-03 01:15:11 +00001075 return FirstField;
1076
Reid Klecknera3609b02013-04-11 18:13:19 +00001077 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner79e02912013-05-03 01:15:11 +00001078 fields.push_back(FirstField);
1079
1080 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Klecknerf6327302013-05-09 21:01:17 +00001081 fields.push_back(llvm::ConstantInt::get(
1082 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner79e02912013-05-03 01:15:11 +00001083
Reid Klecknera3609b02013-04-11 18:13:19 +00001084 if (hasVBPtrOffsetField(Inheritance)) {
Reid Klecknera06d5852013-06-05 15:58:29 +00001085 fields.push_back(llvm::ConstantInt::get(
1086 CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity()));
Reid Klecknera3609b02013-04-11 18:13:19 +00001087 }
Reid Kleckner79e02912013-05-03 01:15:11 +00001088
1089 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Klecknera3609b02013-04-11 18:13:19 +00001090 if (hasVirtualBaseAdjustmentField(Inheritance))
1091 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001092
Reid Klecknera3609b02013-04-11 18:13:19 +00001093 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001094}
1095
Reid Kleckner79e02912013-05-03 01:15:11 +00001096llvm::Constant *
1097MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1098 CharUnits offset) {
1099 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1100 llvm::Constant *FirstField =
1101 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Klecknerf6327302013-05-09 21:01:17 +00001102 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1103 CharUnits::Zero());
1104}
1105
1106llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1107 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1108}
1109
1110llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1111 QualType MPType) {
1112 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1113 const ValueDecl *MPD = MP.getMemberPointerDecl();
1114 if (!MPD)
1115 return EmitNullMemberPointer(MPT);
1116
1117 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1118
1119 // FIXME PR15713: Support virtual inheritance paths.
1120
1121 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1122 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1123 MD, ThisAdjustment);
1124
1125 CharUnits FieldOffset =
1126 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1127 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner79e02912013-05-03 01:15:11 +00001128}
1129
1130llvm::Constant *
Reid Klecknerf6327302013-05-09 21:01:17 +00001131MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1132 const CXXMethodDecl *MD,
1133 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner79e02912013-05-03 01:15:11 +00001134 assert(MD->isInstance() && "Member function must not be static!");
1135 MD = MD->getCanonicalDecl();
Reid Kleckner79e02912013-05-03 01:15:11 +00001136 CodeGenTypes &Types = CGM.getTypes();
1137
1138 llvm::Constant *FirstField;
1139 if (MD->isVirtual()) {
1140 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1141 // the right offset.
1142 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1143 } else {
1144 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1145 llvm::Type *Ty;
1146 // Check whether the function has a computable LLVM signature.
1147 if (Types.isFuncTypeConvertible(FPT)) {
1148 // The function has a computable LLVM signature; use the correct type.
1149 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1150 } else {
1151 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1152 // function type is incomplete.
1153 Ty = CGM.PtrDiffTy;
1154 }
1155 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1156 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1157 }
1158
1159 // The rest of the fields are common with data member pointers.
Reid Klecknerf6327302013-05-09 21:01:17 +00001160 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1161 NonVirtualBaseAdjustment);
Reid Kleckner79e02912013-05-03 01:15:11 +00001162}
1163
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001164/// Member pointers are the same if they're either bitwise identical *or* both
1165/// null. Null-ness for function members is determined by the first field,
1166/// while for data member pointers we must compare all fields.
1167llvm::Value *
1168MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1169 llvm::Value *L,
1170 llvm::Value *R,
1171 const MemberPointerType *MPT,
1172 bool Inequality) {
1173 CGBuilderTy &Builder = CGF.Builder;
1174
1175 // Handle != comparisons by switching the sense of all boolean operations.
1176 llvm::ICmpInst::Predicate Eq;
1177 llvm::Instruction::BinaryOps And, Or;
1178 if (Inequality) {
1179 Eq = llvm::ICmpInst::ICMP_NE;
1180 And = llvm::Instruction::Or;
1181 Or = llvm::Instruction::And;
1182 } else {
1183 Eq = llvm::ICmpInst::ICMP_EQ;
1184 And = llvm::Instruction::And;
1185 Or = llvm::Instruction::Or;
1186 }
1187
1188 // If this is a single field member pointer (single inheritance), this is a
1189 // single icmp.
1190 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1191 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknerf6327302013-05-09 21:01:17 +00001192 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001193 return Builder.CreateICmp(Eq, L, R);
1194
1195 // Compare the first field.
1196 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1197 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1198 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1199
1200 // Compare everything other than the first field.
1201 llvm::Value *Res = 0;
1202 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1203 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1204 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1205 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1206 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1207 if (Res)
1208 Res = Builder.CreateBinOp(And, Res, Cmp);
1209 else
1210 Res = Cmp;
1211 }
1212
1213 // Check if the first field is 0 if this is a function pointer.
1214 if (MPT->isMemberFunctionPointer()) {
1215 // (l1 == r1 && ...) || l0 == 0
1216 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1217 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1218 Res = Builder.CreateBinOp(Or, Res, IsZero);
1219 }
1220
1221 // Combine the comparison of the first field, which must always be true for
1222 // this comparison to succeeed.
1223 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1224}
1225
Reid Klecknera8a0f762013-03-22 19:02:54 +00001226llvm::Value *
1227MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1228 llvm::Value *MemPtr,
1229 const MemberPointerType *MPT) {
1230 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001231 llvm::SmallVector<llvm::Constant *, 4> fields;
1232 // We only need one field for member functions.
1233 if (MPT->isMemberFunctionPointer())
1234 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1235 else
1236 GetNullMemberPointerFields(MPT, fields);
1237 assert(!fields.empty());
1238 llvm::Value *FirstField = MemPtr;
1239 if (MemPtr->getType()->isStructTy())
1240 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1241 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001242
Reid Klecknera3609b02013-04-11 18:13:19 +00001243 // For function member pointers, we only need to test the function pointer
1244 // field. The other fields if any can be garbage.
1245 if (MPT->isMemberFunctionPointer())
1246 return Res;
1247
1248 // Otherwise, emit a series of compares and combine the results.
1249 for (int I = 1, E = fields.size(); I < E; ++I) {
1250 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1251 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1252 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1253 }
1254 return Res;
1255}
1256
Reid Klecknerf6327302013-05-09 21:01:17 +00001257bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1258 llvm::Constant *Val) {
1259 // Function pointers are null if the pointer in the first field is null.
1260 if (MPT->isMemberFunctionPointer()) {
1261 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1262 Val->getAggregateElement(0U) : Val;
1263 return FirstField->isNullValue();
1264 }
1265
1266 // If it's not a function pointer and it's zero initializable, we can easily
1267 // check zero.
1268 if (isZeroInitializable(MPT) && Val->isNullValue())
1269 return true;
1270
1271 // Otherwise, break down all the fields for comparison. Hopefully these
1272 // little Constants are reused, while a big null struct might not be.
1273 llvm::SmallVector<llvm::Constant *, 4> Fields;
1274 GetNullMemberPointerFields(MPT, Fields);
1275 if (Fields.size() == 1) {
1276 assert(Val->getType()->isIntegerTy());
1277 return Val == Fields[0];
1278 }
1279
1280 unsigned I, E;
1281 for (I = 0, E = Fields.size(); I != E; ++I) {
1282 if (Val->getAggregateElement(I) != Fields[I])
1283 break;
1284 }
1285 return I == E;
1286}
1287
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001288llvm::Value *
1289MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1290 llvm::Value *This,
1291 llvm::Value *VBTableOffset,
1292 llvm::Value *VBPtrOffset,
1293 llvm::Value **VBPtrOut) {
1294 CGBuilderTy &Builder = CGF.Builder;
1295 // Load the vbtable pointer from the vbptr in the instance.
1296 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1297 llvm::Value *VBPtr =
1298 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1299 if (VBPtrOut) *VBPtrOut = VBPtr;
1300 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1301 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1302
1303 // Load an i32 offset from the vb-table.
1304 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1305 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1306 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1307}
1308
Reid Klecknera3609b02013-04-11 18:13:19 +00001309// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1310// it.
1311llvm::Value *
1312MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1313 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001314 llvm::Value *VBTableOffset,
Reid Klecknera3609b02013-04-11 18:13:19 +00001315 llvm::Value *VBPtrOffset) {
1316 CGBuilderTy &Builder = CGF.Builder;
1317 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1318 llvm::BasicBlock *OriginalBB = 0;
1319 llvm::BasicBlock *SkipAdjustBB = 0;
1320 llvm::BasicBlock *VBaseAdjustBB = 0;
1321
1322 // In the unspecified inheritance model, there might not be a vbtable at all,
1323 // in which case we need to skip the virtual base lookup. If there is a
1324 // vbtable, the first entry is a no-op entry that gives back the original
1325 // base, so look for a virtual base adjustment offset of zero.
1326 if (VBPtrOffset) {
1327 OriginalBB = Builder.GetInsertBlock();
1328 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1329 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1330 llvm::Value *IsVirtual =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001331 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Klecknera3609b02013-04-11 18:13:19 +00001332 "memptr.is_vbase");
1333 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1334 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001335 }
1336
Reid Klecknera3609b02013-04-11 18:13:19 +00001337 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1338 // know the vbptr offset.
1339 if (!VBPtrOffset) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001340 CharUnits offs = CharUnits::Zero();
1341 if (RD->getNumVBases()) {
1342 offs = GetVBPtrOffsetFromBases(RD);
1343 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001344 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1345 }
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001346 llvm::Value *VBPtr = 0;
Reid Klecknera3609b02013-04-11 18:13:19 +00001347 llvm::Value *VBaseOffs =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001348 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Klecknera3609b02013-04-11 18:13:19 +00001349 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1350
1351 // Merge control flow with the case where we didn't have to adjust.
1352 if (VBaseAdjustBB) {
1353 Builder.CreateBr(SkipAdjustBB);
1354 CGF.EmitBlock(SkipAdjustBB);
1355 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1356 Phi->addIncoming(Base, OriginalBB);
1357 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1358 return Phi;
1359 }
1360 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001361}
1362
1363llvm::Value *
1364MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1365 llvm::Value *Base,
1366 llvm::Value *MemPtr,
1367 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001368 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001369 unsigned AS = Base->getType()->getPointerAddressSpace();
1370 llvm::Type *PType =
1371 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1372 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001373 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1374 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +00001375
Reid Klecknera3609b02013-04-11 18:13:19 +00001376 // Extract the fields we need, regardless of model. We'll apply them if we
1377 // have them.
1378 llvm::Value *FieldOffset = MemPtr;
1379 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1380 llvm::Value *VBPtrOffset = 0;
1381 if (MemPtr->getType()->isStructTy()) {
1382 // We need to extract values.
1383 unsigned I = 0;
1384 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1385 if (hasVBPtrOffsetField(Inheritance))
1386 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1387 if (hasVirtualBaseAdjustmentField(Inheritance))
1388 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001389 }
1390
Reid Klecknera3609b02013-04-11 18:13:19 +00001391 if (VirtualBaseAdjustmentOffset) {
1392 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1393 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001394 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001395 llvm::Value *Addr =
1396 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001397
1398 // Cast the address to the appropriate pointer type, adopting the address
1399 // space of the base pointer.
1400 return Builder.CreateBitCast(Addr, PType);
1401}
1402
Reid Klecknerf6327302013-05-09 21:01:17 +00001403static MSInheritanceModel
1404getInheritanceFromMemptr(const MemberPointerType *MPT) {
1405 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1406}
1407
1408llvm::Value *
1409MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1410 const CastExpr *E,
1411 llvm::Value *Src) {
1412 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1413 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1414 E->getCastKind() == CK_ReinterpretMemberPointer);
1415
1416 // Use constant emission if we can.
1417 if (isa<llvm::Constant>(Src))
1418 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1419
1420 // We may be adding or dropping fields from the member pointer, so we need
1421 // both types and the inheritance models of both records.
1422 const MemberPointerType *SrcTy =
1423 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1424 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1425 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1426 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1427 bool IsFunc = SrcTy->isMemberFunctionPointer();
1428
1429 // If the classes use the same null representation, reinterpret_cast is a nop.
1430 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1431 if (IsReinterpret && (IsFunc ||
1432 nullFieldOffsetIsZero(SrcInheritance) ==
1433 nullFieldOffsetIsZero(DstInheritance)))
1434 return Src;
1435
1436 CGBuilderTy &Builder = CGF.Builder;
1437
1438 // Branch past the conversion if Src is null.
1439 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1440 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1441
1442 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1443 // pointer value of the destination type.
1444 if (IsReinterpret) {
1445 // For reinterpret casts, sema ensures that src and dst are both functions
1446 // or data and have the same size, which means the LLVM types should match.
1447 assert(Src->getType() == DstNull->getType());
1448 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1449 }
1450
1451 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1452 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1453 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1454 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1455 CGF.EmitBlock(ConvertBB);
1456
1457 // Decompose src.
1458 llvm::Value *FirstField = Src;
1459 llvm::Value *NonVirtualBaseAdjustment = 0;
1460 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1461 llvm::Value *VBPtrOffset = 0;
1462 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1463 // We need to extract values.
1464 unsigned I = 0;
1465 FirstField = Builder.CreateExtractValue(Src, I++);
1466 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1467 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1468 if (hasVBPtrOffsetField(SrcInheritance))
1469 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1470 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1471 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1472 }
1473
1474 // For data pointers, we adjust the field offset directly. For functions, we
1475 // have a separate field.
1476 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1477 if (Adj) {
1478 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1479 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1480 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1481 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1482 NVAdjustField = getZeroInt();
1483 if (isDerivedToBase)
1484 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1485 else
1486 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1487 }
1488
1489 // FIXME PR15713: Support conversions through virtually derived classes.
1490
1491 // Recompose dst from the null struct and the adjusted fields from src.
1492 llvm::Value *Dst;
1493 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1494 Dst = FirstField;
1495 } else {
1496 Dst = llvm::UndefValue::get(DstNull->getType());
1497 unsigned Idx = 0;
1498 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1499 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1500 Dst = Builder.CreateInsertValue(
1501 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1502 if (hasVBPtrOffsetField(DstInheritance))
1503 Dst = Builder.CreateInsertValue(
1504 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1505 if (hasVirtualBaseAdjustmentField(DstInheritance))
1506 Dst = Builder.CreateInsertValue(
1507 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1508 }
1509 Builder.CreateBr(ContinueBB);
1510
1511 // In the continuation, choose between DstNull and Dst.
1512 CGF.EmitBlock(ContinueBB);
1513 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1514 Phi->addIncoming(DstNull, OriginalBB);
1515 Phi->addIncoming(Dst, ConvertBB);
1516 return Phi;
1517}
1518
1519llvm::Constant *
1520MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1521 llvm::Constant *Src) {
1522 const MemberPointerType *SrcTy =
1523 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1524 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1525
1526 // If src is null, emit a new null for dst. We can't return src because dst
1527 // might have a new representation.
1528 if (MemberPointerConstantIsNull(SrcTy, Src))
1529 return EmitNullMemberPointer(DstTy);
1530
1531 // We don't need to do anything for reinterpret_casts of non-null member
1532 // pointers. We should only get here when the two type representations have
1533 // the same size.
1534 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1535 return Src;
1536
1537 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1538 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1539
1540 // Decompose src.
1541 llvm::Constant *FirstField = Src;
1542 llvm::Constant *NonVirtualBaseAdjustment = 0;
1543 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1544 llvm::Constant *VBPtrOffset = 0;
1545 bool IsFunc = SrcTy->isMemberFunctionPointer();
1546 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1547 // We need to extract values.
1548 unsigned I = 0;
1549 FirstField = Src->getAggregateElement(I++);
1550 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1551 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1552 if (hasVBPtrOffsetField(SrcInheritance))
1553 VBPtrOffset = Src->getAggregateElement(I++);
1554 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1555 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1556 }
1557
1558 // For data pointers, we adjust the field offset directly. For functions, we
1559 // have a separate field.
1560 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1561 if (Adj) {
1562 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1563 llvm::Constant *&NVAdjustField =
1564 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1565 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1566 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1567 NVAdjustField = getZeroInt();
1568 if (IsDerivedToBase)
1569 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1570 else
1571 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1572 }
1573
1574 // FIXME PR15713: Support conversions through virtually derived classes.
1575
1576 // Recompose dst from the null struct and the adjusted fields from src.
1577 if (hasOnlyOneField(IsFunc, DstInheritance))
1578 return FirstField;
1579
1580 llvm::SmallVector<llvm::Constant *, 4> Fields;
1581 Fields.push_back(FirstField);
1582 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1583 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1584 if (hasVBPtrOffsetField(DstInheritance))
1585 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1586 if (hasVirtualBaseAdjustmentField(DstInheritance))
1587 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1588 return llvm::ConstantStruct::getAnon(Fields);
1589}
1590
Reid Klecknera3609b02013-04-11 18:13:19 +00001591llvm::Value *
1592MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1593 llvm::Value *&This,
1594 llvm::Value *MemPtr,
1595 const MemberPointerType *MPT) {
1596 assert(MPT->isMemberFunctionPointer());
1597 const FunctionProtoType *FPT =
1598 MPT->getPointeeType()->castAs<FunctionProtoType>();
1599 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1600 llvm::FunctionType *FTy =
1601 CGM.getTypes().GetFunctionType(
1602 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1603 CGBuilderTy &Builder = CGF.Builder;
1604
1605 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1606
1607 // Extract the fields we need, regardless of model. We'll apply them if we
1608 // have them.
1609 llvm::Value *FunctionPointer = MemPtr;
1610 llvm::Value *NonVirtualBaseAdjustment = NULL;
1611 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1612 llvm::Value *VBPtrOffset = NULL;
1613 if (MemPtr->getType()->isStructTy()) {
1614 // We need to extract values.
1615 unsigned I = 0;
1616 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001617 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1618 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner79e02912013-05-03 01:15:11 +00001619 if (hasVBPtrOffsetField(Inheritance))
1620 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001621 if (hasVirtualBaseAdjustmentField(Inheritance))
1622 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1623 }
1624
1625 if (VirtualBaseAdjustmentOffset) {
1626 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1627 VBPtrOffset);
1628 }
1629
1630 if (NonVirtualBaseAdjustment) {
1631 // Apply the adjustment and cast back to the original struct type.
1632 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1633 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1634 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1635 }
1636
1637 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1638}
1639
Charles Davis071cc7d2010-08-16 03:33:14 +00001640CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +00001641 return new MicrosoftCXXABI(CGM);
1642}
1643