blob: ee928c5b59006c11b8f87110d7430a547af98cc7 [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
Hans Wennborgfeedf852013-11-21 00:15:56 +000053 bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
54
John McCall82fb8922012-09-25 10:10:39 +000055 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
56 llvm::Value *ptr,
57 QualType type);
58
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000059 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
60 llvm::Value *This,
61 const CXXRecordDecl *ClassDecl,
62 const CXXRecordDecl *BaseClassDecl);
63
John McCall5d865c322010-08-31 07:33:07 +000064 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
65 CXXCtorType Type,
66 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000067 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000068
Reid Kleckner7810af02013-06-19 15:20:38 +000069 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
70 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000071
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000072 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
73 const CXXRecordDecl *RD);
74
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000075 void EmitCXXConstructors(const CXXConstructorDecl *D);
76
Reid Klecknere7de47e2013-07-22 13:51:44 +000077 // Background on MSVC destructors
78 // ==============================
79 //
80 // Both Itanium and MSVC ABIs have destructor variants. The variant names
81 // roughly correspond in the following way:
82 // Itanium Microsoft
83 // Base -> no name, just ~Class
84 // Complete -> vbase destructor
85 // Deleting -> scalar deleting destructor
86 // vector deleting destructor
87 //
88 // The base and complete destructors are the same as in Itanium, although the
89 // complete destructor does not accept a VTT parameter when there are virtual
90 // bases. A separate mechanism involving vtordisps is used to ensure that
91 // virtual methods of destroyed subobjects are not called.
92 //
93 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
94 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
95 // pointer points to an array. The scalar deleting destructor assumes that
96 // bit 2 is zero, and therefore does not contain a loop.
97 //
98 // For virtual destructors, only one entry is reserved in the vftable, and it
99 // always points to the vector deleting destructor. The vector deleting
100 // destructor is the most general, so it can be used to destroy objects in
101 // place, delete single heap objects, or delete arrays.
102 //
103 // A TU defining a non-inline destructor is only guaranteed to emit a base
104 // destructor, and all of the other variants are emitted on an as-needed basis
105 // in COMDATs. Because a non-base destructor can be emitted in a TU that
106 // lacks a definition for the destructor, non-base destructors must always
107 // delegate to or alias the base destructor.
108
109 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000110 CXXDtorType Type,
111 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000112 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000113
Reid Klecknere7de47e2013-07-22 13:51:44 +0000114 /// Non-base dtors should be emitted as delegating thunks in this ABI.
115 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
116 CXXDtorType DT) const {
117 return DT != Dtor_Base;
118 }
119
120 void EmitCXXDestructors(const CXXDestructorDecl *D);
121
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000122 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
123 MD = MD->getCanonicalDecl();
124 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000125 MicrosoftVTableContext::MethodVFTableLocation ML =
126 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000127 // The vbases might be ordered differently in the final overrider object
128 // and the complete object, so the "this" argument may sometimes point to
129 // memory that has no particular type (e.g. past the complete object).
130 // In this case, we just use a generic pointer type.
131 // FIXME: might want to have a more precise type in the non-virtual
132 // multiple inheritance case.
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000133 if (ML.VBase || !ML.VFPtrOffset.isZero())
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000134 return 0;
135 }
136 return MD->getParent();
137 }
138
139 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
140 GlobalDecl GD,
141 llvm::Value *This);
142
John McCall5d865c322010-08-31 07:33:07 +0000143 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
144 QualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +0000145 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000146
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000147 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
148 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
149
John McCall0f999f32012-09-25 08:00:39 +0000150 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000151
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000152 void EmitConstructorCall(CodeGenFunction &CGF,
153 const CXXConstructorDecl *D, CXXCtorType Type,
154 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000155 llvm::Value *This,
156 CallExpr::const_arg_iterator ArgBeg,
157 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000158
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000159 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
160
161 llvm::Value *getVTableAddressPointInStructor(
162 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
163 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
164 bool &NeedsVirtualOffset);
165
166 llvm::Constant *
167 getVTableAddressPointForConstExpr(BaseSubobject Base,
168 const CXXRecordDecl *VTableClass);
169
170 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
171 CharUnits VPtrOffset);
172
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000173 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
174 llvm::Value *This, llvm::Type *Ty);
175
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000176 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
177 const CXXDestructorDecl *Dtor,
178 CXXDtorType DtorType, SourceLocation CallLoc,
179 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000180
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000181 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
182 CallArgList &CallArgs) {
183 assert(GD.getDtorType() == Dtor_Deleting &&
184 "Only deleting destructor thunks are available in this ABI");
185 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
186 CGM.getContext().IntTy);
187 }
188
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000189 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000190
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000191 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
192 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
193 }
194
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000195 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
196 const ThisAdjustment &TA);
197
198 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
199 const ReturnAdjustment &RA);
200
John McCallc84ed6a2012-05-01 06:13:13 +0000201 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
202 llvm::GlobalVariable *DeclPtr,
203 bool PerformInit);
204
John McCall29036752011-01-27 02:46:02 +0000205 // ==== Notes on array cookies =========
206 //
207 // MSVC seems to only use cookies when the class has a destructor; a
208 // two-argument usual array deallocation function isn't sufficient.
209 //
210 // For example, this code prints "100" and "1":
211 // struct A {
212 // char x;
213 // void *operator new[](size_t sz) {
214 // printf("%u\n", sz);
215 // return malloc(sz);
216 // }
217 // void operator delete[](void *p, size_t sz) {
218 // printf("%u\n", sz);
219 // free(p);
220 // }
221 // };
222 // int main() {
223 // A *p = new A[100];
224 // delete[] p;
225 // }
226 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000227
228 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
229 bool requiresArrayCookie(const CXXNewExpr *expr);
230 CharUnits getArrayCookieSizeImpl(QualType type);
231 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
232 llvm::Value *NewPtr,
233 llvm::Value *NumElements,
234 const CXXNewExpr *expr,
235 QualType ElementType);
236 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
237 llvm::Value *allocPtr,
238 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000239
240private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000241 MicrosoftMangleContext &getMangleContext() {
242 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
243 }
244
Reid Kleckner2341ae32013-04-11 18:13:19 +0000245 llvm::Constant *getZeroInt() {
246 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000247 }
248
Reid Kleckner2341ae32013-04-11 18:13:19 +0000249 llvm::Constant *getAllOnesInt() {
250 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000251 }
252
Reid Kleckner452abac2013-05-09 21:01:17 +0000253 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
254 return C ? C : getZeroInt();
255 }
256
257 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
258 return C ? C : getZeroInt();
259 }
260
Reid Kleckner2341ae32013-04-11 18:13:19 +0000261 void
262 GetNullMemberPointerFields(const MemberPointerType *MPT,
263 llvm::SmallVectorImpl<llvm::Constant *> &fields);
264
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000265 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
266 /// it is reusing a vbptr from a non-virtual base. RD must have morally
267 /// virtual bases.
268 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
269
270 /// \brief Shared code for virtual base adjustment. Returns the offset from
271 /// the vbptr to the virtual base. Optionally returns the address of the
272 /// vbptr itself.
273 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
274 llvm::Value *Base,
275 llvm::Value *VBPtrOffset,
276 llvm::Value *VBTableOffset,
277 llvm::Value **VBPtr = 0);
278
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000279 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
280 llvm::Value *Base,
281 int32_t VBPtrOffset,
282 int32_t VBTableOffset,
283 llvm::Value **VBPtr = 0) {
284 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
285 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
286 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
287 }
288
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000289 /// \brief Performs a full virtual base adjustment. Used to dereference
290 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000291 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
292 llvm::Value *Base,
293 llvm::Value *VirtualBaseAdjustmentOffset,
294 llvm::Value *VBPtrOffset /* optional */);
295
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000296 /// \brief Emits a full member pointer with the fields common to data and
297 /// function member pointers.
298 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
299 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000300 const CXXRecordDecl *RD,
301 CharUnits NonVirtualBaseAdjustment);
302
303 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
304 const CXXMethodDecl *MD,
305 CharUnits NonVirtualBaseAdjustment);
306
307 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
308 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000309
Reid Kleckner7810af02013-06-19 15:20:38 +0000310 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
311 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
312
313 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
314 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
315
Hans Wennborg88497d62013-11-15 17:24:45 +0000316 /// \brief Generate a thunk for calling a virtual member function MD.
317 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
318 StringRef ThunkName);
319
Reid Kleckner407e8b62013-03-22 19:02:54 +0000320public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000321 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
322
323 virtual bool isZeroInitializable(const MemberPointerType *MPT);
324
Reid Kleckner407e8b62013-03-22 19:02:54 +0000325 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
326
327 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
328 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000329 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
330 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000331
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000332 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
333 llvm::Value *L,
334 llvm::Value *R,
335 const MemberPointerType *MPT,
336 bool Inequality);
337
Reid Kleckner407e8b62013-03-22 19:02:54 +0000338 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
339 llvm::Value *MemPtr,
340 const MemberPointerType *MPT);
341
342 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
343 llvm::Value *Base,
344 llvm::Value *MemPtr,
345 const MemberPointerType *MPT);
346
Reid Kleckner452abac2013-05-09 21:01:17 +0000347 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
348 const CastExpr *E,
349 llvm::Value *Src);
350
351 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
352 llvm::Constant *Src);
353
Reid Kleckner2341ae32013-04-11 18:13:19 +0000354 virtual llvm::Value *
355 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
356 llvm::Value *&This,
357 llvm::Value *MemPtr,
358 const MemberPointerType *MPT);
359
Reid Kleckner7810af02013-06-19 15:20:38 +0000360private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000361 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
362 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
363 /// \brief All the vftables that have been referenced.
364 VFTablesMapTy VFTablesMap;
365
366 /// \brief This set holds the record decls we've deferred vtable emission for.
367 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
368
369
370 /// \brief All the vbtables which have been referenced.
Reid Kleckner7810af02013-06-19 15:20:38 +0000371 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000372
373 /// Info on the global variable used to guard initialization of static locals.
374 /// The BitIndex field is only used for externally invisible declarations.
375 struct GuardInfo {
376 GuardInfo() : Guard(0), BitIndex(0) {}
377 llvm::GlobalVariable *Guard;
378 unsigned BitIndex;
379 };
380
381 /// Map from DeclContext to the current guard variable. We assume that the
382 /// AST is visited in source code order.
383 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000384};
385
386}
387
John McCall82fb8922012-09-25 10:10:39 +0000388llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
389 llvm::Value *ptr,
390 QualType type) {
391 // FIXME: implement
392 return ptr;
393}
394
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000395/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
396/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
397static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
398 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
399 E = RD->bases_end(); I != E; ++I) {
400 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
401 if (!I->isVirtual() && Base->getNumVBases() > 0)
402 return Base;
403 }
404 llvm_unreachable("RD must have an nv base with vbases");
405}
406
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000407CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
408 assert(RD->getNumVBases());
409 CharUnits Total = CharUnits::Zero();
410 while (RD) {
411 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
412 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
413 // -1 is the sentinel for no vbptr.
414 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
415 Total += VBPtrOffset;
416 break;
417 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000418 RD = FindFirstNVBaseWithVBases(RD);
419 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000420 }
421 return Total;
422}
423
424llvm::Value *
425MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
426 llvm::Value *This,
427 const CXXRecordDecl *ClassDecl,
428 const CXXRecordDecl *BaseClassDecl) {
429 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
430 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000431 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000432 CharUnits VBTableChars =
433 IntSize *
434 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000435 llvm::Value *VBTableOffset =
436 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
437
438 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000439 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000440 VBPtrToNewBase =
441 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
442 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
443}
444
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000445bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
446 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000447}
448
449void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
450 CXXCtorType Type,
451 CanQualType &ResTy,
452 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000453 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000454
455 const CXXRecordDecl *Class = Ctor->getParent();
456 if (Class->getNumVBases()) {
457 // Constructors of classes with virtual bases take an implicit parameter.
458 ArgTys.push_back(CGM.getContext().IntTy);
459 }
460}
461
Reid Kleckner7810af02013-06-19 15:20:38 +0000462llvm::BasicBlock *
463MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
464 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000465 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
466 assert(IsMostDerivedClass &&
467 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000468 llvm::Value *IsCompleteObject =
469 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000470
471 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
472 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
473 CGF.Builder.CreateCondBr(IsCompleteObject,
474 CallVbaseCtorsBB, SkipVbaseCtorsBB);
475
476 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000477
478 // Fill in the vbtable pointers here.
479 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000480
481 // CGF will put the base ctor calls in this basic block for us later.
482
483 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000484}
485
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000486void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
487 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
488 // In most cases, an override for a vbase virtual method can adjust
489 // the "this" parameter by applying a constant offset.
490 // However, this is not enough while a constructor or a destructor of some
491 // class X is being executed if all the following conditions are met:
492 // - X has virtual bases, (1)
493 // - X overrides a virtual method M of a vbase Y, (2)
494 // - X itself is a vbase of the most derived class.
495 //
496 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
497 // which holds the extra amount of "this" adjustment we must do when we use
498 // the X vftables (i.e. during X ctor or dtor).
499 // Outside the ctors and dtors, the values of vtorDisps are zero.
500
501 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
502 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
503 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
504 CGBuilderTy &Builder = CGF.Builder;
505
506 unsigned AS =
507 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
508 llvm::Value *Int8This = 0; // Initialize lazily.
509
510 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
511 I != E; ++I) {
512 if (!I->second.hasVtorDisp())
513 continue;
514
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000515 llvm::Value *VBaseOffset =
516 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000517 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
518 // just to Trunc back immediately.
519 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
520 uint64_t ConstantVBaseOffset =
521 Layout.getVBaseClassOffset(I->first).getQuantity();
522
523 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
524 llvm::Value *VtorDispValue = Builder.CreateSub(
525 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
526 "vtordisp.value");
527
528 if (!Int8This)
529 Int8This = Builder.CreateBitCast(getThisValue(CGF),
530 CGF.Int8Ty->getPointerTo(AS));
531 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
532 // vtorDisp is always the 32-bits before the vbase in the class layout.
533 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
534 VtorDispPtr = Builder.CreateBitCast(
535 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
536
537 Builder.CreateStore(VtorDispValue, VtorDispPtr);
538 }
539}
540
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000541void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
542 // There's only one constructor type in this ABI.
543 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
544}
545
Reid Kleckner7810af02013-06-19 15:20:38 +0000546void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
547 const CXXRecordDecl *RD) {
548 llvm::Value *ThisInt8Ptr =
549 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
550
551 const VBTableVector &VBTables = EnumerateVBTables(RD);
552 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
553 I != E; ++I) {
554 const ASTRecordLayout &SubobjectLayout =
555 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
556 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
557 SubobjectLayout.getVBPtrOffset()).getQuantity();
558 llvm::Value *VBPtr =
559 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
560 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
561 "vbptr." + I->ReusingBase->getName());
562 CGF.Builder.CreateStore(I->GV, VBPtr);
563 }
564}
565
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000566void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
567 CXXDtorType Type,
568 CanQualType &ResTy,
569 SmallVectorImpl<CanQualType> &ArgTys) {
570 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000571
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000572 // TODO: 'for base' flag
573
574 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000575 // The scalar deleting destructor takes an implicit int parameter.
576 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000577 }
578}
579
Reid Klecknere7de47e2013-07-22 13:51:44 +0000580void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
581 // The TU defining a dtor is only guaranteed to emit a base destructor. All
582 // other destructor variants are delegating thunks.
583 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
584}
585
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000586llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
587 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
588 GD = GD.getCanonicalDecl();
589 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000590 // FIXME: consider splitting the vdtor vs regular method code into two
591 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000592
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000593 GlobalDecl LookupGD = GD;
594 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
595 // Complete dtors take a pointer to the complete object,
596 // thus don't need adjustment.
597 if (GD.getDtorType() == Dtor_Complete)
598 return This;
599
600 // There's only Dtor_Deleting in vftable but it shares the this adjustment
601 // with the base one, so look up the deleting one instead.
602 LookupGD = GlobalDecl(DD, Dtor_Deleting);
603 }
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000604 MicrosoftVTableContext::MethodVFTableLocation ML =
605 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000606
607 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
608 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000609 CharUnits StaticOffset = ML.VFPtrOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000610 if (ML.VBase) {
611 bool AvoidVirtualOffset = false;
612 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
613 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000614 // same record type or another destructor of a more derived type;
615 // or a constructor of the same record type if an exception is thrown.
616 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
617 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000618 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000619 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000620
621 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000622 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
623 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
624 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
625 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
626 // We're calling the main base dtor from a complete structor,
627 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000628 AvoidVirtualOffset = true;
629 } else {
630 // Let's see if we try to call a destructor of a non-virtual base.
631 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
632 E = CurRD->bases_end(); I != E; ++I) {
633 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
634 continue;
635 // If we call a base destructor for a non-virtual base, we statically
636 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000637 // The total offset should reflect the adjustment done by
638 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000639 AvoidVirtualOffset = true;
640 break;
641 }
642 }
643 }
644
645 if (AvoidVirtualOffset) {
646 const ASTRecordLayout &Layout =
647 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000648 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
649 } else {
650 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000651 llvm::Value *VBaseOffset =
652 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000653 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
654 }
655 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000656 if (!StaticOffset.isZero()) {
657 assert(StaticOffset.isPositive());
658 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000659 if (ML.VBase) {
660 // Non-virtual adjustment might result in a pointer outside the allocated
661 // object, e.g. if the final overrider class is laid out after the virtual
662 // base that declares a method in the most derived class.
663 // FIXME: Update the code that emits this adjustment in thunks prologues.
664 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
665 } else {
666 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
667 StaticOffset.getQuantity());
668 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000669 }
670 return This;
671}
672
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000673static bool IsDeletingDtor(GlobalDecl GD) {
674 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
675 if (isa<CXXDestructorDecl>(MD)) {
676 return GD.getDtorType() == Dtor_Deleting;
677 }
678 return false;
679}
680
John McCall0f999f32012-09-25 08:00:39 +0000681void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
682 QualType &ResTy,
683 FunctionArgList &Params) {
684 BuildThisParam(CGF, Params);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000685
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000686 ASTContext &Context = getContext();
687 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
688 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
689 ImplicitParamDecl *IsMostDerived
690 = ImplicitParamDecl::Create(Context, 0,
691 CGF.CurGD.getDecl()->getLocation(),
692 &Context.Idents.get("is_most_derived"),
693 Context.IntTy);
694 Params.push_back(IsMostDerived);
695 getStructorImplicitParamDecl(CGF) = IsMostDerived;
696 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000697 ImplicitParamDecl *ShouldDelete
698 = ImplicitParamDecl::Create(Context, 0,
699 CGF.CurGD.getDecl()->getLocation(),
700 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000701 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000702 Params.push_back(ShouldDelete);
703 getStructorImplicitParamDecl(CGF) = ShouldDelete;
704 }
John McCall0f999f32012-09-25 08:00:39 +0000705}
706
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000707llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
708 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
709 GD = GD.getCanonicalDecl();
710 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000711
712 GlobalDecl LookupGD = GD;
713 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
714 // Complete destructors take a pointer to the complete object as a
715 // parameter, thus don't need this adjustment.
716 if (GD.getDtorType() == Dtor_Complete)
717 return This;
718
719 // There's no Dtor_Base in vftable but it shares the this adjustment with
720 // the deleting one, so look it up instead.
721 LookupGD = GlobalDecl(DD, Dtor_Deleting);
722 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000723
724 // In this ABI, every virtual function takes a pointer to one of the
725 // subobjects that first defines it as the 'this' parameter, rather than a
726 // pointer to ther final overrider subobject. Thus, we need to adjust it back
727 // to the final overrider subobject before use.
728 // See comments in the MicrosoftVFTableContext implementation for the details.
729
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000730 MicrosoftVTableContext::MethodVFTableLocation ML =
731 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000732 CharUnits Adjustment = ML.VFPtrOffset;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000733 if (ML.VBase) {
734 const ASTRecordLayout &DerivedLayout =
735 CGF.getContext().getASTRecordLayout(MD->getParent());
736 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
737 }
738
739 if (Adjustment.isZero())
740 return This;
741
742 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
743 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
744 *thisTy = This->getType();
745
746 This = CGF.Builder.CreateBitCast(This, charPtrTy);
747 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000748 This =
749 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000750 return CGF.Builder.CreateBitCast(This, thisTy);
751}
752
John McCall0f999f32012-09-25 08:00:39 +0000753void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
754 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000755
756 /// If this is a function that the ABI specifies returns 'this', initialize
757 /// the return slot to 'this' at the start of the function.
758 ///
759 /// Unlike the setting of return types, this is done within the ABI
760 /// implementation instead of by clients of CGCXXABI because:
761 /// 1) getThisValue is currently protected
762 /// 2) in theory, an ABI could implement 'this' returns some other way;
763 /// HasThisReturn only specifies a contract, not the implementation
764 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000765 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000766
767 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
768 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
769 assert(getStructorImplicitParamDecl(CGF) &&
770 "no implicit parameter for a constructor with virtual bases?");
771 getStructorImplicitParamValue(CGF)
772 = CGF.Builder.CreateLoad(
773 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
774 "is_most_derived");
775 }
776
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000777 if (IsDeletingDtor(CGF.CurGD)) {
778 assert(getStructorImplicitParamDecl(CGF) &&
779 "no implicit parameter for a deleting destructor?");
780 getStructorImplicitParamValue(CGF)
781 = CGF.Builder.CreateLoad(
782 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
783 "should_call_delete");
784 }
John McCall0f999f32012-09-25 08:00:39 +0000785}
786
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000787void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Linc467c872013-06-19 18:10:35 +0000788 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000789 CXXCtorType Type,
790 bool ForVirtualBase,
Stephen Linc467c872013-06-19 18:10:35 +0000791 bool Delegating,
792 llvm::Value *This,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000793 CallExpr::const_arg_iterator ArgBeg,
794 CallExpr::const_arg_iterator ArgEnd) {
795 assert(Type == Ctor_Complete || Type == Ctor_Base);
796 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
797
798 llvm::Value *ImplicitParam = 0;
799 QualType ImplicitParamTy;
800 if (D->getParent()->getNumVBases()) {
801 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
802 ImplicitParamTy = getContext().IntTy;
803 }
804
805 // FIXME: Provide a source location here.
Stephen Linc467c872013-06-19 18:10:35 +0000806 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000807 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000808}
809
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000810void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
811 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000812 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
813 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000814 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
815
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000816 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000817 E = VFPtrs.end(); I != E; ++I) {
818 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
819 if (VTable->hasInitializer())
820 continue;
821
822 const VTableLayout &VTLayout =
823 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
824 llvm::Constant *Init = CGVT.CreateVTableInitializer(
825 RD, VTLayout.vtable_component_begin(),
826 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
827 VTLayout.getNumVTableThunks());
828 VTable->setInitializer(Init);
829
830 VTable->setLinkage(Linkage);
831 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
832 }
833}
834
835llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
836 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
837 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
838 NeedsVirtualOffset = (NearestVBase != 0);
839
840 llvm::Value *VTableAddressPoint =
841 getAddrOfVTable(VTableClass, Base.getBaseOffset());
842 if (!VTableAddressPoint) {
843 assert(Base.getBase()->getNumVBases() &&
844 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
845 }
846 return VTableAddressPoint;
847}
848
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000849static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
850 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
851 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000852 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000853 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000854}
855
856llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
857 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
858 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
859 assert(VTable && "Couldn't find a vftable for the given base?");
860 return VTable;
861}
862
863llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
864 CharUnits VPtrOffset) {
865 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
866 // shouldn't be used in the given record type. We want to cache this result in
867 // VFTablesMap, thus a simple zero check is not sufficient.
868 VFTableIdTy ID(RD, VPtrOffset);
869 VFTablesMapTy::iterator I;
870 bool Inserted;
871 llvm::tie(I, Inserted) = VFTablesMap.insert(
872 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
873 if (!Inserted)
874 return I->second;
875
876 llvm::GlobalVariable *&VTable = I->second;
877
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000878 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
879 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
880 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000881
882 if (DeferredVFTables.insert(RD)) {
883 // We haven't processed this record type before.
884 // Queue up this v-table for possible deferred emission.
885 CGM.addDeferredVTable(RD);
886
887#ifndef NDEBUG
888 // Create all the vftables at once in order to make sure each vftable has
889 // a unique mangled name.
890 llvm::StringSet<> ObservedMangledNames;
891 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
892 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000893 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000894 if (!ObservedMangledNames.insert(Name.str()))
895 llvm_unreachable("Already saw this mangling before?");
896 }
897#endif
898 }
899
900 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
901 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
902 continue;
903
904 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
905 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000906 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000907 .getNumVTableComponents());
908
909 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000910 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000911 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
912 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
913 VTable->setUnnamedAddr(true);
914 break;
915 }
916
917 return VTable;
918}
919
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000920llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
921 GlobalDecl GD,
922 llvm::Value *This,
923 llvm::Type *Ty) {
924 GD = GD.getCanonicalDecl();
925 CGBuilderTy &Builder = CGF.Builder;
926
927 Ty = Ty->getPointerTo()->getPointerTo();
928 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
929 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
930
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000931 MicrosoftVTableContext::MethodVFTableLocation ML =
932 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000933 llvm::Value *VFuncPtr =
934 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
935 return Builder.CreateLoad(VFuncPtr);
936}
937
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000938void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
939 const CXXDestructorDecl *Dtor,
940 CXXDtorType DtorType,
941 SourceLocation CallLoc,
942 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000943 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
944
945 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000946 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000947 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000948 const CGFunctionInfo *FInfo =
949 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000950 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000951 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000952
953 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000954 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000955 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000956 DtorType == Dtor_Deleting);
957
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000958 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000959 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000960 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000961}
962
Reid Kleckner7810af02013-06-19 15:20:38 +0000963const VBTableVector &
964MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
965 // At this layer, we can key the cache off of a single class, which is much
966 // easier than caching at the GlobalVariable layer.
967 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
968 bool added;
969 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
970 VBTableVector &VBTables = I->second;
971 if (!added)
972 return VBTables;
973
974 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
975
976 return VBTables;
977}
978
Hans Wennborg88497d62013-11-15 17:24:45 +0000979llvm::Function *
980MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
981 StringRef ThunkName) {
982 // If the thunk has been generated previously, just return it.
983 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
984 return cast<llvm::Function>(GV);
985
986 // Create the llvm::Function.
987 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
988 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
989 llvm::Function *ThunkFn =
990 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
991 ThunkName.str(), &CGM.getModule());
992 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
993
Hans Wennborg88497d62013-11-15 17:24:45 +0000994 ThunkFn->setLinkage(MD->isExternallyVisible()
995 ? llvm::GlobalValue::LinkOnceODRLinkage
996 : llvm::GlobalValue::InternalLinkage);
997
998 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
999 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1000
1001 // Start codegen.
1002 CodeGenFunction CGF(CGM);
1003 CGF.StartThunk(ThunkFn, MD, FnInfo);
1004
1005 // Get to the Callee.
1006 llvm::Value *This = CGF.LoadCXXThis();
1007 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1008
1009 // Make the call and return the result.
1010 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1011
1012 return ThunkFn;
1013}
1014
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001015void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001016 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001017 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1018
Reid Kleckner7810af02013-06-19 15:20:38 +00001019 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
1020 I != E; ++I) {
1021 I->EmitVBTableDefinition(CGM, RD, Linkage);
1022 }
1023}
1024
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001025llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1026 llvm::Value *This,
1027 const ThisAdjustment &TA) {
1028 if (TA.isEmpty())
1029 return This;
1030
1031 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1032
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001033 if (!TA.Virtual.isEmpty()) {
1034 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1035 // Adjust the this argument based on the vtordisp value.
1036 llvm::Value *VtorDispPtr =
1037 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1038 VtorDispPtr =
1039 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1040 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1041 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1042
1043 if (TA.Virtual.Microsoft.VBPtrOffset) {
1044 // If the final overrider is defined in a virtual base other than the one
1045 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1046 // the vbtable of the derived class.
1047 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1048 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1049 llvm::Value *VBPtr;
1050 llvm::Value *VBaseOffset =
1051 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1052 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1053 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1054 }
1055 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001056
1057 if (TA.NonVirtual) {
1058 // Non-virtual adjustment might result in a pointer outside the allocated
1059 // object, e.g. if the final overrider class is laid out after the virtual
1060 // base that declares a method in the most derived class.
1061 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1062 }
1063
1064 // Don't need to bitcast back, the call CodeGen will handle this.
1065 return V;
1066}
1067
1068llvm::Value *
1069MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1070 const ReturnAdjustment &RA) {
1071 if (RA.isEmpty())
1072 return Ret;
1073
1074 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1075
1076 if (RA.Virtual.Microsoft.VBIndex) {
1077 assert(RA.Virtual.Microsoft.VBIndex > 0);
1078 int32_t IntSize =
1079 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1080 llvm::Value *VBPtr;
1081 llvm::Value *VBaseOffset =
1082 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1083 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1084 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1085 }
1086
1087 if (RA.NonVirtual)
1088 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1089
1090 // Cast back to the original type.
1091 return CGF.Builder.CreateBitCast(V, Ret->getType());
1092}
1093
John McCallb91cd662012-05-01 05:23:51 +00001094bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1095 QualType elementType) {
1096 // Microsoft seems to completely ignore the possibility of a
1097 // two-argument usual deallocation function.
1098 return elementType.isDestructedType();
1099}
1100
1101bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1102 // Microsoft seems to completely ignore the possibility of a
1103 // two-argument usual deallocation function.
1104 return expr->getAllocatedType().isDestructedType();
1105}
1106
1107CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1108 // The array cookie is always a size_t; we then pad that out to the
1109 // alignment of the element type.
1110 ASTContext &Ctx = getContext();
1111 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1112 Ctx.getTypeAlignInChars(type));
1113}
1114
1115llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1116 llvm::Value *allocPtr,
1117 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001118 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001119 llvm::Value *numElementsPtr =
1120 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1121 return CGF.Builder.CreateLoad(numElementsPtr);
1122}
1123
1124llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1125 llvm::Value *newPtr,
1126 llvm::Value *numElements,
1127 const CXXNewExpr *expr,
1128 QualType elementType) {
1129 assert(requiresArrayCookie(expr));
1130
1131 // The size of the cookie.
1132 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1133
1134 // Compute an offset to the cookie.
1135 llvm::Value *cookiePtr = newPtr;
1136
1137 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001138 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001139 llvm::Value *numElementsPtr
1140 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1141 CGF.Builder.CreateStore(numElements, numElementsPtr);
1142
1143 // Finally, compute a pointer to the actual data buffer by skipping
1144 // over the cookie completely.
1145 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1146 cookieSize.getQuantity());
1147}
1148
John McCallc84ed6a2012-05-01 06:13:13 +00001149void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001150 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001151 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001152 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1153 // threadsafe. Since the user may be linking in inline functions compiled by
1154 // cl.exe, there's no reason to provide a false sense of security by using
1155 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001156
Richard Smithdbf74ba2013-04-14 23:01:42 +00001157 if (D.getTLSKind())
1158 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1159
Reid Klecknerd8110b62013-09-10 20:14:30 +00001160 CGBuilderTy &Builder = CGF.Builder;
1161 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1162 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1163
1164 // Get the guard variable for this function if we have one already.
1165 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1166
1167 unsigned BitIndex;
1168 if (D.isExternallyVisible()) {
1169 // Externally visible variables have to be numbered in Sema to properly
1170 // handle unreachable VarDecls.
1171 BitIndex = getContext().getManglingNumber(&D);
1172 assert(BitIndex > 0);
1173 BitIndex--;
1174 } else {
1175 // Non-externally visible variables are numbered here in CodeGen.
1176 BitIndex = GI.BitIndex++;
1177 }
1178
1179 if (BitIndex >= 32) {
1180 if (D.isExternallyVisible())
1181 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1182 BitIndex %= 32;
1183 GI.Guard = 0;
1184 }
1185
1186 // Lazily create the i32 bitfield for this function.
1187 if (!GI.Guard) {
1188 // Mangle the name for the guard.
1189 SmallString<256> GuardName;
1190 {
1191 llvm::raw_svector_ostream Out(GuardName);
1192 getMangleContext().mangleStaticGuardVariable(&D, Out);
1193 Out.flush();
1194 }
1195
1196 // Create the guard variable with a zero-initializer. Just absorb linkage
1197 // and visibility from the guarded variable.
1198 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1199 GV->getLinkage(), Zero, GuardName.str());
1200 GI.Guard->setVisibility(GV->getVisibility());
1201 } else {
1202 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1203 "static local from the same function had different linkage");
1204 }
1205
1206 // Pseudo code for the test:
1207 // if (!(GuardVar & MyGuardBit)) {
1208 // GuardVar |= MyGuardBit;
1209 // ... initialize the object ...;
1210 // }
1211
1212 // Test our bit from the guard variable.
1213 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1214 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1215 llvm::Value *IsInitialized =
1216 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1217 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1218 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1219 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1220
1221 // Set our bit in the guard variable and emit the initializer and add a global
1222 // destructor if appropriate.
1223 CGF.EmitBlock(InitBlock);
1224 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1225 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1226 Builder.CreateBr(EndBlock);
1227
1228 // Continue.
1229 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001230}
1231
Reid Kleckner2341ae32013-04-11 18:13:19 +00001232// Member pointer helpers.
1233static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1234 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001235}
1236
Reid Kleckner452abac2013-05-09 21:01:17 +00001237static bool hasOnlyOneField(bool IsMemberFunction,
1238 MSInheritanceModel Inheritance) {
1239 return Inheritance <= MSIM_SinglePolymorphic ||
1240 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001241}
1242
Reid Kleckner2341ae32013-04-11 18:13:19 +00001243// Only member pointers to functions need a this adjustment, since it can be
1244// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001245static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001246 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001247 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001248}
1249
1250static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1251 return Inheritance >= MSIM_Virtual;
1252}
1253
1254// Use zero for the field offset of a null data member pointer if we can
1255// guarantee that zero is not a valid field offset, or if the member pointer has
1256// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1257// use zero for null. If there are multiple fields, we can use zero even if it
1258// is a valid field offset because null-ness testing will check the other
1259// fields.
1260static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1261 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1262}
1263
1264bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1265 // Null-ness for function memptrs only depends on the first field, which is
1266 // the function pointer. The rest don't matter, so we can zero initialize.
1267 if (MPT->isMemberFunctionPointer())
1268 return true;
1269
1270 // The virtual base adjustment field is always -1 for null, so if we have one
1271 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1272 // valid field offset.
1273 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1274 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1275 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1276 nullFieldOffsetIsZero(Inheritance));
1277}
1278
1279llvm::Type *
1280MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1281 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1282 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1283 llvm::SmallVector<llvm::Type *, 4> fields;
1284 if (MPT->isMemberFunctionPointer())
1285 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1286 else
1287 fields.push_back(CGM.IntTy); // FieldOffset
1288
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001289 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1290 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001291 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001292 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001293 fields.push_back(CGM.IntTy);
1294 if (hasVirtualBaseAdjustmentField(Inheritance))
1295 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1296
1297 if (fields.size() == 1)
1298 return fields[0];
1299 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1300}
1301
1302void MicrosoftCXXABI::
1303GetNullMemberPointerFields(const MemberPointerType *MPT,
1304 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1305 assert(fields.empty());
1306 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1307 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1308 if (MPT->isMemberFunctionPointer()) {
1309 // FunctionPointerOrVirtualThunk
1310 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1311 } else {
1312 if (nullFieldOffsetIsZero(Inheritance))
1313 fields.push_back(getZeroInt()); // FieldOffset
1314 else
1315 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001316 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001317
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001318 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1319 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001320 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001321 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001322 fields.push_back(getZeroInt());
1323 if (hasVirtualBaseAdjustmentField(Inheritance))
1324 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001325}
1326
1327llvm::Constant *
1328MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001329 llvm::SmallVector<llvm::Constant *, 4> fields;
1330 GetNullMemberPointerFields(MPT, fields);
1331 if (fields.size() == 1)
1332 return fields[0];
1333 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1334 assert(Res->getType() == ConvertMemberPointerType(MPT));
1335 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001336}
1337
1338llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001339MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1340 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001341 const CXXRecordDecl *RD,
1342 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001343{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001344 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001345
1346 // Single inheritance class member pointer are represented as scalars instead
1347 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001348 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001349 return FirstField;
1350
Reid Kleckner2341ae32013-04-11 18:13:19 +00001351 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001352 fields.push_back(FirstField);
1353
1354 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001355 fields.push_back(llvm::ConstantInt::get(
1356 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001357
Reid Kleckner2341ae32013-04-11 18:13:19 +00001358 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001359 CharUnits Offs = CharUnits::Zero();
1360 if (RD->getNumVBases())
1361 Offs = GetVBPtrOffsetFromBases(RD);
1362 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001363 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001364
1365 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001366 if (hasVirtualBaseAdjustmentField(Inheritance))
1367 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001368
Reid Kleckner2341ae32013-04-11 18:13:19 +00001369 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001370}
1371
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001372llvm::Constant *
1373MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1374 CharUnits offset) {
1375 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1376 llvm::Constant *FirstField =
1377 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001378 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1379 CharUnits::Zero());
1380}
1381
1382llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1383 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1384}
1385
1386llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1387 QualType MPType) {
1388 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1389 const ValueDecl *MPD = MP.getMemberPointerDecl();
1390 if (!MPD)
1391 return EmitNullMemberPointer(MPT);
1392
1393 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1394
1395 // FIXME PR15713: Support virtual inheritance paths.
1396
1397 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1398 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1399 MD, ThisAdjustment);
1400
1401 CharUnits FieldOffset =
1402 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1403 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001404}
1405
1406llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001407MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1408 const CXXMethodDecl *MD,
1409 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001410 assert(MD->isInstance() && "Member function must not be static!");
1411 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001412 CodeGenTypes &Types = CGM.getTypes();
1413
1414 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001415 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001416 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1417 llvm::Type *Ty;
1418 // Check whether the function has a computable LLVM signature.
1419 if (Types.isFuncTypeConvertible(FPT)) {
1420 // The function has a computable LLVM signature; use the correct type.
1421 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1422 } else {
1423 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1424 // function type is incomplete.
1425 Ty = CGM.PtrDiffTy;
1426 }
1427 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1428 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001429 } else {
1430 MicrosoftVTableContext::MethodVFTableLocation ML =
1431 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1432 if (MD->isVariadic()) {
1433 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1434 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1435 } else if (!CGM.getTypes().isFuncTypeConvertible(
1436 MD->getType()->castAs<FunctionType>())) {
1437 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1438 "incomplete return or parameter type");
1439 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1440 } else if (ML.VBase) {
1441 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1442 "member function in virtual base class");
1443 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1444 } else {
1445 SmallString<256> ThunkName;
1446 int OffsetInVFTable =
1447 ML.Index *
1448 getContext().getTypeSizeInChars(getContext().VoidPtrTy).getQuantity();
1449 llvm::raw_svector_ostream Out(ThunkName);
1450 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1451 Out.flush();
1452
1453 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1454 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1455 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001456 }
1457
1458 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001459 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1460 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001461}
1462
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001463/// Member pointers are the same if they're either bitwise identical *or* both
1464/// null. Null-ness for function members is determined by the first field,
1465/// while for data member pointers we must compare all fields.
1466llvm::Value *
1467MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1468 llvm::Value *L,
1469 llvm::Value *R,
1470 const MemberPointerType *MPT,
1471 bool Inequality) {
1472 CGBuilderTy &Builder = CGF.Builder;
1473
1474 // Handle != comparisons by switching the sense of all boolean operations.
1475 llvm::ICmpInst::Predicate Eq;
1476 llvm::Instruction::BinaryOps And, Or;
1477 if (Inequality) {
1478 Eq = llvm::ICmpInst::ICMP_NE;
1479 And = llvm::Instruction::Or;
1480 Or = llvm::Instruction::And;
1481 } else {
1482 Eq = llvm::ICmpInst::ICMP_EQ;
1483 And = llvm::Instruction::And;
1484 Or = llvm::Instruction::Or;
1485 }
1486
1487 // If this is a single field member pointer (single inheritance), this is a
1488 // single icmp.
1489 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1490 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001491 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001492 return Builder.CreateICmp(Eq, L, R);
1493
1494 // Compare the first field.
1495 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1496 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1497 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1498
1499 // Compare everything other than the first field.
1500 llvm::Value *Res = 0;
1501 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1502 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1503 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1504 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1505 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1506 if (Res)
1507 Res = Builder.CreateBinOp(And, Res, Cmp);
1508 else
1509 Res = Cmp;
1510 }
1511
1512 // Check if the first field is 0 if this is a function pointer.
1513 if (MPT->isMemberFunctionPointer()) {
1514 // (l1 == r1 && ...) || l0 == 0
1515 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1516 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1517 Res = Builder.CreateBinOp(Or, Res, IsZero);
1518 }
1519
1520 // Combine the comparison of the first field, which must always be true for
1521 // this comparison to succeeed.
1522 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1523}
1524
Reid Kleckner407e8b62013-03-22 19:02:54 +00001525llvm::Value *
1526MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1527 llvm::Value *MemPtr,
1528 const MemberPointerType *MPT) {
1529 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001530 llvm::SmallVector<llvm::Constant *, 4> fields;
1531 // We only need one field for member functions.
1532 if (MPT->isMemberFunctionPointer())
1533 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1534 else
1535 GetNullMemberPointerFields(MPT, fields);
1536 assert(!fields.empty());
1537 llvm::Value *FirstField = MemPtr;
1538 if (MemPtr->getType()->isStructTy())
1539 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1540 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001541
Reid Kleckner2341ae32013-04-11 18:13:19 +00001542 // For function member pointers, we only need to test the function pointer
1543 // field. The other fields if any can be garbage.
1544 if (MPT->isMemberFunctionPointer())
1545 return Res;
1546
1547 // Otherwise, emit a series of compares and combine the results.
1548 for (int I = 1, E = fields.size(); I < E; ++I) {
1549 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1550 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1551 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1552 }
1553 return Res;
1554}
1555
Reid Kleckner452abac2013-05-09 21:01:17 +00001556bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1557 llvm::Constant *Val) {
1558 // Function pointers are null if the pointer in the first field is null.
1559 if (MPT->isMemberFunctionPointer()) {
1560 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1561 Val->getAggregateElement(0U) : Val;
1562 return FirstField->isNullValue();
1563 }
1564
1565 // If it's not a function pointer and it's zero initializable, we can easily
1566 // check zero.
1567 if (isZeroInitializable(MPT) && Val->isNullValue())
1568 return true;
1569
1570 // Otherwise, break down all the fields for comparison. Hopefully these
1571 // little Constants are reused, while a big null struct might not be.
1572 llvm::SmallVector<llvm::Constant *, 4> Fields;
1573 GetNullMemberPointerFields(MPT, Fields);
1574 if (Fields.size() == 1) {
1575 assert(Val->getType()->isIntegerTy());
1576 return Val == Fields[0];
1577 }
1578
1579 unsigned I, E;
1580 for (I = 0, E = Fields.size(); I != E; ++I) {
1581 if (Val->getAggregateElement(I) != Fields[I])
1582 break;
1583 }
1584 return I == E;
1585}
1586
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001587llvm::Value *
1588MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1589 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001590 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001591 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001592 llvm::Value **VBPtrOut) {
1593 CGBuilderTy &Builder = CGF.Builder;
1594 // Load the vbtable pointer from the vbptr in the instance.
1595 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1596 llvm::Value *VBPtr =
1597 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1598 if (VBPtrOut) *VBPtrOut = VBPtr;
1599 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1600 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1601
1602 // Load an i32 offset from the vb-table.
1603 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1604 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1605 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1606}
1607
Reid Kleckner2341ae32013-04-11 18:13:19 +00001608// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1609// it.
1610llvm::Value *
1611MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1612 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001613 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001614 llvm::Value *VBPtrOffset) {
1615 CGBuilderTy &Builder = CGF.Builder;
1616 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1617 llvm::BasicBlock *OriginalBB = 0;
1618 llvm::BasicBlock *SkipAdjustBB = 0;
1619 llvm::BasicBlock *VBaseAdjustBB = 0;
1620
1621 // In the unspecified inheritance model, there might not be a vbtable at all,
1622 // in which case we need to skip the virtual base lookup. If there is a
1623 // vbtable, the first entry is a no-op entry that gives back the original
1624 // base, so look for a virtual base adjustment offset of zero.
1625 if (VBPtrOffset) {
1626 OriginalBB = Builder.GetInsertBlock();
1627 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1628 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1629 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001630 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001631 "memptr.is_vbase");
1632 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1633 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001634 }
1635
Reid Kleckner2341ae32013-04-11 18:13:19 +00001636 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1637 // know the vbptr offset.
1638 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001639 CharUnits offs = CharUnits::Zero();
1640 if (RD->getNumVBases()) {
1641 offs = GetVBPtrOffsetFromBases(RD);
1642 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001643 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1644 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001645 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001646 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001647 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001648 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1649
1650 // Merge control flow with the case where we didn't have to adjust.
1651 if (VBaseAdjustBB) {
1652 Builder.CreateBr(SkipAdjustBB);
1653 CGF.EmitBlock(SkipAdjustBB);
1654 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1655 Phi->addIncoming(Base, OriginalBB);
1656 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1657 return Phi;
1658 }
1659 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001660}
1661
1662llvm::Value *
1663MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1664 llvm::Value *Base,
1665 llvm::Value *MemPtr,
1666 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001667 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001668 unsigned AS = Base->getType()->getPointerAddressSpace();
1669 llvm::Type *PType =
1670 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1671 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001672 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1673 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001674
Reid Kleckner2341ae32013-04-11 18:13:19 +00001675 // Extract the fields we need, regardless of model. We'll apply them if we
1676 // have them.
1677 llvm::Value *FieldOffset = MemPtr;
1678 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1679 llvm::Value *VBPtrOffset = 0;
1680 if (MemPtr->getType()->isStructTy()) {
1681 // We need to extract values.
1682 unsigned I = 0;
1683 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1684 if (hasVBPtrOffsetField(Inheritance))
1685 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1686 if (hasVirtualBaseAdjustmentField(Inheritance))
1687 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001688 }
1689
Reid Kleckner2341ae32013-04-11 18:13:19 +00001690 if (VirtualBaseAdjustmentOffset) {
1691 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1692 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001693 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001694 llvm::Value *Addr =
1695 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001696
1697 // Cast the address to the appropriate pointer type, adopting the address
1698 // space of the base pointer.
1699 return Builder.CreateBitCast(Addr, PType);
1700}
1701
Reid Kleckner452abac2013-05-09 21:01:17 +00001702static MSInheritanceModel
1703getInheritanceFromMemptr(const MemberPointerType *MPT) {
1704 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1705}
1706
1707llvm::Value *
1708MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1709 const CastExpr *E,
1710 llvm::Value *Src) {
1711 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1712 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1713 E->getCastKind() == CK_ReinterpretMemberPointer);
1714
1715 // Use constant emission if we can.
1716 if (isa<llvm::Constant>(Src))
1717 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1718
1719 // We may be adding or dropping fields from the member pointer, so we need
1720 // both types and the inheritance models of both records.
1721 const MemberPointerType *SrcTy =
1722 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1723 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1724 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1725 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1726 bool IsFunc = SrcTy->isMemberFunctionPointer();
1727
1728 // If the classes use the same null representation, reinterpret_cast is a nop.
1729 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1730 if (IsReinterpret && (IsFunc ||
1731 nullFieldOffsetIsZero(SrcInheritance) ==
1732 nullFieldOffsetIsZero(DstInheritance)))
1733 return Src;
1734
1735 CGBuilderTy &Builder = CGF.Builder;
1736
1737 // Branch past the conversion if Src is null.
1738 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1739 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1740
1741 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1742 // pointer value of the destination type.
1743 if (IsReinterpret) {
1744 // For reinterpret casts, sema ensures that src and dst are both functions
1745 // or data and have the same size, which means the LLVM types should match.
1746 assert(Src->getType() == DstNull->getType());
1747 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1748 }
1749
1750 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1751 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1752 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1753 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1754 CGF.EmitBlock(ConvertBB);
1755
1756 // Decompose src.
1757 llvm::Value *FirstField = Src;
1758 llvm::Value *NonVirtualBaseAdjustment = 0;
1759 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1760 llvm::Value *VBPtrOffset = 0;
1761 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1762 // We need to extract values.
1763 unsigned I = 0;
1764 FirstField = Builder.CreateExtractValue(Src, I++);
1765 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1766 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1767 if (hasVBPtrOffsetField(SrcInheritance))
1768 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1769 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1770 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1771 }
1772
1773 // For data pointers, we adjust the field offset directly. For functions, we
1774 // have a separate field.
1775 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1776 if (Adj) {
1777 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1778 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1779 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1780 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1781 NVAdjustField = getZeroInt();
1782 if (isDerivedToBase)
1783 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1784 else
1785 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1786 }
1787
1788 // FIXME PR15713: Support conversions through virtually derived classes.
1789
1790 // Recompose dst from the null struct and the adjusted fields from src.
1791 llvm::Value *Dst;
1792 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1793 Dst = FirstField;
1794 } else {
1795 Dst = llvm::UndefValue::get(DstNull->getType());
1796 unsigned Idx = 0;
1797 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1798 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1799 Dst = Builder.CreateInsertValue(
1800 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1801 if (hasVBPtrOffsetField(DstInheritance))
1802 Dst = Builder.CreateInsertValue(
1803 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1804 if (hasVirtualBaseAdjustmentField(DstInheritance))
1805 Dst = Builder.CreateInsertValue(
1806 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1807 }
1808 Builder.CreateBr(ContinueBB);
1809
1810 // In the continuation, choose between DstNull and Dst.
1811 CGF.EmitBlock(ContinueBB);
1812 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1813 Phi->addIncoming(DstNull, OriginalBB);
1814 Phi->addIncoming(Dst, ConvertBB);
1815 return Phi;
1816}
1817
1818llvm::Constant *
1819MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1820 llvm::Constant *Src) {
1821 const MemberPointerType *SrcTy =
1822 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1823 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1824
1825 // If src is null, emit a new null for dst. We can't return src because dst
1826 // might have a new representation.
1827 if (MemberPointerConstantIsNull(SrcTy, Src))
1828 return EmitNullMemberPointer(DstTy);
1829
1830 // We don't need to do anything for reinterpret_casts of non-null member
1831 // pointers. We should only get here when the two type representations have
1832 // the same size.
1833 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1834 return Src;
1835
1836 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1837 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1838
1839 // Decompose src.
1840 llvm::Constant *FirstField = Src;
1841 llvm::Constant *NonVirtualBaseAdjustment = 0;
1842 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1843 llvm::Constant *VBPtrOffset = 0;
1844 bool IsFunc = SrcTy->isMemberFunctionPointer();
1845 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1846 // We need to extract values.
1847 unsigned I = 0;
1848 FirstField = Src->getAggregateElement(I++);
1849 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1850 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1851 if (hasVBPtrOffsetField(SrcInheritance))
1852 VBPtrOffset = Src->getAggregateElement(I++);
1853 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1854 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1855 }
1856
1857 // For data pointers, we adjust the field offset directly. For functions, we
1858 // have a separate field.
1859 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1860 if (Adj) {
1861 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1862 llvm::Constant *&NVAdjustField =
1863 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1864 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1865 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1866 NVAdjustField = getZeroInt();
1867 if (IsDerivedToBase)
1868 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1869 else
1870 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1871 }
1872
1873 // FIXME PR15713: Support conversions through virtually derived classes.
1874
1875 // Recompose dst from the null struct and the adjusted fields from src.
1876 if (hasOnlyOneField(IsFunc, DstInheritance))
1877 return FirstField;
1878
1879 llvm::SmallVector<llvm::Constant *, 4> Fields;
1880 Fields.push_back(FirstField);
1881 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1882 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1883 if (hasVBPtrOffsetField(DstInheritance))
1884 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1885 if (hasVirtualBaseAdjustmentField(DstInheritance))
1886 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1887 return llvm::ConstantStruct::getAnon(Fields);
1888}
1889
Reid Kleckner2341ae32013-04-11 18:13:19 +00001890llvm::Value *
1891MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1892 llvm::Value *&This,
1893 llvm::Value *MemPtr,
1894 const MemberPointerType *MPT) {
1895 assert(MPT->isMemberFunctionPointer());
1896 const FunctionProtoType *FPT =
1897 MPT->getPointeeType()->castAs<FunctionProtoType>();
1898 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1899 llvm::FunctionType *FTy =
1900 CGM.getTypes().GetFunctionType(
1901 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1902 CGBuilderTy &Builder = CGF.Builder;
1903
1904 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1905
1906 // Extract the fields we need, regardless of model. We'll apply them if we
1907 // have them.
1908 llvm::Value *FunctionPointer = MemPtr;
1909 llvm::Value *NonVirtualBaseAdjustment = NULL;
1910 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1911 llvm::Value *VBPtrOffset = NULL;
1912 if (MemPtr->getType()->isStructTy()) {
1913 // We need to extract values.
1914 unsigned I = 0;
1915 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001916 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1917 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001918 if (hasVBPtrOffsetField(Inheritance))
1919 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001920 if (hasVirtualBaseAdjustmentField(Inheritance))
1921 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1922 }
1923
1924 if (VirtualBaseAdjustmentOffset) {
1925 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1926 VBPtrOffset);
1927 }
1928
1929 if (NonVirtualBaseAdjustment) {
1930 // Apply the adjustment and cast back to the original struct type.
1931 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1932 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1933 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1934 }
1935
1936 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1937}
1938
Charles Davis53c59df2010-08-16 03:33:14 +00001939CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00001940 return new MicrosoftCXXABI(CGM);
1941}