blob: e5d7c49a64298cef5c6dc2f07b33ab26bf5fb96a [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"
Charles Davisc3926642010-06-09 23:25:41 +000024
25using namespace clang;
26using namespace CodeGen;
27
28namespace {
29
Charles Davis071cc7d2010-08-16 03:33:14 +000030class MicrosoftCXXABI : public CGCXXABI {
Charles Davisc3926642010-06-09 23:25:41 +000031public:
Peter Collingbourne14110472011-01-13 18:57:25 +000032 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall4c40d982010-08-31 07:33:07 +000033
Stephen Lin3b50e8d2013-06-30 20:40:16 +000034 bool HasThisReturn(GlobalDecl GD) const;
35
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000036 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
37 // Structures that are not C++03 PODs are always indirect.
38 return !RD->isPOD();
39 }
40
41 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner9b601952013-06-21 12:45:15 +000042 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000043 return RAA_DirectInMemory;
44 return RAA_Default;
45 }
46
Joao Matos285baac2012-07-17 17:10:11 +000047 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikie2eb9a952012-10-16 22:56:05 +000048 // No known support for deleted functions in MSVC yet, so this choice is
49 // arbitrary.
50 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos285baac2012-07-17 17:10:11 +000051
John McCallecd03b42012-09-25 10:10:39 +000052 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
53 llvm::Value *ptr,
54 QualType type);
55
Reid Klecknerb0f533e2013-05-29 18:02:47 +000056 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
57 llvm::Value *This,
58 const CXXRecordDecl *ClassDecl,
59 const CXXRecordDecl *BaseClassDecl);
60
John McCall4c40d982010-08-31 07:33:07 +000061 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
62 CXXCtorType Type,
63 CanQualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +000064 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +000065
Reid Kleckner90633022013-06-19 15:20:38 +000066 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
67 const CXXRecordDecl *RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000068
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +000069 void EmitCXXConstructors(const CXXConstructorDecl *D);
70
Reid Klecknera4130ba2013-07-22 13:51:44 +000071 // Background on MSVC destructors
72 // ==============================
73 //
74 // Both Itanium and MSVC ABIs have destructor variants. The variant names
75 // roughly correspond in the following way:
76 // Itanium Microsoft
77 // Base -> no name, just ~Class
78 // Complete -> vbase destructor
79 // Deleting -> scalar deleting destructor
80 // vector deleting destructor
81 //
82 // The base and complete destructors are the same as in Itanium, although the
83 // complete destructor does not accept a VTT parameter when there are virtual
84 // bases. A separate mechanism involving vtordisps is used to ensure that
85 // virtual methods of destroyed subobjects are not called.
86 //
87 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
88 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
89 // pointer points to an array. The scalar deleting destructor assumes that
90 // bit 2 is zero, and therefore does not contain a loop.
91 //
92 // For virtual destructors, only one entry is reserved in the vftable, and it
93 // always points to the vector deleting destructor. The vector deleting
94 // destructor is the most general, so it can be used to destroy objects in
95 // place, delete single heap objects, or delete arrays.
96 //
97 // A TU defining a non-inline destructor is only guaranteed to emit a base
98 // destructor, and all of the other variants are emitted on an as-needed basis
99 // in COMDATs. Because a non-base destructor can be emitted in a TU that
100 // lacks a definition for the destructor, non-base destructors must always
101 // delegate to or alias the base destructor.
102
103 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall4c40d982010-08-31 07:33:07 +0000104 CXXDtorType Type,
105 CanQualType &ResTy,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000106 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000107
Reid Klecknera4130ba2013-07-22 13:51:44 +0000108 /// Non-base dtors should be emitted as delegating thunks in this ABI.
109 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
110 CXXDtorType DT) const {
111 return DT != Dtor_Base;
112 }
113
114 void EmitCXXDestructors(const CXXDestructorDecl *D);
115
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000116 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
117 MD = MD->getCanonicalDecl();
118 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
119 MicrosoftVFTableContext::MethodVFTableLocation ML =
120 CGM.getVFTableContext().getMethodVFTableLocation(MD);
121 // The vbases might be ordered differently in the final overrider object
122 // and the complete object, so the "this" argument may sometimes point to
123 // memory that has no particular type (e.g. past the complete object).
124 // In this case, we just use a generic pointer type.
125 // FIXME: might want to have a more precise type in the non-virtual
126 // multiple inheritance case.
127 if (ML.VBase || !ML.VFTableOffset.isZero())
128 return 0;
129 }
130 return MD->getParent();
131 }
132
133 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
134 GlobalDecl GD,
135 llvm::Value *This);
136
John McCall4c40d982010-08-31 07:33:07 +0000137 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
138 QualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +0000139 FunctionArgList &Params);
John McCall4c40d982010-08-31 07:33:07 +0000140
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000141 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
142 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
143
John McCallbd315742012-09-25 08:00:39 +0000144 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCallfd708262011-01-27 02:46:02 +0000145
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000146 void EmitConstructorCall(CodeGenFunction &CGF,
147 const CXXConstructorDecl *D, CXXCtorType Type,
148 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000149 llvm::Value *This,
150 CallExpr::const_arg_iterator ArgBeg,
151 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000152
153 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
154 llvm::Value *This, llvm::Type *Ty);
155
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000156 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
157 const CXXDestructorDecl *Dtor,
158 CXXDtorType DtorType, SourceLocation CallLoc,
159 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000160
Reid Kleckner90633022013-06-19 15:20:38 +0000161 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
162 const CXXRecordDecl *RD);
163
John McCall20bb1752012-05-01 06:13:13 +0000164 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
165 llvm::GlobalVariable *DeclPtr,
166 bool PerformInit);
167
John McCallfd708262011-01-27 02:46:02 +0000168 // ==== Notes on array cookies =========
169 //
170 // MSVC seems to only use cookies when the class has a destructor; a
171 // two-argument usual array deallocation function isn't sufficient.
172 //
173 // For example, this code prints "100" and "1":
174 // struct A {
175 // char x;
176 // void *operator new[](size_t sz) {
177 // printf("%u\n", sz);
178 // return malloc(sz);
179 // }
180 // void operator delete[](void *p, size_t sz) {
181 // printf("%u\n", sz);
182 // free(p);
183 // }
184 // };
185 // int main() {
186 // A *p = new A[100];
187 // delete[] p;
188 // }
189 // Whereas it prints "104" and "104" if you give A a destructor.
John McCalle2b45e22012-05-01 05:23:51 +0000190
191 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
192 bool requiresArrayCookie(const CXXNewExpr *expr);
193 CharUnits getArrayCookieSizeImpl(QualType type);
194 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
195 llvm::Value *NewPtr,
196 llvm::Value *NumElements,
197 const CXXNewExpr *expr,
198 QualType ElementType);
199 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
200 llvm::Value *allocPtr,
201 CharUnits cookieSize);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000202
203private:
Reid Klecknera3609b02013-04-11 18:13:19 +0000204 llvm::Constant *getZeroInt() {
205 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000206 }
207
Reid Klecknera3609b02013-04-11 18:13:19 +0000208 llvm::Constant *getAllOnesInt() {
209 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000210 }
211
Reid Klecknerf6327302013-05-09 21:01:17 +0000212 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
213 return C ? C : getZeroInt();
214 }
215
216 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
217 return C ? C : getZeroInt();
218 }
219
Reid Klecknera3609b02013-04-11 18:13:19 +0000220 void
221 GetNullMemberPointerFields(const MemberPointerType *MPT,
222 llvm::SmallVectorImpl<llvm::Constant *> &fields);
223
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000224 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
225 /// it is reusing a vbptr from a non-virtual base. RD must have morally
226 /// virtual bases.
227 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
228
229 /// \brief Shared code for virtual base adjustment. Returns the offset from
230 /// the vbptr to the virtual base. Optionally returns the address of the
231 /// vbptr itself.
232 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
233 llvm::Value *Base,
234 llvm::Value *VBPtrOffset,
235 llvm::Value *VBTableOffset,
236 llvm::Value **VBPtr = 0);
237
238 /// \brief Performs a full virtual base adjustment. Used to dereference
239 /// pointers to members of virtual bases.
Reid Klecknera3609b02013-04-11 18:13:19 +0000240 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
241 llvm::Value *Base,
242 llvm::Value *VirtualBaseAdjustmentOffset,
243 llvm::Value *VBPtrOffset /* optional */);
244
Reid Kleckner79e02912013-05-03 01:15:11 +0000245 /// \brief Emits a full member pointer with the fields common to data and
246 /// function member pointers.
247 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
248 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000249 const CXXRecordDecl *RD,
250 CharUnits NonVirtualBaseAdjustment);
251
252 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
253 const CXXMethodDecl *MD,
254 CharUnits NonVirtualBaseAdjustment);
255
256 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
257 llvm::Constant *MP);
Reid Kleckner79e02912013-05-03 01:15:11 +0000258
Reid Kleckner90633022013-06-19 15:20:38 +0000259 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
260 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
261
262 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
263 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
264
Reid Klecknera8a0f762013-03-22 19:02:54 +0000265public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000266 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
267
268 virtual bool isZeroInitializable(const MemberPointerType *MPT);
269
Reid Klecknera8a0f762013-03-22 19:02:54 +0000270 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
271
272 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
273 CharUnits offset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000274 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
275 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000276
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000277 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
278 llvm::Value *L,
279 llvm::Value *R,
280 const MemberPointerType *MPT,
281 bool Inequality);
282
Reid Klecknera8a0f762013-03-22 19:02:54 +0000283 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
284 llvm::Value *MemPtr,
285 const MemberPointerType *MPT);
286
287 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
288 llvm::Value *Base,
289 llvm::Value *MemPtr,
290 const MemberPointerType *MPT);
291
Reid Klecknerf6327302013-05-09 21:01:17 +0000292 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
293 const CastExpr *E,
294 llvm::Value *Src);
295
296 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
297 llvm::Constant *Src);
298
Reid Klecknera3609b02013-04-11 18:13:19 +0000299 virtual llvm::Value *
300 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
301 llvm::Value *&This,
302 llvm::Value *MemPtr,
303 const MemberPointerType *MPT);
304
Reid Kleckner90633022013-06-19 15:20:38 +0000305private:
306 /// VBTables - All the vbtables which have been referenced.
307 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000308
309 /// Info on the global variable used to guard initialization of static locals.
310 /// The BitIndex field is only used for externally invisible declarations.
311 struct GuardInfo {
312 GuardInfo() : Guard(0), BitIndex(0) {}
313 llvm::GlobalVariable *Guard;
314 unsigned BitIndex;
315 };
316
317 /// Map from DeclContext to the current guard variable. We assume that the
318 /// AST is visited in source code order.
319 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davisc3926642010-06-09 23:25:41 +0000320};
321
322}
323
John McCallecd03b42012-09-25 10:10:39 +0000324llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
325 llvm::Value *ptr,
326 QualType type) {
327 // FIXME: implement
328 return ptr;
329}
330
Reid Kleckner8c474322013-06-04 21:32:29 +0000331/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
332/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
333static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
334 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
335 E = RD->bases_end(); I != E; ++I) {
336 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
337 if (!I->isVirtual() && Base->getNumVBases() > 0)
338 return Base;
339 }
340 llvm_unreachable("RD must have an nv base with vbases");
341}
342
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000343CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
344 assert(RD->getNumVBases());
345 CharUnits Total = CharUnits::Zero();
346 while (RD) {
347 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
348 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
349 // -1 is the sentinel for no vbptr.
350 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
351 Total += VBPtrOffset;
352 break;
353 }
Reid Kleckner8c474322013-06-04 21:32:29 +0000354 RD = FindFirstNVBaseWithVBases(RD);
355 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000356 }
357 return Total;
358}
359
360llvm::Value *
361MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
362 llvm::Value *This,
363 const CXXRecordDecl *ClassDecl,
364 const CXXRecordDecl *BaseClassDecl) {
365 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
366 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000367 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner8c474322013-06-04 21:32:29 +0000368 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000369 llvm::Value *VBTableOffset =
370 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
371
372 llvm::Value *VBPtrToNewBase =
373 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
374 VBPtrToNewBase =
375 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
376 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
377}
378
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000379bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
380 return isa<CXXConstructorDecl>(GD.getDecl());
John McCallbd315742012-09-25 08:00:39 +0000381}
382
383void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
384 CXXCtorType Type,
385 CanQualType &ResTy,
386 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000387 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000388
389 const CXXRecordDecl *Class = Ctor->getParent();
390 if (Class->getNumVBases()) {
391 // Constructors of classes with virtual bases take an implicit parameter.
392 ArgTys.push_back(CGM.getContext().IntTy);
393 }
394}
395
Reid Kleckner90633022013-06-19 15:20:38 +0000396llvm::BasicBlock *
397MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
398 const CXXRecordDecl *RD) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000399 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
400 assert(IsMostDerivedClass &&
401 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner90633022013-06-19 15:20:38 +0000402 llvm::Value *IsCompleteObject =
403 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000404
405 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
406 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
407 CGF.Builder.CreateCondBr(IsCompleteObject,
408 CallVbaseCtorsBB, SkipVbaseCtorsBB);
409
410 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner90633022013-06-19 15:20:38 +0000411
412 // Fill in the vbtable pointers here.
413 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000414
415 // CGF will put the base ctor calls in this basic block for us later.
416
417 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000418}
419
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000420void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
421 // There's only one constructor type in this ABI.
422 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
423}
424
Reid Kleckner90633022013-06-19 15:20:38 +0000425void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
426 const CXXRecordDecl *RD) {
427 llvm::Value *ThisInt8Ptr =
428 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
429
430 const VBTableVector &VBTables = EnumerateVBTables(RD);
431 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
432 I != E; ++I) {
433 const ASTRecordLayout &SubobjectLayout =
434 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
435 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
436 SubobjectLayout.getVBPtrOffset()).getQuantity();
437 llvm::Value *VBPtr =
438 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
439 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
440 "vbptr." + I->ReusingBase->getName());
441 CGF.Builder.CreateStore(I->GV, VBPtr);
442 }
443}
444
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000445void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
446 CXXDtorType Type,
447 CanQualType &ResTy,
448 SmallVectorImpl<CanQualType> &ArgTys) {
449 // 'this' is already in place
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000450
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000451 // TODO: 'for base' flag
452
453 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000454 // The scalar deleting destructor takes an implicit int parameter.
455 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000456 }
457}
458
Reid Klecknera4130ba2013-07-22 13:51:44 +0000459void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
460 // The TU defining a dtor is only guaranteed to emit a base destructor. All
461 // other destructor variants are delegating thunks.
462 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
463}
464
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000465llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
466 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
467 GD = GD.getCanonicalDecl();
468 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
469 if (isa<CXXDestructorDecl>(MD))
470 return This;
471
472 MicrosoftVFTableContext::MethodVFTableLocation ML =
473 CGM.getVFTableContext().getMethodVFTableLocation(GD);
474
475 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
476 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
477 if (ML.VBase) {
478 This = CGF.Builder.CreateBitCast(This, charPtrTy);
479 llvm::Value *VBaseOffset = CGM.getCXXABI()
480 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
481 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
482 }
483 CharUnits StaticOffset = ML.VFTableOffset;
484 if (!StaticOffset.isZero()) {
485 assert(StaticOffset.isPositive());
486 This = CGF.Builder.CreateBitCast(This, charPtrTy);
487 This = CGF.Builder
488 .CreateConstInBoundsGEP1_64(This, StaticOffset.getQuantity());
489 }
490 return This;
491}
492
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000493static bool IsDeletingDtor(GlobalDecl GD) {
494 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
495 if (isa<CXXDestructorDecl>(MD)) {
496 return GD.getDtorType() == Dtor_Deleting;
497 }
498 return false;
499}
500
John McCallbd315742012-09-25 08:00:39 +0000501void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
502 QualType &ResTy,
503 FunctionArgList &Params) {
504 BuildThisParam(CGF, Params);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000505
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000506 ASTContext &Context = getContext();
507 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
508 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
509 ImplicitParamDecl *IsMostDerived
510 = ImplicitParamDecl::Create(Context, 0,
511 CGF.CurGD.getDecl()->getLocation(),
512 &Context.Idents.get("is_most_derived"),
513 Context.IntTy);
514 Params.push_back(IsMostDerived);
515 getStructorImplicitParamDecl(CGF) = IsMostDerived;
516 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000517 ImplicitParamDecl *ShouldDelete
518 = ImplicitParamDecl::Create(Context, 0,
519 CGF.CurGD.getDecl()->getLocation(),
520 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000521 Context.IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000522 Params.push_back(ShouldDelete);
523 getStructorImplicitParamDecl(CGF) = ShouldDelete;
524 }
John McCallbd315742012-09-25 08:00:39 +0000525}
526
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000527llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
528 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
529 GD = GD.getCanonicalDecl();
530 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
531 if (isa<CXXDestructorDecl>(MD))
532 return This;
533
534 // In this ABI, every virtual function takes a pointer to one of the
535 // subobjects that first defines it as the 'this' parameter, rather than a
536 // pointer to ther final overrider subobject. Thus, we need to adjust it back
537 // to the final overrider subobject before use.
538 // See comments in the MicrosoftVFTableContext implementation for the details.
539
540 MicrosoftVFTableContext::MethodVFTableLocation ML =
541 CGM.getVFTableContext().getMethodVFTableLocation(GD);
542 CharUnits Adjustment = ML.VFTableOffset;
543 if (ML.VBase) {
544 const ASTRecordLayout &DerivedLayout =
545 CGF.getContext().getASTRecordLayout(MD->getParent());
546 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
547 }
548
549 if (Adjustment.isZero())
550 return This;
551
552 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
553 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
554 *thisTy = This->getType();
555
556 This = CGF.Builder.CreateBitCast(This, charPtrTy);
557 assert(Adjustment.isPositive());
558 This = CGF.Builder.CreateConstGEP1_64(This, -Adjustment.getQuantity());
559 return CGF.Builder.CreateBitCast(This, thisTy);
560}
561
John McCallbd315742012-09-25 08:00:39 +0000562void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
563 EmitThisParam(CGF);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000564
565 /// If this is a function that the ABI specifies returns 'this', initialize
566 /// the return slot to 'this' at the start of the function.
567 ///
568 /// Unlike the setting of return types, this is done within the ABI
569 /// implementation instead of by clients of CGCXXABI because:
570 /// 1) getThisValue is currently protected
571 /// 2) in theory, an ABI could implement 'this' returns some other way;
572 /// HasThisReturn only specifies a contract, not the implementation
573 if (HasThisReturn(CGF.CurGD))
John McCallbd315742012-09-25 08:00:39 +0000574 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000575
576 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
577 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
578 assert(getStructorImplicitParamDecl(CGF) &&
579 "no implicit parameter for a constructor with virtual bases?");
580 getStructorImplicitParamValue(CGF)
581 = CGF.Builder.CreateLoad(
582 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
583 "is_most_derived");
584 }
585
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000586 if (IsDeletingDtor(CGF.CurGD)) {
587 assert(getStructorImplicitParamDecl(CGF) &&
588 "no implicit parameter for a deleting destructor?");
589 getStructorImplicitParamValue(CGF)
590 = CGF.Builder.CreateLoad(
591 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
592 "should_call_delete");
593 }
John McCallbd315742012-09-25 08:00:39 +0000594}
595
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000596void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000597 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000598 CXXCtorType Type,
599 bool ForVirtualBase,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000600 bool Delegating,
601 llvm::Value *This,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000602 CallExpr::const_arg_iterator ArgBeg,
603 CallExpr::const_arg_iterator ArgEnd) {
604 assert(Type == Ctor_Complete || Type == Ctor_Base);
605 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
606
607 llvm::Value *ImplicitParam = 0;
608 QualType ImplicitParamTy;
609 if (D->getParent()->getNumVBases()) {
610 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
611 ImplicitParamTy = getContext().IntTy;
612 }
613
614 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000615 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000616 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000617}
618
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000619llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
620 GlobalDecl GD,
621 llvm::Value *This,
622 llvm::Type *Ty) {
623 GD = GD.getCanonicalDecl();
624 CGBuilderTy &Builder = CGF.Builder;
625
626 Ty = Ty->getPointerTo()->getPointerTo();
627 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
628 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
629
630 MicrosoftVFTableContext::MethodVFTableLocation ML =
631 CGM.getVFTableContext().getMethodVFTableLocation(GD);
632 llvm::Value *VFuncPtr =
633 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
634 return Builder.CreateLoad(VFuncPtr);
635}
636
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000637void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
638 const CXXDestructorDecl *Dtor,
639 CXXDtorType DtorType,
640 SourceLocation CallLoc,
641 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000642 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
643
644 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000645 // by passing an implicit int parameter.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000646 const CGFunctionInfo *FInfo =
647 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000648 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000649 llvm::Value *Callee =
650 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, Dtor_Deleting), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000651
652 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000653 llvm::Value *ImplicitParam =
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000654 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000655 DtorType == Dtor_Deleting);
656
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000657 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000658 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000659}
660
Reid Kleckner90633022013-06-19 15:20:38 +0000661const VBTableVector &
662MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
663 // At this layer, we can key the cache off of a single class, which is much
664 // easier than caching at the GlobalVariable layer.
665 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
666 bool added;
667 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
668 VBTableVector &VBTables = I->second;
669 if (!added)
670 return VBTables;
671
672 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
673
674 return VBTables;
675}
676
677void MicrosoftCXXABI::EmitVirtualInheritanceTables(
678 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
679 const VBTableVector &VBTables = EnumerateVBTables(RD);
680 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
681 I != E; ++I) {
682 I->EmitVBTableDefinition(CGM, RD, Linkage);
683 }
684}
685
John McCalle2b45e22012-05-01 05:23:51 +0000686bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
687 QualType elementType) {
688 // Microsoft seems to completely ignore the possibility of a
689 // two-argument usual deallocation function.
690 return elementType.isDestructedType();
691}
692
693bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
694 // Microsoft seems to completely ignore the possibility of a
695 // two-argument usual deallocation function.
696 return expr->getAllocatedType().isDestructedType();
697}
698
699CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
700 // The array cookie is always a size_t; we then pad that out to the
701 // alignment of the element type.
702 ASTContext &Ctx = getContext();
703 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
704 Ctx.getTypeAlignInChars(type));
705}
706
707llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
708 llvm::Value *allocPtr,
709 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +0000710 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000711 llvm::Value *numElementsPtr =
712 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
713 return CGF.Builder.CreateLoad(numElementsPtr);
714}
715
716llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
717 llvm::Value *newPtr,
718 llvm::Value *numElements,
719 const CXXNewExpr *expr,
720 QualType elementType) {
721 assert(requiresArrayCookie(expr));
722
723 // The size of the cookie.
724 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
725
726 // Compute an offset to the cookie.
727 llvm::Value *cookiePtr = newPtr;
728
729 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +0000730 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000731 llvm::Value *numElementsPtr
732 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
733 CGF.Builder.CreateStore(numElements, numElementsPtr);
734
735 // Finally, compute a pointer to the actual data buffer by skipping
736 // over the cookie completely.
737 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
738 cookieSize.getQuantity());
739}
740
John McCall20bb1752012-05-01 06:13:13 +0000741void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000742 llvm::GlobalVariable *GV,
John McCall20bb1752012-05-01 06:13:13 +0000743 bool PerformInit) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000744 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
745 // threadsafe. Since the user may be linking in inline functions compiled by
746 // cl.exe, there's no reason to provide a false sense of security by using
747 // critical sections here.
John McCall20bb1752012-05-01 06:13:13 +0000748
Richard Smith04e51762013-04-14 23:01:42 +0000749 if (D.getTLSKind())
750 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
751
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000752 CGBuilderTy &Builder = CGF.Builder;
753 llvm::IntegerType *GuardTy = CGF.Int32Ty;
754 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
755
756 // Get the guard variable for this function if we have one already.
757 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
758
759 unsigned BitIndex;
760 if (D.isExternallyVisible()) {
761 // Externally visible variables have to be numbered in Sema to properly
762 // handle unreachable VarDecls.
763 BitIndex = getContext().getManglingNumber(&D);
764 assert(BitIndex > 0);
765 BitIndex--;
766 } else {
767 // Non-externally visible variables are numbered here in CodeGen.
768 BitIndex = GI.BitIndex++;
769 }
770
771 if (BitIndex >= 32) {
772 if (D.isExternallyVisible())
773 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
774 BitIndex %= 32;
775 GI.Guard = 0;
776 }
777
778 // Lazily create the i32 bitfield for this function.
779 if (!GI.Guard) {
780 // Mangle the name for the guard.
781 SmallString<256> GuardName;
782 {
783 llvm::raw_svector_ostream Out(GuardName);
784 getMangleContext().mangleStaticGuardVariable(&D, Out);
785 Out.flush();
786 }
787
788 // Create the guard variable with a zero-initializer. Just absorb linkage
789 // and visibility from the guarded variable.
790 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
791 GV->getLinkage(), Zero, GuardName.str());
792 GI.Guard->setVisibility(GV->getVisibility());
793 } else {
794 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
795 "static local from the same function had different linkage");
796 }
797
798 // Pseudo code for the test:
799 // if (!(GuardVar & MyGuardBit)) {
800 // GuardVar |= MyGuardBit;
801 // ... initialize the object ...;
802 // }
803
804 // Test our bit from the guard variable.
805 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
806 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
807 llvm::Value *IsInitialized =
808 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
809 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
810 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
811 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
812
813 // Set our bit in the guard variable and emit the initializer and add a global
814 // destructor if appropriate.
815 CGF.EmitBlock(InitBlock);
816 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
817 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
818 Builder.CreateBr(EndBlock);
819
820 // Continue.
821 CGF.EmitBlock(EndBlock);
John McCall20bb1752012-05-01 06:13:13 +0000822}
823
Reid Klecknera3609b02013-04-11 18:13:19 +0000824// Member pointer helpers.
825static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
826 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000827}
828
Reid Klecknerf6327302013-05-09 21:01:17 +0000829static bool hasOnlyOneField(bool IsMemberFunction,
830 MSInheritanceModel Inheritance) {
831 return Inheritance <= MSIM_SinglePolymorphic ||
832 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000833}
834
Reid Klecknera3609b02013-04-11 18:13:19 +0000835// Only member pointers to functions need a this adjustment, since it can be
836// combined with the field offset for data pointers.
Reid Kleckner79e02912013-05-03 01:15:11 +0000837static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Klecknera3609b02013-04-11 18:13:19 +0000838 MSInheritanceModel Inheritance) {
Reid Kleckner79e02912013-05-03 01:15:11 +0000839 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Klecknera3609b02013-04-11 18:13:19 +0000840}
841
842static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
843 return Inheritance >= MSIM_Virtual;
844}
845
846// Use zero for the field offset of a null data member pointer if we can
847// guarantee that zero is not a valid field offset, or if the member pointer has
848// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
849// use zero for null. If there are multiple fields, we can use zero even if it
850// is a valid field offset because null-ness testing will check the other
851// fields.
852static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
853 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
854}
855
856bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
857 // Null-ness for function memptrs only depends on the first field, which is
858 // the function pointer. The rest don't matter, so we can zero initialize.
859 if (MPT->isMemberFunctionPointer())
860 return true;
861
862 // The virtual base adjustment field is always -1 for null, so if we have one
863 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
864 // valid field offset.
865 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
866 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
867 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
868 nullFieldOffsetIsZero(Inheritance));
869}
870
871llvm::Type *
872MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
873 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
874 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
875 llvm::SmallVector<llvm::Type *, 4> fields;
876 if (MPT->isMemberFunctionPointer())
877 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
878 else
879 fields.push_back(CGM.IntTy); // FieldOffset
880
Reid Kleckner79e02912013-05-03 01:15:11 +0000881 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
882 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000883 fields.push_back(CGM.IntTy);
Reid Kleckner79e02912013-05-03 01:15:11 +0000884 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000885 fields.push_back(CGM.IntTy);
886 if (hasVirtualBaseAdjustmentField(Inheritance))
887 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
888
889 if (fields.size() == 1)
890 return fields[0];
891 return llvm::StructType::get(CGM.getLLVMContext(), fields);
892}
893
894void MicrosoftCXXABI::
895GetNullMemberPointerFields(const MemberPointerType *MPT,
896 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
897 assert(fields.empty());
898 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
899 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
900 if (MPT->isMemberFunctionPointer()) {
901 // FunctionPointerOrVirtualThunk
902 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
903 } else {
904 if (nullFieldOffsetIsZero(Inheritance))
905 fields.push_back(getZeroInt()); // FieldOffset
906 else
907 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +0000908 }
Reid Klecknera3609b02013-04-11 18:13:19 +0000909
Reid Kleckner79e02912013-05-03 01:15:11 +0000910 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
911 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000912 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +0000913 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000914 fields.push_back(getZeroInt());
915 if (hasVirtualBaseAdjustmentField(Inheritance))
916 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +0000917}
918
919llvm::Constant *
920MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +0000921 llvm::SmallVector<llvm::Constant *, 4> fields;
922 GetNullMemberPointerFields(MPT, fields);
923 if (fields.size() == 1)
924 return fields[0];
925 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
926 assert(Res->getType() == ConvertMemberPointerType(MPT));
927 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000928}
929
930llvm::Constant *
Reid Kleckner79e02912013-05-03 01:15:11 +0000931MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
932 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000933 const CXXRecordDecl *RD,
934 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner79e02912013-05-03 01:15:11 +0000935{
Reid Klecknera3609b02013-04-11 18:13:19 +0000936 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner79e02912013-05-03 01:15:11 +0000937
938 // Single inheritance class member pointer are represented as scalars instead
939 // of aggregates.
Reid Klecknerf6327302013-05-09 21:01:17 +0000940 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner79e02912013-05-03 01:15:11 +0000941 return FirstField;
942
Reid Klecknera3609b02013-04-11 18:13:19 +0000943 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner79e02912013-05-03 01:15:11 +0000944 fields.push_back(FirstField);
945
946 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Klecknerf6327302013-05-09 21:01:17 +0000947 fields.push_back(llvm::ConstantInt::get(
948 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner79e02912013-05-03 01:15:11 +0000949
Reid Klecknera3609b02013-04-11 18:13:19 +0000950 if (hasVBPtrOffsetField(Inheritance)) {
Reid Klecknera06d5852013-06-05 15:58:29 +0000951 fields.push_back(llvm::ConstantInt::get(
952 CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity()));
Reid Klecknera3609b02013-04-11 18:13:19 +0000953 }
Reid Kleckner79e02912013-05-03 01:15:11 +0000954
955 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Klecknera3609b02013-04-11 18:13:19 +0000956 if (hasVirtualBaseAdjustmentField(Inheritance))
957 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +0000958
Reid Klecknera3609b02013-04-11 18:13:19 +0000959 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000960}
961
Reid Kleckner79e02912013-05-03 01:15:11 +0000962llvm::Constant *
963MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
964 CharUnits offset) {
965 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
966 llvm::Constant *FirstField =
967 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Klecknerf6327302013-05-09 21:01:17 +0000968 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
969 CharUnits::Zero());
970}
971
972llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
973 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
974}
975
976llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
977 QualType MPType) {
978 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
979 const ValueDecl *MPD = MP.getMemberPointerDecl();
980 if (!MPD)
981 return EmitNullMemberPointer(MPT);
982
983 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
984
985 // FIXME PR15713: Support virtual inheritance paths.
986
987 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
988 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
989 MD, ThisAdjustment);
990
991 CharUnits FieldOffset =
992 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
993 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000994}
995
996llvm::Constant *
Reid Klecknerf6327302013-05-09 21:01:17 +0000997MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
998 const CXXMethodDecl *MD,
999 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner79e02912013-05-03 01:15:11 +00001000 assert(MD->isInstance() && "Member function must not be static!");
1001 MD = MD->getCanonicalDecl();
Reid Kleckner79e02912013-05-03 01:15:11 +00001002 CodeGenTypes &Types = CGM.getTypes();
1003
1004 llvm::Constant *FirstField;
1005 if (MD->isVirtual()) {
1006 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1007 // the right offset.
1008 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1009 } else {
1010 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1011 llvm::Type *Ty;
1012 // Check whether the function has a computable LLVM signature.
1013 if (Types.isFuncTypeConvertible(FPT)) {
1014 // The function has a computable LLVM signature; use the correct type.
1015 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1016 } else {
1017 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1018 // function type is incomplete.
1019 Ty = CGM.PtrDiffTy;
1020 }
1021 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1022 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1023 }
1024
1025 // The rest of the fields are common with data member pointers.
Reid Klecknerf6327302013-05-09 21:01:17 +00001026 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1027 NonVirtualBaseAdjustment);
Reid Kleckner79e02912013-05-03 01:15:11 +00001028}
1029
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001030/// Member pointers are the same if they're either bitwise identical *or* both
1031/// null. Null-ness for function members is determined by the first field,
1032/// while for data member pointers we must compare all fields.
1033llvm::Value *
1034MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1035 llvm::Value *L,
1036 llvm::Value *R,
1037 const MemberPointerType *MPT,
1038 bool Inequality) {
1039 CGBuilderTy &Builder = CGF.Builder;
1040
1041 // Handle != comparisons by switching the sense of all boolean operations.
1042 llvm::ICmpInst::Predicate Eq;
1043 llvm::Instruction::BinaryOps And, Or;
1044 if (Inequality) {
1045 Eq = llvm::ICmpInst::ICMP_NE;
1046 And = llvm::Instruction::Or;
1047 Or = llvm::Instruction::And;
1048 } else {
1049 Eq = llvm::ICmpInst::ICMP_EQ;
1050 And = llvm::Instruction::And;
1051 Or = llvm::Instruction::Or;
1052 }
1053
1054 // If this is a single field member pointer (single inheritance), this is a
1055 // single icmp.
1056 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1057 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknerf6327302013-05-09 21:01:17 +00001058 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001059 return Builder.CreateICmp(Eq, L, R);
1060
1061 // Compare the first field.
1062 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1063 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1064 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1065
1066 // Compare everything other than the first field.
1067 llvm::Value *Res = 0;
1068 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1069 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1070 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1071 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1072 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1073 if (Res)
1074 Res = Builder.CreateBinOp(And, Res, Cmp);
1075 else
1076 Res = Cmp;
1077 }
1078
1079 // Check if the first field is 0 if this is a function pointer.
1080 if (MPT->isMemberFunctionPointer()) {
1081 // (l1 == r1 && ...) || l0 == 0
1082 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1083 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1084 Res = Builder.CreateBinOp(Or, Res, IsZero);
1085 }
1086
1087 // Combine the comparison of the first field, which must always be true for
1088 // this comparison to succeeed.
1089 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1090}
1091
Reid Klecknera8a0f762013-03-22 19:02:54 +00001092llvm::Value *
1093MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1094 llvm::Value *MemPtr,
1095 const MemberPointerType *MPT) {
1096 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001097 llvm::SmallVector<llvm::Constant *, 4> fields;
1098 // We only need one field for member functions.
1099 if (MPT->isMemberFunctionPointer())
1100 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1101 else
1102 GetNullMemberPointerFields(MPT, fields);
1103 assert(!fields.empty());
1104 llvm::Value *FirstField = MemPtr;
1105 if (MemPtr->getType()->isStructTy())
1106 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1107 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001108
Reid Klecknera3609b02013-04-11 18:13:19 +00001109 // For function member pointers, we only need to test the function pointer
1110 // field. The other fields if any can be garbage.
1111 if (MPT->isMemberFunctionPointer())
1112 return Res;
1113
1114 // Otherwise, emit a series of compares and combine the results.
1115 for (int I = 1, E = fields.size(); I < E; ++I) {
1116 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1117 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1118 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1119 }
1120 return Res;
1121}
1122
Reid Klecknerf6327302013-05-09 21:01:17 +00001123bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1124 llvm::Constant *Val) {
1125 // Function pointers are null if the pointer in the first field is null.
1126 if (MPT->isMemberFunctionPointer()) {
1127 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1128 Val->getAggregateElement(0U) : Val;
1129 return FirstField->isNullValue();
1130 }
1131
1132 // If it's not a function pointer and it's zero initializable, we can easily
1133 // check zero.
1134 if (isZeroInitializable(MPT) && Val->isNullValue())
1135 return true;
1136
1137 // Otherwise, break down all the fields for comparison. Hopefully these
1138 // little Constants are reused, while a big null struct might not be.
1139 llvm::SmallVector<llvm::Constant *, 4> Fields;
1140 GetNullMemberPointerFields(MPT, Fields);
1141 if (Fields.size() == 1) {
1142 assert(Val->getType()->isIntegerTy());
1143 return Val == Fields[0];
1144 }
1145
1146 unsigned I, E;
1147 for (I = 0, E = Fields.size(); I != E; ++I) {
1148 if (Val->getAggregateElement(I) != Fields[I])
1149 break;
1150 }
1151 return I == E;
1152}
1153
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001154llvm::Value *
1155MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1156 llvm::Value *This,
1157 llvm::Value *VBTableOffset,
1158 llvm::Value *VBPtrOffset,
1159 llvm::Value **VBPtrOut) {
1160 CGBuilderTy &Builder = CGF.Builder;
1161 // Load the vbtable pointer from the vbptr in the instance.
1162 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1163 llvm::Value *VBPtr =
1164 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1165 if (VBPtrOut) *VBPtrOut = VBPtr;
1166 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1167 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1168
1169 // Load an i32 offset from the vb-table.
1170 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1171 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1172 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1173}
1174
Reid Klecknera3609b02013-04-11 18:13:19 +00001175// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1176// it.
1177llvm::Value *
1178MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1179 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001180 llvm::Value *VBTableOffset,
Reid Klecknera3609b02013-04-11 18:13:19 +00001181 llvm::Value *VBPtrOffset) {
1182 CGBuilderTy &Builder = CGF.Builder;
1183 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1184 llvm::BasicBlock *OriginalBB = 0;
1185 llvm::BasicBlock *SkipAdjustBB = 0;
1186 llvm::BasicBlock *VBaseAdjustBB = 0;
1187
1188 // In the unspecified inheritance model, there might not be a vbtable at all,
1189 // in which case we need to skip the virtual base lookup. If there is a
1190 // vbtable, the first entry is a no-op entry that gives back the original
1191 // base, so look for a virtual base adjustment offset of zero.
1192 if (VBPtrOffset) {
1193 OriginalBB = Builder.GetInsertBlock();
1194 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1195 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1196 llvm::Value *IsVirtual =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001197 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Klecknera3609b02013-04-11 18:13:19 +00001198 "memptr.is_vbase");
1199 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1200 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001201 }
1202
Reid Klecknera3609b02013-04-11 18:13:19 +00001203 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1204 // know the vbptr offset.
1205 if (!VBPtrOffset) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001206 CharUnits offs = CharUnits::Zero();
1207 if (RD->getNumVBases()) {
1208 offs = GetVBPtrOffsetFromBases(RD);
1209 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001210 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1211 }
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001212 llvm::Value *VBPtr = 0;
Reid Klecknera3609b02013-04-11 18:13:19 +00001213 llvm::Value *VBaseOffs =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001214 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Klecknera3609b02013-04-11 18:13:19 +00001215 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1216
1217 // Merge control flow with the case where we didn't have to adjust.
1218 if (VBaseAdjustBB) {
1219 Builder.CreateBr(SkipAdjustBB);
1220 CGF.EmitBlock(SkipAdjustBB);
1221 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1222 Phi->addIncoming(Base, OriginalBB);
1223 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1224 return Phi;
1225 }
1226 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001227}
1228
1229llvm::Value *
1230MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1231 llvm::Value *Base,
1232 llvm::Value *MemPtr,
1233 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001234 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001235 unsigned AS = Base->getType()->getPointerAddressSpace();
1236 llvm::Type *PType =
1237 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1238 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001239 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1240 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +00001241
Reid Klecknera3609b02013-04-11 18:13:19 +00001242 // Extract the fields we need, regardless of model. We'll apply them if we
1243 // have them.
1244 llvm::Value *FieldOffset = MemPtr;
1245 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1246 llvm::Value *VBPtrOffset = 0;
1247 if (MemPtr->getType()->isStructTy()) {
1248 // We need to extract values.
1249 unsigned I = 0;
1250 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1251 if (hasVBPtrOffsetField(Inheritance))
1252 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1253 if (hasVirtualBaseAdjustmentField(Inheritance))
1254 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001255 }
1256
Reid Klecknera3609b02013-04-11 18:13:19 +00001257 if (VirtualBaseAdjustmentOffset) {
1258 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1259 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001260 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001261 llvm::Value *Addr =
1262 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001263
1264 // Cast the address to the appropriate pointer type, adopting the address
1265 // space of the base pointer.
1266 return Builder.CreateBitCast(Addr, PType);
1267}
1268
Reid Klecknerf6327302013-05-09 21:01:17 +00001269static MSInheritanceModel
1270getInheritanceFromMemptr(const MemberPointerType *MPT) {
1271 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1272}
1273
1274llvm::Value *
1275MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1276 const CastExpr *E,
1277 llvm::Value *Src) {
1278 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1279 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1280 E->getCastKind() == CK_ReinterpretMemberPointer);
1281
1282 // Use constant emission if we can.
1283 if (isa<llvm::Constant>(Src))
1284 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1285
1286 // We may be adding or dropping fields from the member pointer, so we need
1287 // both types and the inheritance models of both records.
1288 const MemberPointerType *SrcTy =
1289 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1290 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1291 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1292 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1293 bool IsFunc = SrcTy->isMemberFunctionPointer();
1294
1295 // If the classes use the same null representation, reinterpret_cast is a nop.
1296 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1297 if (IsReinterpret && (IsFunc ||
1298 nullFieldOffsetIsZero(SrcInheritance) ==
1299 nullFieldOffsetIsZero(DstInheritance)))
1300 return Src;
1301
1302 CGBuilderTy &Builder = CGF.Builder;
1303
1304 // Branch past the conversion if Src is null.
1305 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1306 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1307
1308 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1309 // pointer value of the destination type.
1310 if (IsReinterpret) {
1311 // For reinterpret casts, sema ensures that src and dst are both functions
1312 // or data and have the same size, which means the LLVM types should match.
1313 assert(Src->getType() == DstNull->getType());
1314 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1315 }
1316
1317 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1318 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1319 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1320 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1321 CGF.EmitBlock(ConvertBB);
1322
1323 // Decompose src.
1324 llvm::Value *FirstField = Src;
1325 llvm::Value *NonVirtualBaseAdjustment = 0;
1326 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1327 llvm::Value *VBPtrOffset = 0;
1328 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1329 // We need to extract values.
1330 unsigned I = 0;
1331 FirstField = Builder.CreateExtractValue(Src, I++);
1332 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1333 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1334 if (hasVBPtrOffsetField(SrcInheritance))
1335 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1336 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1337 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1338 }
1339
1340 // For data pointers, we adjust the field offset directly. For functions, we
1341 // have a separate field.
1342 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1343 if (Adj) {
1344 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1345 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1346 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1347 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1348 NVAdjustField = getZeroInt();
1349 if (isDerivedToBase)
1350 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1351 else
1352 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1353 }
1354
1355 // FIXME PR15713: Support conversions through virtually derived classes.
1356
1357 // Recompose dst from the null struct and the adjusted fields from src.
1358 llvm::Value *Dst;
1359 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1360 Dst = FirstField;
1361 } else {
1362 Dst = llvm::UndefValue::get(DstNull->getType());
1363 unsigned Idx = 0;
1364 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1365 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1366 Dst = Builder.CreateInsertValue(
1367 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1368 if (hasVBPtrOffsetField(DstInheritance))
1369 Dst = Builder.CreateInsertValue(
1370 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1371 if (hasVirtualBaseAdjustmentField(DstInheritance))
1372 Dst = Builder.CreateInsertValue(
1373 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1374 }
1375 Builder.CreateBr(ContinueBB);
1376
1377 // In the continuation, choose between DstNull and Dst.
1378 CGF.EmitBlock(ContinueBB);
1379 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1380 Phi->addIncoming(DstNull, OriginalBB);
1381 Phi->addIncoming(Dst, ConvertBB);
1382 return Phi;
1383}
1384
1385llvm::Constant *
1386MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1387 llvm::Constant *Src) {
1388 const MemberPointerType *SrcTy =
1389 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1390 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1391
1392 // If src is null, emit a new null for dst. We can't return src because dst
1393 // might have a new representation.
1394 if (MemberPointerConstantIsNull(SrcTy, Src))
1395 return EmitNullMemberPointer(DstTy);
1396
1397 // We don't need to do anything for reinterpret_casts of non-null member
1398 // pointers. We should only get here when the two type representations have
1399 // the same size.
1400 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1401 return Src;
1402
1403 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1404 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1405
1406 // Decompose src.
1407 llvm::Constant *FirstField = Src;
1408 llvm::Constant *NonVirtualBaseAdjustment = 0;
1409 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1410 llvm::Constant *VBPtrOffset = 0;
1411 bool IsFunc = SrcTy->isMemberFunctionPointer();
1412 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1413 // We need to extract values.
1414 unsigned I = 0;
1415 FirstField = Src->getAggregateElement(I++);
1416 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1417 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1418 if (hasVBPtrOffsetField(SrcInheritance))
1419 VBPtrOffset = Src->getAggregateElement(I++);
1420 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1421 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1422 }
1423
1424 // For data pointers, we adjust the field offset directly. For functions, we
1425 // have a separate field.
1426 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1427 if (Adj) {
1428 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1429 llvm::Constant *&NVAdjustField =
1430 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1431 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1432 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1433 NVAdjustField = getZeroInt();
1434 if (IsDerivedToBase)
1435 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1436 else
1437 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1438 }
1439
1440 // FIXME PR15713: Support conversions through virtually derived classes.
1441
1442 // Recompose dst from the null struct and the adjusted fields from src.
1443 if (hasOnlyOneField(IsFunc, DstInheritance))
1444 return FirstField;
1445
1446 llvm::SmallVector<llvm::Constant *, 4> Fields;
1447 Fields.push_back(FirstField);
1448 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1449 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1450 if (hasVBPtrOffsetField(DstInheritance))
1451 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1452 if (hasVirtualBaseAdjustmentField(DstInheritance))
1453 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1454 return llvm::ConstantStruct::getAnon(Fields);
1455}
1456
Reid Klecknera3609b02013-04-11 18:13:19 +00001457llvm::Value *
1458MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1459 llvm::Value *&This,
1460 llvm::Value *MemPtr,
1461 const MemberPointerType *MPT) {
1462 assert(MPT->isMemberFunctionPointer());
1463 const FunctionProtoType *FPT =
1464 MPT->getPointeeType()->castAs<FunctionProtoType>();
1465 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1466 llvm::FunctionType *FTy =
1467 CGM.getTypes().GetFunctionType(
1468 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1469 CGBuilderTy &Builder = CGF.Builder;
1470
1471 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1472
1473 // Extract the fields we need, regardless of model. We'll apply them if we
1474 // have them.
1475 llvm::Value *FunctionPointer = MemPtr;
1476 llvm::Value *NonVirtualBaseAdjustment = NULL;
1477 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1478 llvm::Value *VBPtrOffset = NULL;
1479 if (MemPtr->getType()->isStructTy()) {
1480 // We need to extract values.
1481 unsigned I = 0;
1482 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001483 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1484 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner79e02912013-05-03 01:15:11 +00001485 if (hasVBPtrOffsetField(Inheritance))
1486 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001487 if (hasVirtualBaseAdjustmentField(Inheritance))
1488 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1489 }
1490
1491 if (VirtualBaseAdjustmentOffset) {
1492 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1493 VBPtrOffset);
1494 }
1495
1496 if (NonVirtualBaseAdjustment) {
1497 // Apply the adjustment and cast back to the original struct type.
1498 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1499 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1500 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1501 }
1502
1503 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1504}
1505
Charles Davis071cc7d2010-08-16 03:33:14 +00001506CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +00001507 return new MicrosoftCXXABI(CGM);
1508}
1509