blob: a8e074c7b379e05f62b79439f0ec2c2e3bca1b5d [file] [log] [blame]
Charles Davis74ce8592010-06-09 23:25:41 +00001//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davis74ce8592010-06-09 23:25:41 +000011// The class in this file generates structures that follow the Microsoft
12// Visual C++ ABI, which is actually not very well documented at all outside
13// of Microsoft.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGCXXABI.h"
18#include "CodeGenModule.h"
Reid Kleckner7810af02013-06-19 15:20:38 +000019#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
Charles Davis74ce8592010-06-09 23:25:41 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000023#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000024#include "llvm/ADT/StringSet.h"
Charles Davis74ce8592010-06-09 23:25:41 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
Charles Davis53c59df2010-08-16 03:33:14 +000031class MicrosoftCXXABI : public CGCXXABI {
Charles Davis74ce8592010-06-09 23:25:41 +000032public:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall5d865c322010-08-31 07:33:07 +000034
Stephen Lin9dc6eef2013-06-30 20:40:16 +000035 bool HasThisReturn(GlobalDecl GD) const;
36
Timur Iskhodzhanov8fe501d2013-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 Kleckner23f4c4b2013-06-21 12:45:15 +000043 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000044 return RAA_DirectInMemory;
45 return RAA_Default;
46 }
47
Joao Matos2ce88ef2012-07-17 17:10:11 +000048 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-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 Matos2ce88ef2012-07-17 17:10:11 +000052
John McCall82fb8922012-09-25 10:10:39 +000053 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
54 llvm::Value *ptr,
55 QualType type);
56
Reid Klecknerd8cbeec2013-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 McCall5d865c322010-08-31 07:33:07 +000062 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
63 CXXCtorType Type,
64 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000065 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000066
Reid Kleckner7810af02013-06-19 15:20:38 +000067 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
68 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000069
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000070 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
71 const CXXRecordDecl *RD);
72
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000073 void EmitCXXConstructors(const CXXConstructorDecl *D);
74
Reid Klecknere7de47e2013-07-22 13:51:44 +000075 // Background on MSVC destructors
76 // ==============================
77 //
78 // Both Itanium and MSVC ABIs have destructor variants. The variant names
79 // roughly correspond in the following way:
80 // Itanium Microsoft
81 // Base -> no name, just ~Class
82 // Complete -> vbase destructor
83 // Deleting -> scalar deleting destructor
84 // vector deleting destructor
85 //
86 // The base and complete destructors are the same as in Itanium, although the
87 // complete destructor does not accept a VTT parameter when there are virtual
88 // bases. A separate mechanism involving vtordisps is used to ensure that
89 // virtual methods of destroyed subobjects are not called.
90 //
91 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
92 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
93 // pointer points to an array. The scalar deleting destructor assumes that
94 // bit 2 is zero, and therefore does not contain a loop.
95 //
96 // For virtual destructors, only one entry is reserved in the vftable, and it
97 // always points to the vector deleting destructor. The vector deleting
98 // destructor is the most general, so it can be used to destroy objects in
99 // place, delete single heap objects, or delete arrays.
100 //
101 // A TU defining a non-inline destructor is only guaranteed to emit a base
102 // destructor, and all of the other variants are emitted on an as-needed basis
103 // in COMDATs. Because a non-base destructor can be emitted in a TU that
104 // lacks a definition for the destructor, non-base destructors must always
105 // delegate to or alias the base destructor.
106
107 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000108 CXXDtorType Type,
109 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000110 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000111
Reid Klecknere7de47e2013-07-22 13:51:44 +0000112 /// Non-base dtors should be emitted as delegating thunks in this ABI.
113 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
114 CXXDtorType DT) const {
115 return DT != Dtor_Base;
116 }
117
118 void EmitCXXDestructors(const CXXDestructorDecl *D);
119
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000120 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
121 MD = MD->getCanonicalDecl();
122 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
123 MicrosoftVFTableContext::MethodVFTableLocation ML =
124 CGM.getVFTableContext().getMethodVFTableLocation(MD);
125 // The vbases might be ordered differently in the final overrider object
126 // and the complete object, so the "this" argument may sometimes point to
127 // memory that has no particular type (e.g. past the complete object).
128 // In this case, we just use a generic pointer type.
129 // FIXME: might want to have a more precise type in the non-virtual
130 // multiple inheritance case.
131 if (ML.VBase || !ML.VFTableOffset.isZero())
132 return 0;
133 }
134 return MD->getParent();
135 }
136
137 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
138 GlobalDecl GD,
139 llvm::Value *This);
140
John McCall5d865c322010-08-31 07:33:07 +0000141 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
142 QualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +0000143 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000144
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000145 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
146 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
147
John McCall0f999f32012-09-25 08:00:39 +0000148 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000149
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000150 void EmitConstructorCall(CodeGenFunction &CGF,
151 const CXXConstructorDecl *D, CXXCtorType Type,
152 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000153 llvm::Value *This,
154 CallExpr::const_arg_iterator ArgBeg,
155 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000156
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000157 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
158
159 llvm::Value *getVTableAddressPointInStructor(
160 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
161 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
162 bool &NeedsVirtualOffset);
163
164 llvm::Constant *
165 getVTableAddressPointForConstExpr(BaseSubobject Base,
166 const CXXRecordDecl *VTableClass);
167
168 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
169 CharUnits VPtrOffset);
170
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
172 llvm::Value *This, llvm::Type *Ty);
173
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000174 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
175 const CXXDestructorDecl *Dtor,
176 CXXDtorType DtorType, SourceLocation CallLoc,
177 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000178
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000179 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
180 CallArgList &CallArgs) {
181 assert(GD.getDtorType() == Dtor_Deleting &&
182 "Only deleting destructor thunks are available in this ABI");
183 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
184 CGM.getContext().IntTy);
185 }
186
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000187 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000188
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000189 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
190 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
191 }
192
John McCallc84ed6a2012-05-01 06:13:13 +0000193 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
194 llvm::GlobalVariable *DeclPtr,
195 bool PerformInit);
196
John McCall29036752011-01-27 02:46:02 +0000197 // ==== Notes on array cookies =========
198 //
199 // MSVC seems to only use cookies when the class has a destructor; a
200 // two-argument usual array deallocation function isn't sufficient.
201 //
202 // For example, this code prints "100" and "1":
203 // struct A {
204 // char x;
205 // void *operator new[](size_t sz) {
206 // printf("%u\n", sz);
207 // return malloc(sz);
208 // }
209 // void operator delete[](void *p, size_t sz) {
210 // printf("%u\n", sz);
211 // free(p);
212 // }
213 // };
214 // int main() {
215 // A *p = new A[100];
216 // delete[] p;
217 // }
218 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000219
220 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
221 bool requiresArrayCookie(const CXXNewExpr *expr);
222 CharUnits getArrayCookieSizeImpl(QualType type);
223 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
224 llvm::Value *NewPtr,
225 llvm::Value *NumElements,
226 const CXXNewExpr *expr,
227 QualType ElementType);
228 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
229 llvm::Value *allocPtr,
230 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000231
232private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000233 MicrosoftMangleContext &getMangleContext() {
234 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
235 }
236
Reid Kleckner2341ae32013-04-11 18:13:19 +0000237 llvm::Constant *getZeroInt() {
238 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000239 }
240
Reid Kleckner2341ae32013-04-11 18:13:19 +0000241 llvm::Constant *getAllOnesInt() {
242 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000243 }
244
Reid Kleckner452abac2013-05-09 21:01:17 +0000245 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
246 return C ? C : getZeroInt();
247 }
248
249 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
250 return C ? C : getZeroInt();
251 }
252
Reid Kleckner2341ae32013-04-11 18:13:19 +0000253 void
254 GetNullMemberPointerFields(const MemberPointerType *MPT,
255 llvm::SmallVectorImpl<llvm::Constant *> &fields);
256
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000257 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
258 /// it is reusing a vbptr from a non-virtual base. RD must have morally
259 /// virtual bases.
260 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
261
262 /// \brief Shared code for virtual base adjustment. Returns the offset from
263 /// the vbptr to the virtual base. Optionally returns the address of the
264 /// vbptr itself.
265 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
266 llvm::Value *Base,
267 llvm::Value *VBPtrOffset,
268 llvm::Value *VBTableOffset,
269 llvm::Value **VBPtr = 0);
270
271 /// \brief Performs a full virtual base adjustment. Used to dereference
272 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000273 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
274 llvm::Value *Base,
275 llvm::Value *VirtualBaseAdjustmentOffset,
276 llvm::Value *VBPtrOffset /* optional */);
277
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000278 /// \brief Emits a full member pointer with the fields common to data and
279 /// function member pointers.
280 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
281 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000282 const CXXRecordDecl *RD,
283 CharUnits NonVirtualBaseAdjustment);
284
285 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
286 const CXXMethodDecl *MD,
287 CharUnits NonVirtualBaseAdjustment);
288
289 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
290 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000291
Reid Kleckner7810af02013-06-19 15:20:38 +0000292 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
293 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
294
295 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
296 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
297
Reid Kleckner407e8b62013-03-22 19:02:54 +0000298public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000299 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
300
301 virtual bool isZeroInitializable(const MemberPointerType *MPT);
302
Reid Kleckner407e8b62013-03-22 19:02:54 +0000303 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
304
305 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
306 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000307 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
308 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000309
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000310 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
311 llvm::Value *L,
312 llvm::Value *R,
313 const MemberPointerType *MPT,
314 bool Inequality);
315
Reid Kleckner407e8b62013-03-22 19:02:54 +0000316 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
317 llvm::Value *MemPtr,
318 const MemberPointerType *MPT);
319
320 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
321 llvm::Value *Base,
322 llvm::Value *MemPtr,
323 const MemberPointerType *MPT);
324
Reid Kleckner452abac2013-05-09 21:01:17 +0000325 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
326 const CastExpr *E,
327 llvm::Value *Src);
328
329 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
330 llvm::Constant *Src);
331
Reid Kleckner2341ae32013-04-11 18:13:19 +0000332 virtual llvm::Value *
333 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
334 llvm::Value *&This,
335 llvm::Value *MemPtr,
336 const MemberPointerType *MPT);
337
Reid Kleckner7810af02013-06-19 15:20:38 +0000338private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000339 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
340 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
341 /// \brief All the vftables that have been referenced.
342 VFTablesMapTy VFTablesMap;
343
344 /// \brief This set holds the record decls we've deferred vtable emission for.
345 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
346
347
348 /// \brief All the vbtables which have been referenced.
Reid Kleckner7810af02013-06-19 15:20:38 +0000349 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000350
351 /// Info on the global variable used to guard initialization of static locals.
352 /// The BitIndex field is only used for externally invisible declarations.
353 struct GuardInfo {
354 GuardInfo() : Guard(0), BitIndex(0) {}
355 llvm::GlobalVariable *Guard;
356 unsigned BitIndex;
357 };
358
359 /// Map from DeclContext to the current guard variable. We assume that the
360 /// AST is visited in source code order.
361 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000362};
363
364}
365
John McCall82fb8922012-09-25 10:10:39 +0000366llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
367 llvm::Value *ptr,
368 QualType type) {
369 // FIXME: implement
370 return ptr;
371}
372
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000373/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
374/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
375static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
376 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
377 E = RD->bases_end(); I != E; ++I) {
378 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
379 if (!I->isVirtual() && Base->getNumVBases() > 0)
380 return Base;
381 }
382 llvm_unreachable("RD must have an nv base with vbases");
383}
384
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000385CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
386 assert(RD->getNumVBases());
387 CharUnits Total = CharUnits::Zero();
388 while (RD) {
389 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
390 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
391 // -1 is the sentinel for no vbptr.
392 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
393 Total += VBPtrOffset;
394 break;
395 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000396 RD = FindFirstNVBaseWithVBases(RD);
397 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000398 }
399 return Total;
400}
401
402llvm::Value *
403MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
404 llvm::Value *This,
405 const CXXRecordDecl *ClassDecl,
406 const CXXRecordDecl *BaseClassDecl) {
407 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
408 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000409 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000410 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000411 llvm::Value *VBTableOffset =
412 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
413
414 llvm::Value *VBPtrToNewBase =
415 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
416 VBPtrToNewBase =
417 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
418 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
419}
420
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000421bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
422 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000423}
424
425void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
426 CXXCtorType Type,
427 CanQualType &ResTy,
428 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000429 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000430
431 const CXXRecordDecl *Class = Ctor->getParent();
432 if (Class->getNumVBases()) {
433 // Constructors of classes with virtual bases take an implicit parameter.
434 ArgTys.push_back(CGM.getContext().IntTy);
435 }
436}
437
Reid Kleckner7810af02013-06-19 15:20:38 +0000438llvm::BasicBlock *
439MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
440 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000441 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
442 assert(IsMostDerivedClass &&
443 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000444 llvm::Value *IsCompleteObject =
445 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000446
447 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
448 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
449 CGF.Builder.CreateCondBr(IsCompleteObject,
450 CallVbaseCtorsBB, SkipVbaseCtorsBB);
451
452 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000453
454 // Fill in the vbtable pointers here.
455 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000456
457 // CGF will put the base ctor calls in this basic block for us later.
458
459 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000460}
461
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000462void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
463 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
464 // In most cases, an override for a vbase virtual method can adjust
465 // the "this" parameter by applying a constant offset.
466 // However, this is not enough while a constructor or a destructor of some
467 // class X is being executed if all the following conditions are met:
468 // - X has virtual bases, (1)
469 // - X overrides a virtual method M of a vbase Y, (2)
470 // - X itself is a vbase of the most derived class.
471 //
472 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
473 // which holds the extra amount of "this" adjustment we must do when we use
474 // the X vftables (i.e. during X ctor or dtor).
475 // Outside the ctors and dtors, the values of vtorDisps are zero.
476
477 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
478 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
479 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
480 CGBuilderTy &Builder = CGF.Builder;
481
482 unsigned AS =
483 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
484 llvm::Value *Int8This = 0; // Initialize lazily.
485
486 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
487 I != E; ++I) {
488 if (!I->second.hasVtorDisp())
489 continue;
490
491 llvm::Value *VBaseOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
492 CGF, getThisValue(CGF), RD, I->first);
493 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
494 // just to Trunc back immediately.
495 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
496 uint64_t ConstantVBaseOffset =
497 Layout.getVBaseClassOffset(I->first).getQuantity();
498
499 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
500 llvm::Value *VtorDispValue = Builder.CreateSub(
501 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
502 "vtordisp.value");
503
504 if (!Int8This)
505 Int8This = Builder.CreateBitCast(getThisValue(CGF),
506 CGF.Int8Ty->getPointerTo(AS));
507 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
508 // vtorDisp is always the 32-bits before the vbase in the class layout.
509 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
510 VtorDispPtr = Builder.CreateBitCast(
511 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
512
513 Builder.CreateStore(VtorDispValue, VtorDispPtr);
514 }
515}
516
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000517void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
518 // There's only one constructor type in this ABI.
519 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
520}
521
Reid Kleckner7810af02013-06-19 15:20:38 +0000522void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
523 const CXXRecordDecl *RD) {
524 llvm::Value *ThisInt8Ptr =
525 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
526
527 const VBTableVector &VBTables = EnumerateVBTables(RD);
528 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
529 I != E; ++I) {
530 const ASTRecordLayout &SubobjectLayout =
531 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
532 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
533 SubobjectLayout.getVBPtrOffset()).getQuantity();
534 llvm::Value *VBPtr =
535 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
536 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
537 "vbptr." + I->ReusingBase->getName());
538 CGF.Builder.CreateStore(I->GV, VBPtr);
539 }
540}
541
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000542void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
543 CXXDtorType Type,
544 CanQualType &ResTy,
545 SmallVectorImpl<CanQualType> &ArgTys) {
546 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000547
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000548 // TODO: 'for base' flag
549
550 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000551 // The scalar deleting destructor takes an implicit int parameter.
552 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000553 }
554}
555
Reid Klecknere7de47e2013-07-22 13:51:44 +0000556void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
557 // The TU defining a dtor is only guaranteed to emit a base destructor. All
558 // other destructor variants are delegating thunks.
559 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
560}
561
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000562llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
563 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
564 GD = GD.getCanonicalDecl();
565 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000566 // FIXME: consider splitting the vdtor vs regular method code into two
567 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000568
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000569 GlobalDecl LookupGD = GD;
570 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
571 // Complete dtors take a pointer to the complete object,
572 // thus don't need adjustment.
573 if (GD.getDtorType() == Dtor_Complete)
574 return This;
575
576 // There's only Dtor_Deleting in vftable but it shares the this adjustment
577 // with the base one, so look up the deleting one instead.
578 LookupGD = GlobalDecl(DD, Dtor_Deleting);
579 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000580 MicrosoftVFTableContext::MethodVFTableLocation ML =
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000581 CGM.getVFTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000582
583 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
584 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000585 CharUnits StaticOffset = ML.VFTableOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000586 if (ML.VBase) {
587 bool AvoidVirtualOffset = false;
588 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
589 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000590 // same record type or another destructor of a more derived type;
591 // or a constructor of the same record type if an exception is thrown.
592 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
593 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000594 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000595 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000596
597 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000598 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
599 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
600 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
601 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
602 // We're calling the main base dtor from a complete structor,
603 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000604 AvoidVirtualOffset = true;
605 } else {
606 // Let's see if we try to call a destructor of a non-virtual base.
607 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
608 E = CurRD->bases_end(); I != E; ++I) {
609 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
610 continue;
611 // If we call a base destructor for a non-virtual base, we statically
612 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000613 // The total offset should reflect the adjustment done by
614 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000615 AvoidVirtualOffset = true;
616 break;
617 }
618 }
619 }
620
621 if (AvoidVirtualOffset) {
622 const ASTRecordLayout &Layout =
623 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000624 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
625 } else {
626 This = CGF.Builder.CreateBitCast(This, charPtrTy);
627 llvm::Value *VBaseOffset = CGM.getCXXABI()
628 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
629 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
630 }
631 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000632 if (!StaticOffset.isZero()) {
633 assert(StaticOffset.isPositive());
634 This = CGF.Builder.CreateBitCast(This, charPtrTy);
635 This = CGF.Builder
636 .CreateConstInBoundsGEP1_64(This, StaticOffset.getQuantity());
637 }
638 return This;
639}
640
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000641static bool IsDeletingDtor(GlobalDecl GD) {
642 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
643 if (isa<CXXDestructorDecl>(MD)) {
644 return GD.getDtorType() == Dtor_Deleting;
645 }
646 return false;
647}
648
John McCall0f999f32012-09-25 08:00:39 +0000649void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
650 QualType &ResTy,
651 FunctionArgList &Params) {
652 BuildThisParam(CGF, Params);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000653
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000654 ASTContext &Context = getContext();
655 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
656 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
657 ImplicitParamDecl *IsMostDerived
658 = ImplicitParamDecl::Create(Context, 0,
659 CGF.CurGD.getDecl()->getLocation(),
660 &Context.Idents.get("is_most_derived"),
661 Context.IntTy);
662 Params.push_back(IsMostDerived);
663 getStructorImplicitParamDecl(CGF) = IsMostDerived;
664 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000665 ImplicitParamDecl *ShouldDelete
666 = ImplicitParamDecl::Create(Context, 0,
667 CGF.CurGD.getDecl()->getLocation(),
668 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000669 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000670 Params.push_back(ShouldDelete);
671 getStructorImplicitParamDecl(CGF) = ShouldDelete;
672 }
John McCall0f999f32012-09-25 08:00:39 +0000673}
674
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000675llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
676 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
677 GD = GD.getCanonicalDecl();
678 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000679
680 GlobalDecl LookupGD = GD;
681 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
682 // Complete destructors take a pointer to the complete object as a
683 // parameter, thus don't need this adjustment.
684 if (GD.getDtorType() == Dtor_Complete)
685 return This;
686
687 // There's no Dtor_Base in vftable but it shares the this adjustment with
688 // the deleting one, so look it up instead.
689 LookupGD = GlobalDecl(DD, Dtor_Deleting);
690 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000691
692 // In this ABI, every virtual function takes a pointer to one of the
693 // subobjects that first defines it as the 'this' parameter, rather than a
694 // pointer to ther final overrider subobject. Thus, we need to adjust it back
695 // to the final overrider subobject before use.
696 // See comments in the MicrosoftVFTableContext implementation for the details.
697
698 MicrosoftVFTableContext::MethodVFTableLocation ML =
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000699 CGM.getVFTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000700 CharUnits Adjustment = ML.VFTableOffset;
701 if (ML.VBase) {
702 const ASTRecordLayout &DerivedLayout =
703 CGF.getContext().getASTRecordLayout(MD->getParent());
704 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
705 }
706
707 if (Adjustment.isZero())
708 return This;
709
710 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
711 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
712 *thisTy = This->getType();
713
714 This = CGF.Builder.CreateBitCast(This, charPtrTy);
715 assert(Adjustment.isPositive());
716 This = CGF.Builder.CreateConstGEP1_64(This, -Adjustment.getQuantity());
717 return CGF.Builder.CreateBitCast(This, thisTy);
718}
719
John McCall0f999f32012-09-25 08:00:39 +0000720void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
721 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000722
723 /// If this is a function that the ABI specifies returns 'this', initialize
724 /// the return slot to 'this' at the start of the function.
725 ///
726 /// Unlike the setting of return types, this is done within the ABI
727 /// implementation instead of by clients of CGCXXABI because:
728 /// 1) getThisValue is currently protected
729 /// 2) in theory, an ABI could implement 'this' returns some other way;
730 /// HasThisReturn only specifies a contract, not the implementation
731 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000732 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000733
734 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
735 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
736 assert(getStructorImplicitParamDecl(CGF) &&
737 "no implicit parameter for a constructor with virtual bases?");
738 getStructorImplicitParamValue(CGF)
739 = CGF.Builder.CreateLoad(
740 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
741 "is_most_derived");
742 }
743
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000744 if (IsDeletingDtor(CGF.CurGD)) {
745 assert(getStructorImplicitParamDecl(CGF) &&
746 "no implicit parameter for a deleting destructor?");
747 getStructorImplicitParamValue(CGF)
748 = CGF.Builder.CreateLoad(
749 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
750 "should_call_delete");
751 }
John McCall0f999f32012-09-25 08:00:39 +0000752}
753
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000754void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Linc467c872013-06-19 18:10:35 +0000755 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000756 CXXCtorType Type,
757 bool ForVirtualBase,
Stephen Linc467c872013-06-19 18:10:35 +0000758 bool Delegating,
759 llvm::Value *This,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000760 CallExpr::const_arg_iterator ArgBeg,
761 CallExpr::const_arg_iterator ArgEnd) {
762 assert(Type == Ctor_Complete || Type == Ctor_Base);
763 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
764
765 llvm::Value *ImplicitParam = 0;
766 QualType ImplicitParamTy;
767 if (D->getParent()->getNumVBases()) {
768 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
769 ImplicitParamTy = getContext().IntTy;
770 }
771
772 // FIXME: Provide a source location here.
Stephen Linc467c872013-06-19 18:10:35 +0000773 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000774 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000775}
776
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000777void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
778 const CXXRecordDecl *RD) {
779 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
780 MicrosoftVFTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
781 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
782
783 for (MicrosoftVFTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
784 E = VFPtrs.end(); I != E; ++I) {
785 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
786 if (VTable->hasInitializer())
787 continue;
788
789 const VTableLayout &VTLayout =
790 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
791 llvm::Constant *Init = CGVT.CreateVTableInitializer(
792 RD, VTLayout.vtable_component_begin(),
793 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
794 VTLayout.getNumVTableThunks());
795 VTable->setInitializer(Init);
796
797 VTable->setLinkage(Linkage);
798 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
799 }
800}
801
802llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
803 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
804 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
805 NeedsVirtualOffset = (NearestVBase != 0);
806
807 llvm::Value *VTableAddressPoint =
808 getAddrOfVTable(VTableClass, Base.getBaseOffset());
809 if (!VTableAddressPoint) {
810 assert(Base.getBase()->getNumVBases() &&
811 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
812 }
813 return VTableAddressPoint;
814}
815
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000816static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
817 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
818 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000819 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000820 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000821}
822
823llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
824 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
825 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
826 assert(VTable && "Couldn't find a vftable for the given base?");
827 return VTable;
828}
829
830llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
831 CharUnits VPtrOffset) {
832 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
833 // shouldn't be used in the given record type. We want to cache this result in
834 // VFTablesMap, thus a simple zero check is not sufficient.
835 VFTableIdTy ID(RD, VPtrOffset);
836 VFTablesMapTy::iterator I;
837 bool Inserted;
838 llvm::tie(I, Inserted) = VFTablesMap.insert(
839 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
840 if (!Inserted)
841 return I->second;
842
843 llvm::GlobalVariable *&VTable = I->second;
844
845 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
846 const MicrosoftVFTableContext::VFPtrListTy &VFPtrs =
847 VFTContext.getVFPtrOffsets(RD);
848
849 if (DeferredVFTables.insert(RD)) {
850 // We haven't processed this record type before.
851 // Queue up this v-table for possible deferred emission.
852 CGM.addDeferredVTable(RD);
853
854#ifndef NDEBUG
855 // Create all the vftables at once in order to make sure each vftable has
856 // a unique mangled name.
857 llvm::StringSet<> ObservedMangledNames;
858 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
859 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000860 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000861 if (!ObservedMangledNames.insert(Name.str()))
862 llvm_unreachable("Already saw this mangling before?");
863 }
864#endif
865 }
866
867 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
868 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
869 continue;
870
871 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
872 CGM.Int8PtrTy,
873 VFTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
874 .getNumVTableComponents());
875
876 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000877 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000878 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
879 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
880 VTable->setUnnamedAddr(true);
881 break;
882 }
883
884 return VTable;
885}
886
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000887llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
888 GlobalDecl GD,
889 llvm::Value *This,
890 llvm::Type *Ty) {
891 GD = GD.getCanonicalDecl();
892 CGBuilderTy &Builder = CGF.Builder;
893
894 Ty = Ty->getPointerTo()->getPointerTo();
895 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
896 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
897
898 MicrosoftVFTableContext::MethodVFTableLocation ML =
899 CGM.getVFTableContext().getMethodVFTableLocation(GD);
900 llvm::Value *VFuncPtr =
901 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
902 return Builder.CreateLoad(VFuncPtr);
903}
904
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000905void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
906 const CXXDestructorDecl *Dtor,
907 CXXDtorType DtorType,
908 SourceLocation CallLoc,
909 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000910 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
911
912 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000913 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000914 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000915 const CGFunctionInfo *FInfo =
916 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000917 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000918 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000919
920 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000921 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000922 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000923 DtorType == Dtor_Deleting);
924
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000925 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000926 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000927 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000928}
929
Reid Kleckner7810af02013-06-19 15:20:38 +0000930const VBTableVector &
931MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
932 // At this layer, we can key the cache off of a single class, which is much
933 // easier than caching at the GlobalVariable layer.
934 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
935 bool added;
936 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
937 VBTableVector &VBTables = I->second;
938 if (!added)
939 return VBTables;
940
941 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
942
943 return VBTables;
944}
945
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000946void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +0000947 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000948 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
949
Reid Kleckner7810af02013-06-19 15:20:38 +0000950 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
951 I != E; ++I) {
952 I->EmitVBTableDefinition(CGM, RD, Linkage);
953 }
954}
955
John McCallb91cd662012-05-01 05:23:51 +0000956bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
957 QualType elementType) {
958 // Microsoft seems to completely ignore the possibility of a
959 // two-argument usual deallocation function.
960 return elementType.isDestructedType();
961}
962
963bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
964 // Microsoft seems to completely ignore the possibility of a
965 // two-argument usual deallocation function.
966 return expr->getAllocatedType().isDestructedType();
967}
968
969CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
970 // The array cookie is always a size_t; we then pad that out to the
971 // alignment of the element type.
972 ASTContext &Ctx = getContext();
973 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
974 Ctx.getTypeAlignInChars(type));
975}
976
977llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
978 llvm::Value *allocPtr,
979 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +0000980 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +0000981 llvm::Value *numElementsPtr =
982 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
983 return CGF.Builder.CreateLoad(numElementsPtr);
984}
985
986llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
987 llvm::Value *newPtr,
988 llvm::Value *numElements,
989 const CXXNewExpr *expr,
990 QualType elementType) {
991 assert(requiresArrayCookie(expr));
992
993 // The size of the cookie.
994 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
995
996 // Compute an offset to the cookie.
997 llvm::Value *cookiePtr = newPtr;
998
999 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001000 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001001 llvm::Value *numElementsPtr
1002 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1003 CGF.Builder.CreateStore(numElements, numElementsPtr);
1004
1005 // Finally, compute a pointer to the actual data buffer by skipping
1006 // over the cookie completely.
1007 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1008 cookieSize.getQuantity());
1009}
1010
John McCallc84ed6a2012-05-01 06:13:13 +00001011void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001012 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001013 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001014 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1015 // threadsafe. Since the user may be linking in inline functions compiled by
1016 // cl.exe, there's no reason to provide a false sense of security by using
1017 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001018
Richard Smithdbf74ba2013-04-14 23:01:42 +00001019 if (D.getTLSKind())
1020 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1021
Reid Klecknerd8110b62013-09-10 20:14:30 +00001022 CGBuilderTy &Builder = CGF.Builder;
1023 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1024 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1025
1026 // Get the guard variable for this function if we have one already.
1027 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1028
1029 unsigned BitIndex;
1030 if (D.isExternallyVisible()) {
1031 // Externally visible variables have to be numbered in Sema to properly
1032 // handle unreachable VarDecls.
1033 BitIndex = getContext().getManglingNumber(&D);
1034 assert(BitIndex > 0);
1035 BitIndex--;
1036 } else {
1037 // Non-externally visible variables are numbered here in CodeGen.
1038 BitIndex = GI.BitIndex++;
1039 }
1040
1041 if (BitIndex >= 32) {
1042 if (D.isExternallyVisible())
1043 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1044 BitIndex %= 32;
1045 GI.Guard = 0;
1046 }
1047
1048 // Lazily create the i32 bitfield for this function.
1049 if (!GI.Guard) {
1050 // Mangle the name for the guard.
1051 SmallString<256> GuardName;
1052 {
1053 llvm::raw_svector_ostream Out(GuardName);
1054 getMangleContext().mangleStaticGuardVariable(&D, Out);
1055 Out.flush();
1056 }
1057
1058 // Create the guard variable with a zero-initializer. Just absorb linkage
1059 // and visibility from the guarded variable.
1060 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1061 GV->getLinkage(), Zero, GuardName.str());
1062 GI.Guard->setVisibility(GV->getVisibility());
1063 } else {
1064 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1065 "static local from the same function had different linkage");
1066 }
1067
1068 // Pseudo code for the test:
1069 // if (!(GuardVar & MyGuardBit)) {
1070 // GuardVar |= MyGuardBit;
1071 // ... initialize the object ...;
1072 // }
1073
1074 // Test our bit from the guard variable.
1075 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1076 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1077 llvm::Value *IsInitialized =
1078 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1079 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1080 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1081 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1082
1083 // Set our bit in the guard variable and emit the initializer and add a global
1084 // destructor if appropriate.
1085 CGF.EmitBlock(InitBlock);
1086 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1087 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1088 Builder.CreateBr(EndBlock);
1089
1090 // Continue.
1091 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001092}
1093
Reid Kleckner2341ae32013-04-11 18:13:19 +00001094// Member pointer helpers.
1095static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1096 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001097}
1098
Reid Kleckner452abac2013-05-09 21:01:17 +00001099static bool hasOnlyOneField(bool IsMemberFunction,
1100 MSInheritanceModel Inheritance) {
1101 return Inheritance <= MSIM_SinglePolymorphic ||
1102 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001103}
1104
Reid Kleckner2341ae32013-04-11 18:13:19 +00001105// Only member pointers to functions need a this adjustment, since it can be
1106// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001107static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001108 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001109 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001110}
1111
1112static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1113 return Inheritance >= MSIM_Virtual;
1114}
1115
1116// Use zero for the field offset of a null data member pointer if we can
1117// guarantee that zero is not a valid field offset, or if the member pointer has
1118// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1119// use zero for null. If there are multiple fields, we can use zero even if it
1120// is a valid field offset because null-ness testing will check the other
1121// fields.
1122static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1123 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1124}
1125
1126bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1127 // Null-ness for function memptrs only depends on the first field, which is
1128 // the function pointer. The rest don't matter, so we can zero initialize.
1129 if (MPT->isMemberFunctionPointer())
1130 return true;
1131
1132 // The virtual base adjustment field is always -1 for null, so if we have one
1133 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1134 // valid field offset.
1135 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1136 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1137 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1138 nullFieldOffsetIsZero(Inheritance));
1139}
1140
1141llvm::Type *
1142MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1143 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1144 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1145 llvm::SmallVector<llvm::Type *, 4> fields;
1146 if (MPT->isMemberFunctionPointer())
1147 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1148 else
1149 fields.push_back(CGM.IntTy); // FieldOffset
1150
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001151 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1152 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001153 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001154 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001155 fields.push_back(CGM.IntTy);
1156 if (hasVirtualBaseAdjustmentField(Inheritance))
1157 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1158
1159 if (fields.size() == 1)
1160 return fields[0];
1161 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1162}
1163
1164void MicrosoftCXXABI::
1165GetNullMemberPointerFields(const MemberPointerType *MPT,
1166 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1167 assert(fields.empty());
1168 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1169 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1170 if (MPT->isMemberFunctionPointer()) {
1171 // FunctionPointerOrVirtualThunk
1172 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1173 } else {
1174 if (nullFieldOffsetIsZero(Inheritance))
1175 fields.push_back(getZeroInt()); // FieldOffset
1176 else
1177 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001178 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001179
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001180 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1181 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001182 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001183 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001184 fields.push_back(getZeroInt());
1185 if (hasVirtualBaseAdjustmentField(Inheritance))
1186 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001187}
1188
1189llvm::Constant *
1190MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001191 llvm::SmallVector<llvm::Constant *, 4> fields;
1192 GetNullMemberPointerFields(MPT, fields);
1193 if (fields.size() == 1)
1194 return fields[0];
1195 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1196 assert(Res->getType() == ConvertMemberPointerType(MPT));
1197 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001198}
1199
1200llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001201MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1202 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001203 const CXXRecordDecl *RD,
1204 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001205{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001206 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001207
1208 // Single inheritance class member pointer are represented as scalars instead
1209 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001210 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001211 return FirstField;
1212
Reid Kleckner2341ae32013-04-11 18:13:19 +00001213 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001214 fields.push_back(FirstField);
1215
1216 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001217 fields.push_back(llvm::ConstantInt::get(
1218 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001219
Reid Kleckner2341ae32013-04-11 18:13:19 +00001220 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001221 CharUnits Offs = CharUnits::Zero();
1222 if (RD->getNumVBases())
1223 Offs = GetVBPtrOffsetFromBases(RD);
1224 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001225 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001226
1227 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001228 if (hasVirtualBaseAdjustmentField(Inheritance))
1229 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001230
Reid Kleckner2341ae32013-04-11 18:13:19 +00001231 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001232}
1233
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001234llvm::Constant *
1235MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1236 CharUnits offset) {
1237 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1238 llvm::Constant *FirstField =
1239 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001240 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1241 CharUnits::Zero());
1242}
1243
1244llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1245 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1246}
1247
1248llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1249 QualType MPType) {
1250 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1251 const ValueDecl *MPD = MP.getMemberPointerDecl();
1252 if (!MPD)
1253 return EmitNullMemberPointer(MPT);
1254
1255 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1256
1257 // FIXME PR15713: Support virtual inheritance paths.
1258
1259 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1260 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1261 MD, ThisAdjustment);
1262
1263 CharUnits FieldOffset =
1264 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1265 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001266}
1267
1268llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001269MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1270 const CXXMethodDecl *MD,
1271 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001272 assert(MD->isInstance() && "Member function must not be static!");
1273 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001274 CodeGenTypes &Types = CGM.getTypes();
1275
1276 llvm::Constant *FirstField;
1277 if (MD->isVirtual()) {
1278 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1279 // the right offset.
1280 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1281 } else {
1282 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1283 llvm::Type *Ty;
1284 // Check whether the function has a computable LLVM signature.
1285 if (Types.isFuncTypeConvertible(FPT)) {
1286 // The function has a computable LLVM signature; use the correct type.
1287 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1288 } else {
1289 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1290 // function type is incomplete.
1291 Ty = CGM.PtrDiffTy;
1292 }
1293 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1294 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1295 }
1296
1297 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001298 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1299 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001300}
1301
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001302/// Member pointers are the same if they're either bitwise identical *or* both
1303/// null. Null-ness for function members is determined by the first field,
1304/// while for data member pointers we must compare all fields.
1305llvm::Value *
1306MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1307 llvm::Value *L,
1308 llvm::Value *R,
1309 const MemberPointerType *MPT,
1310 bool Inequality) {
1311 CGBuilderTy &Builder = CGF.Builder;
1312
1313 // Handle != comparisons by switching the sense of all boolean operations.
1314 llvm::ICmpInst::Predicate Eq;
1315 llvm::Instruction::BinaryOps And, Or;
1316 if (Inequality) {
1317 Eq = llvm::ICmpInst::ICMP_NE;
1318 And = llvm::Instruction::Or;
1319 Or = llvm::Instruction::And;
1320 } else {
1321 Eq = llvm::ICmpInst::ICMP_EQ;
1322 And = llvm::Instruction::And;
1323 Or = llvm::Instruction::Or;
1324 }
1325
1326 // If this is a single field member pointer (single inheritance), this is a
1327 // single icmp.
1328 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1329 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001330 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001331 return Builder.CreateICmp(Eq, L, R);
1332
1333 // Compare the first field.
1334 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1335 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1336 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1337
1338 // Compare everything other than the first field.
1339 llvm::Value *Res = 0;
1340 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1341 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1342 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1343 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1344 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1345 if (Res)
1346 Res = Builder.CreateBinOp(And, Res, Cmp);
1347 else
1348 Res = Cmp;
1349 }
1350
1351 // Check if the first field is 0 if this is a function pointer.
1352 if (MPT->isMemberFunctionPointer()) {
1353 // (l1 == r1 && ...) || l0 == 0
1354 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1355 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1356 Res = Builder.CreateBinOp(Or, Res, IsZero);
1357 }
1358
1359 // Combine the comparison of the first field, which must always be true for
1360 // this comparison to succeeed.
1361 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1362}
1363
Reid Kleckner407e8b62013-03-22 19:02:54 +00001364llvm::Value *
1365MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1366 llvm::Value *MemPtr,
1367 const MemberPointerType *MPT) {
1368 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001369 llvm::SmallVector<llvm::Constant *, 4> fields;
1370 // We only need one field for member functions.
1371 if (MPT->isMemberFunctionPointer())
1372 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1373 else
1374 GetNullMemberPointerFields(MPT, fields);
1375 assert(!fields.empty());
1376 llvm::Value *FirstField = MemPtr;
1377 if (MemPtr->getType()->isStructTy())
1378 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1379 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001380
Reid Kleckner2341ae32013-04-11 18:13:19 +00001381 // For function member pointers, we only need to test the function pointer
1382 // field. The other fields if any can be garbage.
1383 if (MPT->isMemberFunctionPointer())
1384 return Res;
1385
1386 // Otherwise, emit a series of compares and combine the results.
1387 for (int I = 1, E = fields.size(); I < E; ++I) {
1388 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1389 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1390 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1391 }
1392 return Res;
1393}
1394
Reid Kleckner452abac2013-05-09 21:01:17 +00001395bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1396 llvm::Constant *Val) {
1397 // Function pointers are null if the pointer in the first field is null.
1398 if (MPT->isMemberFunctionPointer()) {
1399 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1400 Val->getAggregateElement(0U) : Val;
1401 return FirstField->isNullValue();
1402 }
1403
1404 // If it's not a function pointer and it's zero initializable, we can easily
1405 // check zero.
1406 if (isZeroInitializable(MPT) && Val->isNullValue())
1407 return true;
1408
1409 // Otherwise, break down all the fields for comparison. Hopefully these
1410 // little Constants are reused, while a big null struct might not be.
1411 llvm::SmallVector<llvm::Constant *, 4> Fields;
1412 GetNullMemberPointerFields(MPT, Fields);
1413 if (Fields.size() == 1) {
1414 assert(Val->getType()->isIntegerTy());
1415 return Val == Fields[0];
1416 }
1417
1418 unsigned I, E;
1419 for (I = 0, E = Fields.size(); I != E; ++I) {
1420 if (Val->getAggregateElement(I) != Fields[I])
1421 break;
1422 }
1423 return I == E;
1424}
1425
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001426llvm::Value *
1427MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1428 llvm::Value *This,
1429 llvm::Value *VBTableOffset,
1430 llvm::Value *VBPtrOffset,
1431 llvm::Value **VBPtrOut) {
1432 CGBuilderTy &Builder = CGF.Builder;
1433 // Load the vbtable pointer from the vbptr in the instance.
1434 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1435 llvm::Value *VBPtr =
1436 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1437 if (VBPtrOut) *VBPtrOut = VBPtr;
1438 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1439 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1440
1441 // Load an i32 offset from the vb-table.
1442 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1443 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1444 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1445}
1446
Reid Kleckner2341ae32013-04-11 18:13:19 +00001447// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1448// it.
1449llvm::Value *
1450MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1451 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001452 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001453 llvm::Value *VBPtrOffset) {
1454 CGBuilderTy &Builder = CGF.Builder;
1455 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1456 llvm::BasicBlock *OriginalBB = 0;
1457 llvm::BasicBlock *SkipAdjustBB = 0;
1458 llvm::BasicBlock *VBaseAdjustBB = 0;
1459
1460 // In the unspecified inheritance model, there might not be a vbtable at all,
1461 // in which case we need to skip the virtual base lookup. If there is a
1462 // vbtable, the first entry is a no-op entry that gives back the original
1463 // base, so look for a virtual base adjustment offset of zero.
1464 if (VBPtrOffset) {
1465 OriginalBB = Builder.GetInsertBlock();
1466 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1467 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1468 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001469 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001470 "memptr.is_vbase");
1471 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1472 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001473 }
1474
Reid Kleckner2341ae32013-04-11 18:13:19 +00001475 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1476 // know the vbptr offset.
1477 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001478 CharUnits offs = CharUnits::Zero();
1479 if (RD->getNumVBases()) {
1480 offs = GetVBPtrOffsetFromBases(RD);
1481 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001482 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1483 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001484 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001485 llvm::Value *VBaseOffs =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001486 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001487 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1488
1489 // Merge control flow with the case where we didn't have to adjust.
1490 if (VBaseAdjustBB) {
1491 Builder.CreateBr(SkipAdjustBB);
1492 CGF.EmitBlock(SkipAdjustBB);
1493 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1494 Phi->addIncoming(Base, OriginalBB);
1495 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1496 return Phi;
1497 }
1498 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001499}
1500
1501llvm::Value *
1502MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1503 llvm::Value *Base,
1504 llvm::Value *MemPtr,
1505 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001506 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001507 unsigned AS = Base->getType()->getPointerAddressSpace();
1508 llvm::Type *PType =
1509 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1510 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001511 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1512 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001513
Reid Kleckner2341ae32013-04-11 18:13:19 +00001514 // Extract the fields we need, regardless of model. We'll apply them if we
1515 // have them.
1516 llvm::Value *FieldOffset = MemPtr;
1517 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1518 llvm::Value *VBPtrOffset = 0;
1519 if (MemPtr->getType()->isStructTy()) {
1520 // We need to extract values.
1521 unsigned I = 0;
1522 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1523 if (hasVBPtrOffsetField(Inheritance))
1524 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1525 if (hasVirtualBaseAdjustmentField(Inheritance))
1526 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001527 }
1528
Reid Kleckner2341ae32013-04-11 18:13:19 +00001529 if (VirtualBaseAdjustmentOffset) {
1530 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1531 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001532 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001533 llvm::Value *Addr =
1534 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001535
1536 // Cast the address to the appropriate pointer type, adopting the address
1537 // space of the base pointer.
1538 return Builder.CreateBitCast(Addr, PType);
1539}
1540
Reid Kleckner452abac2013-05-09 21:01:17 +00001541static MSInheritanceModel
1542getInheritanceFromMemptr(const MemberPointerType *MPT) {
1543 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1544}
1545
1546llvm::Value *
1547MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1548 const CastExpr *E,
1549 llvm::Value *Src) {
1550 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1551 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1552 E->getCastKind() == CK_ReinterpretMemberPointer);
1553
1554 // Use constant emission if we can.
1555 if (isa<llvm::Constant>(Src))
1556 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1557
1558 // We may be adding or dropping fields from the member pointer, so we need
1559 // both types and the inheritance models of both records.
1560 const MemberPointerType *SrcTy =
1561 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1562 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1563 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1564 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1565 bool IsFunc = SrcTy->isMemberFunctionPointer();
1566
1567 // If the classes use the same null representation, reinterpret_cast is a nop.
1568 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1569 if (IsReinterpret && (IsFunc ||
1570 nullFieldOffsetIsZero(SrcInheritance) ==
1571 nullFieldOffsetIsZero(DstInheritance)))
1572 return Src;
1573
1574 CGBuilderTy &Builder = CGF.Builder;
1575
1576 // Branch past the conversion if Src is null.
1577 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1578 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1579
1580 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1581 // pointer value of the destination type.
1582 if (IsReinterpret) {
1583 // For reinterpret casts, sema ensures that src and dst are both functions
1584 // or data and have the same size, which means the LLVM types should match.
1585 assert(Src->getType() == DstNull->getType());
1586 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1587 }
1588
1589 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1590 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1591 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1592 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1593 CGF.EmitBlock(ConvertBB);
1594
1595 // Decompose src.
1596 llvm::Value *FirstField = Src;
1597 llvm::Value *NonVirtualBaseAdjustment = 0;
1598 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1599 llvm::Value *VBPtrOffset = 0;
1600 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1601 // We need to extract values.
1602 unsigned I = 0;
1603 FirstField = Builder.CreateExtractValue(Src, I++);
1604 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1605 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1606 if (hasVBPtrOffsetField(SrcInheritance))
1607 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1608 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1609 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1610 }
1611
1612 // For data pointers, we adjust the field offset directly. For functions, we
1613 // have a separate field.
1614 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1615 if (Adj) {
1616 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1617 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1618 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1619 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1620 NVAdjustField = getZeroInt();
1621 if (isDerivedToBase)
1622 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1623 else
1624 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1625 }
1626
1627 // FIXME PR15713: Support conversions through virtually derived classes.
1628
1629 // Recompose dst from the null struct and the adjusted fields from src.
1630 llvm::Value *Dst;
1631 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1632 Dst = FirstField;
1633 } else {
1634 Dst = llvm::UndefValue::get(DstNull->getType());
1635 unsigned Idx = 0;
1636 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1637 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1638 Dst = Builder.CreateInsertValue(
1639 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1640 if (hasVBPtrOffsetField(DstInheritance))
1641 Dst = Builder.CreateInsertValue(
1642 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1643 if (hasVirtualBaseAdjustmentField(DstInheritance))
1644 Dst = Builder.CreateInsertValue(
1645 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1646 }
1647 Builder.CreateBr(ContinueBB);
1648
1649 // In the continuation, choose between DstNull and Dst.
1650 CGF.EmitBlock(ContinueBB);
1651 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1652 Phi->addIncoming(DstNull, OriginalBB);
1653 Phi->addIncoming(Dst, ConvertBB);
1654 return Phi;
1655}
1656
1657llvm::Constant *
1658MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1659 llvm::Constant *Src) {
1660 const MemberPointerType *SrcTy =
1661 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1662 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1663
1664 // If src is null, emit a new null for dst. We can't return src because dst
1665 // might have a new representation.
1666 if (MemberPointerConstantIsNull(SrcTy, Src))
1667 return EmitNullMemberPointer(DstTy);
1668
1669 // We don't need to do anything for reinterpret_casts of non-null member
1670 // pointers. We should only get here when the two type representations have
1671 // the same size.
1672 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1673 return Src;
1674
1675 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1676 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1677
1678 // Decompose src.
1679 llvm::Constant *FirstField = Src;
1680 llvm::Constant *NonVirtualBaseAdjustment = 0;
1681 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1682 llvm::Constant *VBPtrOffset = 0;
1683 bool IsFunc = SrcTy->isMemberFunctionPointer();
1684 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1685 // We need to extract values.
1686 unsigned I = 0;
1687 FirstField = Src->getAggregateElement(I++);
1688 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1689 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1690 if (hasVBPtrOffsetField(SrcInheritance))
1691 VBPtrOffset = Src->getAggregateElement(I++);
1692 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1693 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1694 }
1695
1696 // For data pointers, we adjust the field offset directly. For functions, we
1697 // have a separate field.
1698 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1699 if (Adj) {
1700 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1701 llvm::Constant *&NVAdjustField =
1702 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1703 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1704 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1705 NVAdjustField = getZeroInt();
1706 if (IsDerivedToBase)
1707 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1708 else
1709 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1710 }
1711
1712 // FIXME PR15713: Support conversions through virtually derived classes.
1713
1714 // Recompose dst from the null struct and the adjusted fields from src.
1715 if (hasOnlyOneField(IsFunc, DstInheritance))
1716 return FirstField;
1717
1718 llvm::SmallVector<llvm::Constant *, 4> Fields;
1719 Fields.push_back(FirstField);
1720 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1721 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1722 if (hasVBPtrOffsetField(DstInheritance))
1723 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1724 if (hasVirtualBaseAdjustmentField(DstInheritance))
1725 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1726 return llvm::ConstantStruct::getAnon(Fields);
1727}
1728
Reid Kleckner2341ae32013-04-11 18:13:19 +00001729llvm::Value *
1730MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1731 llvm::Value *&This,
1732 llvm::Value *MemPtr,
1733 const MemberPointerType *MPT) {
1734 assert(MPT->isMemberFunctionPointer());
1735 const FunctionProtoType *FPT =
1736 MPT->getPointeeType()->castAs<FunctionProtoType>();
1737 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1738 llvm::FunctionType *FTy =
1739 CGM.getTypes().GetFunctionType(
1740 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1741 CGBuilderTy &Builder = CGF.Builder;
1742
1743 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1744
1745 // Extract the fields we need, regardless of model. We'll apply them if we
1746 // have them.
1747 llvm::Value *FunctionPointer = MemPtr;
1748 llvm::Value *NonVirtualBaseAdjustment = NULL;
1749 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1750 llvm::Value *VBPtrOffset = NULL;
1751 if (MemPtr->getType()->isStructTy()) {
1752 // We need to extract values.
1753 unsigned I = 0;
1754 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001755 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1756 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001757 if (hasVBPtrOffsetField(Inheritance))
1758 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001759 if (hasVirtualBaseAdjustmentField(Inheritance))
1760 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1761 }
1762
1763 if (VirtualBaseAdjustmentOffset) {
1764 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1765 VBPtrOffset);
1766 }
1767
1768 if (NonVirtualBaseAdjustment) {
1769 // Apply the adjustment and cast back to the original struct type.
1770 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1771 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1772 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1773 }
1774
1775 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1776}
1777
Charles Davis53c59df2010-08-16 03:33:14 +00001778CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00001779 return new MicrosoftCXXABI(CGM);
1780}
1781