blob: 62b7f430221169d1410e82427bb251482d04a40b [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
Reid Kleckner89077a12013-12-17 19:46:40 +0000143 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
144 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000145
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000146 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
147 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
148
John McCall0f999f32012-09-25 08:00:39 +0000149 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000150
Reid Kleckner89077a12013-12-17 19:46:40 +0000151 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
152 const CXXConstructorDecl *D,
153 CXXCtorType Type, bool ForVirtualBase,
154 bool Delegating, CallArgList &Args);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000155
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000156 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
157 CXXDtorType Type, bool ForVirtualBase,
158 bool Delegating, llvm::Value *This);
159
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000160 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
161
162 llvm::Value *getVTableAddressPointInStructor(
163 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
164 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
165 bool &NeedsVirtualOffset);
166
167 llvm::Constant *
168 getVTableAddressPointForConstExpr(BaseSubobject Base,
169 const CXXRecordDecl *VTableClass);
170
171 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
172 CharUnits VPtrOffset);
173
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000174 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
175 llvm::Value *This, llvm::Type *Ty);
176
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000177 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
178 const CXXDestructorDecl *Dtor,
179 CXXDtorType DtorType, SourceLocation CallLoc,
180 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000181
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000182 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
183 CallArgList &CallArgs) {
184 assert(GD.getDtorType() == Dtor_Deleting &&
185 "Only deleting destructor thunks are available in this ABI");
186 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
187 CGM.getContext().IntTy);
188 }
189
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000190 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000191
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000192 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
193 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
194 }
195
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000196 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
197 const ThisAdjustment &TA);
198
199 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
200 const ReturnAdjustment &RA);
201
John McCallc84ed6a2012-05-01 06:13:13 +0000202 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
203 llvm::GlobalVariable *DeclPtr,
204 bool PerformInit);
205
John McCall29036752011-01-27 02:46:02 +0000206 // ==== Notes on array cookies =========
207 //
208 // MSVC seems to only use cookies when the class has a destructor; a
209 // two-argument usual array deallocation function isn't sufficient.
210 //
211 // For example, this code prints "100" and "1":
212 // struct A {
213 // char x;
214 // void *operator new[](size_t sz) {
215 // printf("%u\n", sz);
216 // return malloc(sz);
217 // }
218 // void operator delete[](void *p, size_t sz) {
219 // printf("%u\n", sz);
220 // free(p);
221 // }
222 // };
223 // int main() {
224 // A *p = new A[100];
225 // delete[] p;
226 // }
227 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000228
229 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
230 bool requiresArrayCookie(const CXXNewExpr *expr);
231 CharUnits getArrayCookieSizeImpl(QualType type);
232 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
233 llvm::Value *NewPtr,
234 llvm::Value *NumElements,
235 const CXXNewExpr *expr,
236 QualType ElementType);
237 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
238 llvm::Value *allocPtr,
239 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000240
241private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000242 MicrosoftMangleContext &getMangleContext() {
243 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
244 }
245
Reid Kleckner2341ae32013-04-11 18:13:19 +0000246 llvm::Constant *getZeroInt() {
247 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000248 }
249
Reid Kleckner2341ae32013-04-11 18:13:19 +0000250 llvm::Constant *getAllOnesInt() {
251 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000252 }
253
Reid Kleckner452abac2013-05-09 21:01:17 +0000254 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
255 return C ? C : getZeroInt();
256 }
257
258 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
259 return C ? C : getZeroInt();
260 }
261
Reid Kleckner2341ae32013-04-11 18:13:19 +0000262 void
263 GetNullMemberPointerFields(const MemberPointerType *MPT,
264 llvm::SmallVectorImpl<llvm::Constant *> &fields);
265
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000266 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
267 /// it is reusing a vbptr from a non-virtual base. RD must have morally
268 /// virtual bases.
269 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
270
271 /// \brief Shared code for virtual base adjustment. Returns the offset from
272 /// the vbptr to the virtual base. Optionally returns the address of the
273 /// vbptr itself.
274 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
275 llvm::Value *Base,
276 llvm::Value *VBPtrOffset,
277 llvm::Value *VBTableOffset,
278 llvm::Value **VBPtr = 0);
279
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000280 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
281 llvm::Value *Base,
282 int32_t VBPtrOffset,
283 int32_t VBTableOffset,
284 llvm::Value **VBPtr = 0) {
285 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
286 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
287 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
288 }
289
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000290 /// \brief Performs a full virtual base adjustment. Used to dereference
291 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000292 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
293 llvm::Value *Base,
294 llvm::Value *VirtualBaseAdjustmentOffset,
295 llvm::Value *VBPtrOffset /* optional */);
296
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000297 /// \brief Emits a full member pointer with the fields common to data and
298 /// function member pointers.
299 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
300 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000301 const CXXRecordDecl *RD,
302 CharUnits NonVirtualBaseAdjustment);
303
304 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
305 const CXXMethodDecl *MD,
306 CharUnits NonVirtualBaseAdjustment);
307
308 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
309 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000310
Reid Kleckner7810af02013-06-19 15:20:38 +0000311 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
312 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
313
314 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
315 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
316
Hans Wennborg88497d62013-11-15 17:24:45 +0000317 /// \brief Generate a thunk for calling a virtual member function MD.
318 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
319 StringRef ThunkName);
320
Reid Kleckner407e8b62013-03-22 19:02:54 +0000321public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000322 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
323
324 virtual bool isZeroInitializable(const MemberPointerType *MPT);
325
Reid Kleckner407e8b62013-03-22 19:02:54 +0000326 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
327
328 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
329 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000330 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
331 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000332
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000333 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
334 llvm::Value *L,
335 llvm::Value *R,
336 const MemberPointerType *MPT,
337 bool Inequality);
338
Reid Kleckner407e8b62013-03-22 19:02:54 +0000339 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
340 llvm::Value *MemPtr,
341 const MemberPointerType *MPT);
342
343 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
344 llvm::Value *Base,
345 llvm::Value *MemPtr,
346 const MemberPointerType *MPT);
347
Reid Kleckner452abac2013-05-09 21:01:17 +0000348 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
349 const CastExpr *E,
350 llvm::Value *Src);
351
352 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
353 llvm::Constant *Src);
354
Reid Kleckner2341ae32013-04-11 18:13:19 +0000355 virtual llvm::Value *
356 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
357 llvm::Value *&This,
358 llvm::Value *MemPtr,
359 const MemberPointerType *MPT);
360
Reid Kleckner7810af02013-06-19 15:20:38 +0000361private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000362 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
363 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
364 /// \brief All the vftables that have been referenced.
365 VFTablesMapTy VFTablesMap;
366
367 /// \brief This set holds the record decls we've deferred vtable emission for.
368 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
369
370
371 /// \brief All the vbtables which have been referenced.
Reid Kleckner7810af02013-06-19 15:20:38 +0000372 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000373
374 /// Info on the global variable used to guard initialization of static locals.
375 /// The BitIndex field is only used for externally invisible declarations.
376 struct GuardInfo {
377 GuardInfo() : Guard(0), BitIndex(0) {}
378 llvm::GlobalVariable *Guard;
379 unsigned BitIndex;
380 };
381
382 /// Map from DeclContext to the current guard variable. We assume that the
383 /// AST is visited in source code order.
384 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000385};
386
387}
388
John McCall82fb8922012-09-25 10:10:39 +0000389llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
390 llvm::Value *ptr,
391 QualType type) {
392 // FIXME: implement
393 return ptr;
394}
395
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000396/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
397/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
398static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
399 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
400 E = RD->bases_end(); I != E; ++I) {
401 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
402 if (!I->isVirtual() && Base->getNumVBases() > 0)
403 return Base;
404 }
405 llvm_unreachable("RD must have an nv base with vbases");
406}
407
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000408CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
409 assert(RD->getNumVBases());
410 CharUnits Total = CharUnits::Zero();
411 while (RD) {
412 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
413 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
414 // -1 is the sentinel for no vbptr.
415 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
416 Total += VBPtrOffset;
417 break;
418 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000419 RD = FindFirstNVBaseWithVBases(RD);
420 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000421 }
422 return Total;
423}
424
425llvm::Value *
426MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
427 llvm::Value *This,
428 const CXXRecordDecl *ClassDecl,
429 const CXXRecordDecl *BaseClassDecl) {
430 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
431 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000432 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000433 CharUnits VBTableChars =
434 IntSize *
435 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000436 llvm::Value *VBTableOffset =
437 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
438
439 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000440 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000441 VBPtrToNewBase =
442 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
443 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
444}
445
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000446bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
447 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000448}
449
Reid Kleckner89077a12013-12-17 19:46:40 +0000450void MicrosoftCXXABI::BuildConstructorSignature(
451 const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
452 SmallVectorImpl<CanQualType> &ArgTys) {
453
454 // All parameters are already in place except is_most_derived, which goes
455 // after 'this' if it's variadic and last if it's not.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000456
457 const CXXRecordDecl *Class = Ctor->getParent();
Reid Kleckner89077a12013-12-17 19:46:40 +0000458 const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000459 if (Class->getNumVBases()) {
Reid Kleckner89077a12013-12-17 19:46:40 +0000460 if (FPT->isVariadic())
461 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
462 else
463 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000464 }
465}
466
Reid Kleckner7810af02013-06-19 15:20:38 +0000467llvm::BasicBlock *
468MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
469 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000470 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
471 assert(IsMostDerivedClass &&
472 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000473 llvm::Value *IsCompleteObject =
474 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000475
476 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
477 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
478 CGF.Builder.CreateCondBr(IsCompleteObject,
479 CallVbaseCtorsBB, SkipVbaseCtorsBB);
480
481 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000482
483 // Fill in the vbtable pointers here.
484 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000485
486 // CGF will put the base ctor calls in this basic block for us later.
487
488 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000489}
490
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000491void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
492 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
493 // In most cases, an override for a vbase virtual method can adjust
494 // the "this" parameter by applying a constant offset.
495 // However, this is not enough while a constructor or a destructor of some
496 // class X is being executed if all the following conditions are met:
497 // - X has virtual bases, (1)
498 // - X overrides a virtual method M of a vbase Y, (2)
499 // - X itself is a vbase of the most derived class.
500 //
501 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
502 // which holds the extra amount of "this" adjustment we must do when we use
503 // the X vftables (i.e. during X ctor or dtor).
504 // Outside the ctors and dtors, the values of vtorDisps are zero.
505
506 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
507 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
508 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
509 CGBuilderTy &Builder = CGF.Builder;
510
511 unsigned AS =
512 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
513 llvm::Value *Int8This = 0; // Initialize lazily.
514
515 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
516 I != E; ++I) {
517 if (!I->second.hasVtorDisp())
518 continue;
519
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000520 llvm::Value *VBaseOffset =
521 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000522 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
523 // just to Trunc back immediately.
524 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
525 uint64_t ConstantVBaseOffset =
526 Layout.getVBaseClassOffset(I->first).getQuantity();
527
528 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
529 llvm::Value *VtorDispValue = Builder.CreateSub(
530 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
531 "vtordisp.value");
532
533 if (!Int8This)
534 Int8This = Builder.CreateBitCast(getThisValue(CGF),
535 CGF.Int8Ty->getPointerTo(AS));
536 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
537 // vtorDisp is always the 32-bits before the vbase in the class layout.
538 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
539 VtorDispPtr = Builder.CreateBitCast(
540 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
541
542 Builder.CreateStore(VtorDispValue, VtorDispPtr);
543 }
544}
545
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000546void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
547 // There's only one constructor type in this ABI.
548 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
549}
550
Reid Kleckner7810af02013-06-19 15:20:38 +0000551void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
552 const CXXRecordDecl *RD) {
553 llvm::Value *ThisInt8Ptr =
554 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
555
556 const VBTableVector &VBTables = EnumerateVBTables(RD);
557 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
558 I != E; ++I) {
559 const ASTRecordLayout &SubobjectLayout =
560 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
561 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
562 SubobjectLayout.getVBPtrOffset()).getQuantity();
563 llvm::Value *VBPtr =
564 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
565 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
566 "vbptr." + I->ReusingBase->getName());
567 CGF.Builder.CreateStore(I->GV, VBPtr);
568 }
569}
570
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000571void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
572 CXXDtorType Type,
573 CanQualType &ResTy,
574 SmallVectorImpl<CanQualType> &ArgTys) {
575 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000576
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000577 // TODO: 'for base' flag
578
579 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000580 // The scalar deleting destructor takes an implicit int parameter.
581 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000582 }
583}
584
Reid Klecknere7de47e2013-07-22 13:51:44 +0000585void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
586 // The TU defining a dtor is only guaranteed to emit a base destructor. All
587 // other destructor variants are delegating thunks.
588 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
589}
590
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000591llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
592 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
593 GD = GD.getCanonicalDecl();
594 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000595 // FIXME: consider splitting the vdtor vs regular method code into two
596 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000597
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000598 GlobalDecl LookupGD = GD;
599 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
600 // Complete dtors take a pointer to the complete object,
601 // thus don't need adjustment.
602 if (GD.getDtorType() == Dtor_Complete)
603 return This;
604
605 // There's only Dtor_Deleting in vftable but it shares the this adjustment
606 // with the base one, so look up the deleting one instead.
607 LookupGD = GlobalDecl(DD, Dtor_Deleting);
608 }
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000609 MicrosoftVTableContext::MethodVFTableLocation ML =
610 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000611
612 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
613 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000614 CharUnits StaticOffset = ML.VFPtrOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000615 if (ML.VBase) {
616 bool AvoidVirtualOffset = false;
617 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
618 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000619 // same record type or another destructor of a more derived type;
620 // or a constructor of the same record type if an exception is thrown.
621 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
622 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000623 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000624 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000625
626 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000627 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
628 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
629 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
630 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
631 // We're calling the main base dtor from a complete structor,
632 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000633 AvoidVirtualOffset = true;
634 } else {
635 // Let's see if we try to call a destructor of a non-virtual base.
636 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
637 E = CurRD->bases_end(); I != E; ++I) {
638 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
639 continue;
640 // If we call a base destructor for a non-virtual base, we statically
641 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000642 // The total offset should reflect the adjustment done by
643 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000644 AvoidVirtualOffset = true;
645 break;
646 }
647 }
648 }
649
650 if (AvoidVirtualOffset) {
651 const ASTRecordLayout &Layout =
652 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000653 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
654 } else {
655 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000656 llvm::Value *VBaseOffset =
657 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000658 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
659 }
660 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000661 if (!StaticOffset.isZero()) {
662 assert(StaticOffset.isPositive());
663 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000664 if (ML.VBase) {
665 // Non-virtual adjustment might result in a pointer outside the allocated
666 // object, e.g. if the final overrider class is laid out after the virtual
667 // base that declares a method in the most derived class.
668 // FIXME: Update the code that emits this adjustment in thunks prologues.
669 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
670 } else {
671 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
672 StaticOffset.getQuantity());
673 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000674 }
675 return This;
676}
677
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000678static bool IsDeletingDtor(GlobalDecl GD) {
679 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
680 if (isa<CXXDestructorDecl>(MD)) {
681 return GD.getDtorType() == Dtor_Deleting;
682 }
683 return false;
684}
685
Reid Kleckner89077a12013-12-17 19:46:40 +0000686void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
687 QualType &ResTy,
688 FunctionArgList &Params) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000689 ASTContext &Context = getContext();
690 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000691 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000692 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
693 ImplicitParamDecl *IsMostDerived
694 = ImplicitParamDecl::Create(Context, 0,
695 CGF.CurGD.getDecl()->getLocation(),
696 &Context.Idents.get("is_most_derived"),
697 Context.IntTy);
Reid Kleckner89077a12013-12-17 19:46:40 +0000698 // The 'most_derived' parameter goes second if the ctor is variadic and last
699 // if it's not. Dtors can't be variadic.
700 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
701 if (FPT->isVariadic())
702 Params.insert(Params.begin() + 1, IsMostDerived);
703 else
704 Params.push_back(IsMostDerived);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000705 getStructorImplicitParamDecl(CGF) = IsMostDerived;
706 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000707 ImplicitParamDecl *ShouldDelete
708 = ImplicitParamDecl::Create(Context, 0,
709 CGF.CurGD.getDecl()->getLocation(),
710 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000711 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000712 Params.push_back(ShouldDelete);
713 getStructorImplicitParamDecl(CGF) = ShouldDelete;
714 }
John McCall0f999f32012-09-25 08:00:39 +0000715}
716
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000717llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
718 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
719 GD = GD.getCanonicalDecl();
720 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000721
722 GlobalDecl LookupGD = GD;
723 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
724 // Complete destructors take a pointer to the complete object as a
725 // parameter, thus don't need this adjustment.
726 if (GD.getDtorType() == Dtor_Complete)
727 return This;
728
729 // There's no Dtor_Base in vftable but it shares the this adjustment with
730 // the deleting one, so look it up instead.
731 LookupGD = GlobalDecl(DD, Dtor_Deleting);
732 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000733
734 // In this ABI, every virtual function takes a pointer to one of the
735 // subobjects that first defines it as the 'this' parameter, rather than a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000736 // pointer to the final overrider subobject. Thus, we need to adjust it back
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000737 // to the final overrider subobject before use.
738 // See comments in the MicrosoftVFTableContext implementation for the details.
739
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000740 MicrosoftVTableContext::MethodVFTableLocation ML =
741 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000742 CharUnits Adjustment = ML.VFPtrOffset;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000743 if (ML.VBase) {
744 const ASTRecordLayout &DerivedLayout =
745 CGF.getContext().getASTRecordLayout(MD->getParent());
746 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
747 }
748
749 if (Adjustment.isZero())
750 return This;
751
752 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
753 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
754 *thisTy = This->getType();
755
756 This = CGF.Builder.CreateBitCast(This, charPtrTy);
757 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000758 This =
759 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000760 return CGF.Builder.CreateBitCast(This, thisTy);
761}
762
John McCall0f999f32012-09-25 08:00:39 +0000763void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
764 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000765
766 /// If this is a function that the ABI specifies returns 'this', initialize
767 /// the return slot to 'this' at the start of the function.
768 ///
769 /// Unlike the setting of return types, this is done within the ABI
770 /// implementation instead of by clients of CGCXXABI because:
771 /// 1) getThisValue is currently protected
772 /// 2) in theory, an ABI could implement 'this' returns some other way;
773 /// HasThisReturn only specifies a contract, not the implementation
774 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000775 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000776
777 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
778 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
779 assert(getStructorImplicitParamDecl(CGF) &&
780 "no implicit parameter for a constructor with virtual bases?");
781 getStructorImplicitParamValue(CGF)
782 = CGF.Builder.CreateLoad(
783 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
784 "is_most_derived");
785 }
786
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000787 if (IsDeletingDtor(CGF.CurGD)) {
788 assert(getStructorImplicitParamDecl(CGF) &&
789 "no implicit parameter for a deleting destructor?");
790 getStructorImplicitParamValue(CGF)
791 = CGF.Builder.CreateLoad(
792 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
793 "should_call_delete");
794 }
John McCall0f999f32012-09-25 08:00:39 +0000795}
796
Reid Kleckner89077a12013-12-17 19:46:40 +0000797unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
798 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
799 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000800 assert(Type == Ctor_Complete || Type == Ctor_Base);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000801
Reid Kleckner89077a12013-12-17 19:46:40 +0000802 // Check if we need a 'most_derived' parameter.
803 if (!D->getParent()->getNumVBases())
804 return 0;
805
806 // Add the 'most_derived' argument second if we are variadic or last if not.
807 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
808 llvm::Value *MostDerivedArg =
809 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
810 RValue RV = RValue::get(MostDerivedArg);
811 if (MostDerivedArg) {
812 if (FPT->isVariadic())
813 Args.insert(Args.begin() + 1,
814 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
815 else
816 Args.add(RV, getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000817 }
818
Reid Kleckner89077a12013-12-17 19:46:40 +0000819 return 1; // Added one arg.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000820}
821
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000822void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
823 const CXXDestructorDecl *DD,
824 CXXDtorType Type, bool ForVirtualBase,
825 bool Delegating, llvm::Value *This) {
826 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
827
828 if (DD->isVirtual())
829 This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This);
830
831 // FIXME: Provide a source location here.
832 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
833 /*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0);
834}
835
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000836void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
837 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000838 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
839 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000840 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
841
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000842 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000843 E = VFPtrs.end(); I != E; ++I) {
844 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
845 if (VTable->hasInitializer())
846 continue;
847
848 const VTableLayout &VTLayout =
849 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
850 llvm::Constant *Init = CGVT.CreateVTableInitializer(
851 RD, VTLayout.vtable_component_begin(),
852 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
853 VTLayout.getNumVTableThunks());
854 VTable->setInitializer(Init);
855
856 VTable->setLinkage(Linkage);
857 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
858 }
859}
860
861llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
862 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
863 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
864 NeedsVirtualOffset = (NearestVBase != 0);
865
866 llvm::Value *VTableAddressPoint =
867 getAddrOfVTable(VTableClass, Base.getBaseOffset());
868 if (!VTableAddressPoint) {
869 assert(Base.getBase()->getNumVBases() &&
870 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
871 }
872 return VTableAddressPoint;
873}
874
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000875static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
876 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
877 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000878 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000879 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000880}
881
882llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
883 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
884 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
885 assert(VTable && "Couldn't find a vftable for the given base?");
886 return VTable;
887}
888
889llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
890 CharUnits VPtrOffset) {
891 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
892 // shouldn't be used in the given record type. We want to cache this result in
893 // VFTablesMap, thus a simple zero check is not sufficient.
894 VFTableIdTy ID(RD, VPtrOffset);
895 VFTablesMapTy::iterator I;
896 bool Inserted;
897 llvm::tie(I, Inserted) = VFTablesMap.insert(
898 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
899 if (!Inserted)
900 return I->second;
901
902 llvm::GlobalVariable *&VTable = I->second;
903
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000904 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
905 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
906 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000907
908 if (DeferredVFTables.insert(RD)) {
909 // We haven't processed this record type before.
910 // Queue up this v-table for possible deferred emission.
911 CGM.addDeferredVTable(RD);
912
913#ifndef NDEBUG
914 // Create all the vftables at once in order to make sure each vftable has
915 // a unique mangled name.
916 llvm::StringSet<> ObservedMangledNames;
917 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
918 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000919 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000920 if (!ObservedMangledNames.insert(Name.str()))
921 llvm_unreachable("Already saw this mangling before?");
922 }
923#endif
924 }
925
926 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
927 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
928 continue;
929
930 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
931 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000932 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000933 .getNumVTableComponents());
934
935 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000936 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000937 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
938 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
939 VTable->setUnnamedAddr(true);
940 break;
941 }
942
943 return VTable;
944}
945
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000946llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
947 GlobalDecl GD,
948 llvm::Value *This,
949 llvm::Type *Ty) {
950 GD = GD.getCanonicalDecl();
951 CGBuilderTy &Builder = CGF.Builder;
952
953 Ty = Ty->getPointerTo()->getPointerTo();
954 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
955 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
956
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000957 MicrosoftVTableContext::MethodVFTableLocation ML =
958 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000959 llvm::Value *VFuncPtr =
960 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
961 return Builder.CreateLoad(VFuncPtr);
962}
963
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000964void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
965 const CXXDestructorDecl *Dtor,
966 CXXDtorType DtorType,
967 SourceLocation CallLoc,
968 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000969 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
970
971 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000972 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000973 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000974 const CGFunctionInfo *FInfo =
975 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000976 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000977 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000978
979 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000980 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000981 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000982 DtorType == Dtor_Deleting);
983
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000984 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000985 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000986 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000987}
988
Reid Kleckner7810af02013-06-19 15:20:38 +0000989const VBTableVector &
990MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
991 // At this layer, we can key the cache off of a single class, which is much
992 // easier than caching at the GlobalVariable layer.
993 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
994 bool added;
995 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
996 VBTableVector &VBTables = I->second;
997 if (!added)
998 return VBTables;
999
1000 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
1001
1002 return VBTables;
1003}
1004
Hans Wennborg88497d62013-11-15 17:24:45 +00001005llvm::Function *
1006MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1007 StringRef ThunkName) {
1008 // If the thunk has been generated previously, just return it.
1009 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1010 return cast<llvm::Function>(GV);
1011
1012 // Create the llvm::Function.
1013 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1014 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1015 llvm::Function *ThunkFn =
1016 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1017 ThunkName.str(), &CGM.getModule());
1018 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1019
Hans Wennborg88497d62013-11-15 17:24:45 +00001020 ThunkFn->setLinkage(MD->isExternallyVisible()
1021 ? llvm::GlobalValue::LinkOnceODRLinkage
1022 : llvm::GlobalValue::InternalLinkage);
1023
1024 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1025 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1026
1027 // Start codegen.
1028 CodeGenFunction CGF(CGM);
1029 CGF.StartThunk(ThunkFn, MD, FnInfo);
1030
1031 // Get to the Callee.
1032 llvm::Value *This = CGF.LoadCXXThis();
1033 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1034
1035 // Make the call and return the result.
1036 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1037
1038 return ThunkFn;
1039}
1040
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001041void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001042 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001043 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1044
Reid Kleckner7810af02013-06-19 15:20:38 +00001045 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
1046 I != E; ++I) {
1047 I->EmitVBTableDefinition(CGM, RD, Linkage);
1048 }
1049}
1050
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001051llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1052 llvm::Value *This,
1053 const ThisAdjustment &TA) {
1054 if (TA.isEmpty())
1055 return This;
1056
1057 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1058
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001059 if (!TA.Virtual.isEmpty()) {
1060 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1061 // Adjust the this argument based on the vtordisp value.
1062 llvm::Value *VtorDispPtr =
1063 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1064 VtorDispPtr =
1065 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1066 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1067 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1068
1069 if (TA.Virtual.Microsoft.VBPtrOffset) {
1070 // If the final overrider is defined in a virtual base other than the one
1071 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1072 // the vbtable of the derived class.
1073 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1074 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1075 llvm::Value *VBPtr;
1076 llvm::Value *VBaseOffset =
1077 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1078 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1079 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1080 }
1081 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001082
1083 if (TA.NonVirtual) {
1084 // Non-virtual adjustment might result in a pointer outside the allocated
1085 // object, e.g. if the final overrider class is laid out after the virtual
1086 // base that declares a method in the most derived class.
1087 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1088 }
1089
1090 // Don't need to bitcast back, the call CodeGen will handle this.
1091 return V;
1092}
1093
1094llvm::Value *
1095MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1096 const ReturnAdjustment &RA) {
1097 if (RA.isEmpty())
1098 return Ret;
1099
1100 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1101
1102 if (RA.Virtual.Microsoft.VBIndex) {
1103 assert(RA.Virtual.Microsoft.VBIndex > 0);
1104 int32_t IntSize =
1105 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1106 llvm::Value *VBPtr;
1107 llvm::Value *VBaseOffset =
1108 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1109 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1110 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1111 }
1112
1113 if (RA.NonVirtual)
1114 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1115
1116 // Cast back to the original type.
1117 return CGF.Builder.CreateBitCast(V, Ret->getType());
1118}
1119
John McCallb91cd662012-05-01 05:23:51 +00001120bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1121 QualType elementType) {
1122 // Microsoft seems to completely ignore the possibility of a
1123 // two-argument usual deallocation function.
1124 return elementType.isDestructedType();
1125}
1126
1127bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1128 // Microsoft seems to completely ignore the possibility of a
1129 // two-argument usual deallocation function.
1130 return expr->getAllocatedType().isDestructedType();
1131}
1132
1133CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1134 // The array cookie is always a size_t; we then pad that out to the
1135 // alignment of the element type.
1136 ASTContext &Ctx = getContext();
1137 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1138 Ctx.getTypeAlignInChars(type));
1139}
1140
1141llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1142 llvm::Value *allocPtr,
1143 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001144 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001145 llvm::Value *numElementsPtr =
1146 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1147 return CGF.Builder.CreateLoad(numElementsPtr);
1148}
1149
1150llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1151 llvm::Value *newPtr,
1152 llvm::Value *numElements,
1153 const CXXNewExpr *expr,
1154 QualType elementType) {
1155 assert(requiresArrayCookie(expr));
1156
1157 // The size of the cookie.
1158 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1159
1160 // Compute an offset to the cookie.
1161 llvm::Value *cookiePtr = newPtr;
1162
1163 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001164 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001165 llvm::Value *numElementsPtr
1166 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1167 CGF.Builder.CreateStore(numElements, numElementsPtr);
1168
1169 // Finally, compute a pointer to the actual data buffer by skipping
1170 // over the cookie completely.
1171 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1172 cookieSize.getQuantity());
1173}
1174
John McCallc84ed6a2012-05-01 06:13:13 +00001175void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001176 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001177 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001178 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1179 // threadsafe. Since the user may be linking in inline functions compiled by
1180 // cl.exe, there's no reason to provide a false sense of security by using
1181 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001182
Richard Smithdbf74ba2013-04-14 23:01:42 +00001183 if (D.getTLSKind())
1184 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1185
Reid Klecknerd8110b62013-09-10 20:14:30 +00001186 CGBuilderTy &Builder = CGF.Builder;
1187 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1188 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1189
1190 // Get the guard variable for this function if we have one already.
1191 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1192
1193 unsigned BitIndex;
1194 if (D.isExternallyVisible()) {
1195 // Externally visible variables have to be numbered in Sema to properly
1196 // handle unreachable VarDecls.
1197 BitIndex = getContext().getManglingNumber(&D);
1198 assert(BitIndex > 0);
1199 BitIndex--;
1200 } else {
1201 // Non-externally visible variables are numbered here in CodeGen.
1202 BitIndex = GI.BitIndex++;
1203 }
1204
1205 if (BitIndex >= 32) {
1206 if (D.isExternallyVisible())
1207 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1208 BitIndex %= 32;
1209 GI.Guard = 0;
1210 }
1211
1212 // Lazily create the i32 bitfield for this function.
1213 if (!GI.Guard) {
1214 // Mangle the name for the guard.
1215 SmallString<256> GuardName;
1216 {
1217 llvm::raw_svector_ostream Out(GuardName);
1218 getMangleContext().mangleStaticGuardVariable(&D, Out);
1219 Out.flush();
1220 }
1221
1222 // Create the guard variable with a zero-initializer. Just absorb linkage
1223 // and visibility from the guarded variable.
1224 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1225 GV->getLinkage(), Zero, GuardName.str());
1226 GI.Guard->setVisibility(GV->getVisibility());
1227 } else {
1228 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1229 "static local from the same function had different linkage");
1230 }
1231
1232 // Pseudo code for the test:
1233 // if (!(GuardVar & MyGuardBit)) {
1234 // GuardVar |= MyGuardBit;
1235 // ... initialize the object ...;
1236 // }
1237
1238 // Test our bit from the guard variable.
1239 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1240 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1241 llvm::Value *IsInitialized =
1242 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1243 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1244 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1245 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1246
1247 // Set our bit in the guard variable and emit the initializer and add a global
1248 // destructor if appropriate.
1249 CGF.EmitBlock(InitBlock);
1250 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1251 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1252 Builder.CreateBr(EndBlock);
1253
1254 // Continue.
1255 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001256}
1257
Reid Kleckner2341ae32013-04-11 18:13:19 +00001258// Member pointer helpers.
1259static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1260 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001261}
1262
Reid Kleckner452abac2013-05-09 21:01:17 +00001263static bool hasOnlyOneField(bool IsMemberFunction,
1264 MSInheritanceModel Inheritance) {
1265 return Inheritance <= MSIM_SinglePolymorphic ||
1266 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001267}
1268
Reid Kleckner2341ae32013-04-11 18:13:19 +00001269// Only member pointers to functions need a this adjustment, since it can be
1270// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001271static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001272 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001273 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001274}
1275
1276static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1277 return Inheritance >= MSIM_Virtual;
1278}
1279
1280// Use zero for the field offset of a null data member pointer if we can
1281// guarantee that zero is not a valid field offset, or if the member pointer has
1282// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1283// use zero for null. If there are multiple fields, we can use zero even if it
1284// is a valid field offset because null-ness testing will check the other
1285// fields.
1286static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1287 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1288}
1289
1290bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1291 // Null-ness for function memptrs only depends on the first field, which is
1292 // the function pointer. The rest don't matter, so we can zero initialize.
1293 if (MPT->isMemberFunctionPointer())
1294 return true;
1295
1296 // The virtual base adjustment field is always -1 for null, so if we have one
1297 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1298 // valid field offset.
1299 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1300 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1301 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1302 nullFieldOffsetIsZero(Inheritance));
1303}
1304
1305llvm::Type *
1306MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1307 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1308 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1309 llvm::SmallVector<llvm::Type *, 4> fields;
1310 if (MPT->isMemberFunctionPointer())
1311 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1312 else
1313 fields.push_back(CGM.IntTy); // FieldOffset
1314
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001315 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1316 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001317 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001318 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001319 fields.push_back(CGM.IntTy);
1320 if (hasVirtualBaseAdjustmentField(Inheritance))
1321 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1322
1323 if (fields.size() == 1)
1324 return fields[0];
1325 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1326}
1327
1328void MicrosoftCXXABI::
1329GetNullMemberPointerFields(const MemberPointerType *MPT,
1330 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1331 assert(fields.empty());
1332 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1333 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1334 if (MPT->isMemberFunctionPointer()) {
1335 // FunctionPointerOrVirtualThunk
1336 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1337 } else {
1338 if (nullFieldOffsetIsZero(Inheritance))
1339 fields.push_back(getZeroInt()); // FieldOffset
1340 else
1341 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001342 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001343
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001344 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1345 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001346 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001347 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001348 fields.push_back(getZeroInt());
1349 if (hasVirtualBaseAdjustmentField(Inheritance))
1350 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001351}
1352
1353llvm::Constant *
1354MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001355 llvm::SmallVector<llvm::Constant *, 4> fields;
1356 GetNullMemberPointerFields(MPT, fields);
1357 if (fields.size() == 1)
1358 return fields[0];
1359 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1360 assert(Res->getType() == ConvertMemberPointerType(MPT));
1361 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001362}
1363
1364llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001365MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1366 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001367 const CXXRecordDecl *RD,
1368 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001369{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001370 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001371
1372 // Single inheritance class member pointer are represented as scalars instead
1373 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001374 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001375 return FirstField;
1376
Reid Kleckner2341ae32013-04-11 18:13:19 +00001377 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001378 fields.push_back(FirstField);
1379
1380 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001381 fields.push_back(llvm::ConstantInt::get(
1382 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001383
Reid Kleckner2341ae32013-04-11 18:13:19 +00001384 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001385 CharUnits Offs = CharUnits::Zero();
1386 if (RD->getNumVBases())
1387 Offs = GetVBPtrOffsetFromBases(RD);
1388 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001389 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001390
1391 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001392 if (hasVirtualBaseAdjustmentField(Inheritance))
1393 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001394
Reid Kleckner2341ae32013-04-11 18:13:19 +00001395 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001396}
1397
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001398llvm::Constant *
1399MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1400 CharUnits offset) {
1401 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1402 llvm::Constant *FirstField =
1403 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001404 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1405 CharUnits::Zero());
1406}
1407
1408llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1409 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1410}
1411
1412llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1413 QualType MPType) {
1414 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1415 const ValueDecl *MPD = MP.getMemberPointerDecl();
1416 if (!MPD)
1417 return EmitNullMemberPointer(MPT);
1418
1419 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1420
1421 // FIXME PR15713: Support virtual inheritance paths.
1422
1423 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1424 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1425 MD, ThisAdjustment);
1426
1427 CharUnits FieldOffset =
1428 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1429 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001430}
1431
1432llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001433MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1434 const CXXMethodDecl *MD,
1435 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001436 assert(MD->isInstance() && "Member function must not be static!");
1437 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001438 CodeGenTypes &Types = CGM.getTypes();
1439
1440 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001441 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001442 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1443 llvm::Type *Ty;
1444 // Check whether the function has a computable LLVM signature.
1445 if (Types.isFuncTypeConvertible(FPT)) {
1446 // The function has a computable LLVM signature; use the correct type.
1447 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1448 } else {
1449 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1450 // function type is incomplete.
1451 Ty = CGM.PtrDiffTy;
1452 }
1453 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1454 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001455 } else {
1456 MicrosoftVTableContext::MethodVFTableLocation ML =
1457 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1458 if (MD->isVariadic()) {
1459 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1460 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1461 } else if (!CGM.getTypes().isFuncTypeConvertible(
1462 MD->getType()->castAs<FunctionType>())) {
1463 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1464 "incomplete return or parameter type");
1465 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1466 } else if (ML.VBase) {
1467 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1468 "member function in virtual base class");
1469 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1470 } else {
1471 SmallString<256> ThunkName;
David Majnemer2a816452013-12-09 10:44:32 +00001472 CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1473 getContext().getTargetInfo().getPointerWidth(0));
1474 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
Hans Wennborg88497d62013-11-15 17:24:45 +00001475 llvm::raw_svector_ostream Out(ThunkName);
1476 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1477 Out.flush();
1478
1479 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1480 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1481 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001482 }
1483
1484 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001485 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1486 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001487}
1488
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001489/// Member pointers are the same if they're either bitwise identical *or* both
1490/// null. Null-ness for function members is determined by the first field,
1491/// while for data member pointers we must compare all fields.
1492llvm::Value *
1493MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1494 llvm::Value *L,
1495 llvm::Value *R,
1496 const MemberPointerType *MPT,
1497 bool Inequality) {
1498 CGBuilderTy &Builder = CGF.Builder;
1499
1500 // Handle != comparisons by switching the sense of all boolean operations.
1501 llvm::ICmpInst::Predicate Eq;
1502 llvm::Instruction::BinaryOps And, Or;
1503 if (Inequality) {
1504 Eq = llvm::ICmpInst::ICMP_NE;
1505 And = llvm::Instruction::Or;
1506 Or = llvm::Instruction::And;
1507 } else {
1508 Eq = llvm::ICmpInst::ICMP_EQ;
1509 And = llvm::Instruction::And;
1510 Or = llvm::Instruction::Or;
1511 }
1512
1513 // If this is a single field member pointer (single inheritance), this is a
1514 // single icmp.
1515 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1516 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001517 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001518 return Builder.CreateICmp(Eq, L, R);
1519
1520 // Compare the first field.
1521 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1522 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1523 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1524
1525 // Compare everything other than the first field.
1526 llvm::Value *Res = 0;
1527 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1528 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1529 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1530 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1531 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1532 if (Res)
1533 Res = Builder.CreateBinOp(And, Res, Cmp);
1534 else
1535 Res = Cmp;
1536 }
1537
1538 // Check if the first field is 0 if this is a function pointer.
1539 if (MPT->isMemberFunctionPointer()) {
1540 // (l1 == r1 && ...) || l0 == 0
1541 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1542 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1543 Res = Builder.CreateBinOp(Or, Res, IsZero);
1544 }
1545
1546 // Combine the comparison of the first field, which must always be true for
1547 // this comparison to succeeed.
1548 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1549}
1550
Reid Kleckner407e8b62013-03-22 19:02:54 +00001551llvm::Value *
1552MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1553 llvm::Value *MemPtr,
1554 const MemberPointerType *MPT) {
1555 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001556 llvm::SmallVector<llvm::Constant *, 4> fields;
1557 // We only need one field for member functions.
1558 if (MPT->isMemberFunctionPointer())
1559 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1560 else
1561 GetNullMemberPointerFields(MPT, fields);
1562 assert(!fields.empty());
1563 llvm::Value *FirstField = MemPtr;
1564 if (MemPtr->getType()->isStructTy())
1565 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1566 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001567
Reid Kleckner2341ae32013-04-11 18:13:19 +00001568 // For function member pointers, we only need to test the function pointer
1569 // field. The other fields if any can be garbage.
1570 if (MPT->isMemberFunctionPointer())
1571 return Res;
1572
1573 // Otherwise, emit a series of compares and combine the results.
1574 for (int I = 1, E = fields.size(); I < E; ++I) {
1575 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1576 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1577 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1578 }
1579 return Res;
1580}
1581
Reid Kleckner452abac2013-05-09 21:01:17 +00001582bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1583 llvm::Constant *Val) {
1584 // Function pointers are null if the pointer in the first field is null.
1585 if (MPT->isMemberFunctionPointer()) {
1586 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1587 Val->getAggregateElement(0U) : Val;
1588 return FirstField->isNullValue();
1589 }
1590
1591 // If it's not a function pointer and it's zero initializable, we can easily
1592 // check zero.
1593 if (isZeroInitializable(MPT) && Val->isNullValue())
1594 return true;
1595
1596 // Otherwise, break down all the fields for comparison. Hopefully these
1597 // little Constants are reused, while a big null struct might not be.
1598 llvm::SmallVector<llvm::Constant *, 4> Fields;
1599 GetNullMemberPointerFields(MPT, Fields);
1600 if (Fields.size() == 1) {
1601 assert(Val->getType()->isIntegerTy());
1602 return Val == Fields[0];
1603 }
1604
1605 unsigned I, E;
1606 for (I = 0, E = Fields.size(); I != E; ++I) {
1607 if (Val->getAggregateElement(I) != Fields[I])
1608 break;
1609 }
1610 return I == E;
1611}
1612
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001613llvm::Value *
1614MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1615 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001616 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001617 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001618 llvm::Value **VBPtrOut) {
1619 CGBuilderTy &Builder = CGF.Builder;
1620 // Load the vbtable pointer from the vbptr in the instance.
1621 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1622 llvm::Value *VBPtr =
1623 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1624 if (VBPtrOut) *VBPtrOut = VBPtr;
1625 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1626 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1627
1628 // Load an i32 offset from the vb-table.
1629 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1630 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1631 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1632}
1633
Reid Kleckner2341ae32013-04-11 18:13:19 +00001634// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1635// it.
1636llvm::Value *
1637MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1638 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001639 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001640 llvm::Value *VBPtrOffset) {
1641 CGBuilderTy &Builder = CGF.Builder;
1642 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1643 llvm::BasicBlock *OriginalBB = 0;
1644 llvm::BasicBlock *SkipAdjustBB = 0;
1645 llvm::BasicBlock *VBaseAdjustBB = 0;
1646
1647 // In the unspecified inheritance model, there might not be a vbtable at all,
1648 // in which case we need to skip the virtual base lookup. If there is a
1649 // vbtable, the first entry is a no-op entry that gives back the original
1650 // base, so look for a virtual base adjustment offset of zero.
1651 if (VBPtrOffset) {
1652 OriginalBB = Builder.GetInsertBlock();
1653 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1654 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1655 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001656 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001657 "memptr.is_vbase");
1658 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1659 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001660 }
1661
Reid Kleckner2341ae32013-04-11 18:13:19 +00001662 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1663 // know the vbptr offset.
1664 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001665 CharUnits offs = CharUnits::Zero();
1666 if (RD->getNumVBases()) {
1667 offs = GetVBPtrOffsetFromBases(RD);
1668 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001669 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1670 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001671 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001672 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001673 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001674 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1675
1676 // Merge control flow with the case where we didn't have to adjust.
1677 if (VBaseAdjustBB) {
1678 Builder.CreateBr(SkipAdjustBB);
1679 CGF.EmitBlock(SkipAdjustBB);
1680 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1681 Phi->addIncoming(Base, OriginalBB);
1682 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1683 return Phi;
1684 }
1685 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001686}
1687
1688llvm::Value *
1689MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1690 llvm::Value *Base,
1691 llvm::Value *MemPtr,
1692 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001693 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001694 unsigned AS = Base->getType()->getPointerAddressSpace();
1695 llvm::Type *PType =
1696 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1697 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001698 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1699 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001700
Reid Kleckner2341ae32013-04-11 18:13:19 +00001701 // Extract the fields we need, regardless of model. We'll apply them if we
1702 // have them.
1703 llvm::Value *FieldOffset = MemPtr;
1704 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1705 llvm::Value *VBPtrOffset = 0;
1706 if (MemPtr->getType()->isStructTy()) {
1707 // We need to extract values.
1708 unsigned I = 0;
1709 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1710 if (hasVBPtrOffsetField(Inheritance))
1711 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1712 if (hasVirtualBaseAdjustmentField(Inheritance))
1713 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001714 }
1715
Reid Kleckner2341ae32013-04-11 18:13:19 +00001716 if (VirtualBaseAdjustmentOffset) {
1717 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1718 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001719 }
Reid Klecknerae945122013-12-05 22:44:07 +00001720
1721 // Cast to char*.
1722 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1723
1724 // Apply the offset, which we assume is non-null.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001725 llvm::Value *Addr =
1726 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001727
1728 // Cast the address to the appropriate pointer type, adopting the address
1729 // space of the base pointer.
1730 return Builder.CreateBitCast(Addr, PType);
1731}
1732
Reid Kleckner452abac2013-05-09 21:01:17 +00001733static MSInheritanceModel
1734getInheritanceFromMemptr(const MemberPointerType *MPT) {
1735 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1736}
1737
1738llvm::Value *
1739MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1740 const CastExpr *E,
1741 llvm::Value *Src) {
1742 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1743 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1744 E->getCastKind() == CK_ReinterpretMemberPointer);
1745
1746 // Use constant emission if we can.
1747 if (isa<llvm::Constant>(Src))
1748 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1749
1750 // We may be adding or dropping fields from the member pointer, so we need
1751 // both types and the inheritance models of both records.
1752 const MemberPointerType *SrcTy =
1753 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1754 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1755 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1756 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1757 bool IsFunc = SrcTy->isMemberFunctionPointer();
1758
1759 // If the classes use the same null representation, reinterpret_cast is a nop.
1760 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1761 if (IsReinterpret && (IsFunc ||
1762 nullFieldOffsetIsZero(SrcInheritance) ==
1763 nullFieldOffsetIsZero(DstInheritance)))
1764 return Src;
1765
1766 CGBuilderTy &Builder = CGF.Builder;
1767
1768 // Branch past the conversion if Src is null.
1769 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1770 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1771
1772 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1773 // pointer value of the destination type.
1774 if (IsReinterpret) {
1775 // For reinterpret casts, sema ensures that src and dst are both functions
1776 // or data and have the same size, which means the LLVM types should match.
1777 assert(Src->getType() == DstNull->getType());
1778 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1779 }
1780
1781 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1782 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1783 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1784 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1785 CGF.EmitBlock(ConvertBB);
1786
1787 // Decompose src.
1788 llvm::Value *FirstField = Src;
1789 llvm::Value *NonVirtualBaseAdjustment = 0;
1790 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1791 llvm::Value *VBPtrOffset = 0;
1792 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1793 // We need to extract values.
1794 unsigned I = 0;
1795 FirstField = Builder.CreateExtractValue(Src, I++);
1796 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1797 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1798 if (hasVBPtrOffsetField(SrcInheritance))
1799 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1800 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1801 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1802 }
1803
1804 // For data pointers, we adjust the field offset directly. For functions, we
1805 // have a separate field.
1806 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1807 if (Adj) {
1808 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1809 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1810 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1811 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1812 NVAdjustField = getZeroInt();
1813 if (isDerivedToBase)
1814 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1815 else
1816 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1817 }
1818
1819 // FIXME PR15713: Support conversions through virtually derived classes.
1820
1821 // Recompose dst from the null struct and the adjusted fields from src.
1822 llvm::Value *Dst;
1823 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1824 Dst = FirstField;
1825 } else {
1826 Dst = llvm::UndefValue::get(DstNull->getType());
1827 unsigned Idx = 0;
1828 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1829 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1830 Dst = Builder.CreateInsertValue(
1831 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1832 if (hasVBPtrOffsetField(DstInheritance))
1833 Dst = Builder.CreateInsertValue(
1834 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1835 if (hasVirtualBaseAdjustmentField(DstInheritance))
1836 Dst = Builder.CreateInsertValue(
1837 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1838 }
1839 Builder.CreateBr(ContinueBB);
1840
1841 // In the continuation, choose between DstNull and Dst.
1842 CGF.EmitBlock(ContinueBB);
1843 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1844 Phi->addIncoming(DstNull, OriginalBB);
1845 Phi->addIncoming(Dst, ConvertBB);
1846 return Phi;
1847}
1848
1849llvm::Constant *
1850MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1851 llvm::Constant *Src) {
1852 const MemberPointerType *SrcTy =
1853 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1854 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1855
1856 // If src is null, emit a new null for dst. We can't return src because dst
1857 // might have a new representation.
1858 if (MemberPointerConstantIsNull(SrcTy, Src))
1859 return EmitNullMemberPointer(DstTy);
1860
1861 // We don't need to do anything for reinterpret_casts of non-null member
1862 // pointers. We should only get here when the two type representations have
1863 // the same size.
1864 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1865 return Src;
1866
1867 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1868 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1869
1870 // Decompose src.
1871 llvm::Constant *FirstField = Src;
1872 llvm::Constant *NonVirtualBaseAdjustment = 0;
1873 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1874 llvm::Constant *VBPtrOffset = 0;
1875 bool IsFunc = SrcTy->isMemberFunctionPointer();
1876 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1877 // We need to extract values.
1878 unsigned I = 0;
1879 FirstField = Src->getAggregateElement(I++);
1880 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1881 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1882 if (hasVBPtrOffsetField(SrcInheritance))
1883 VBPtrOffset = Src->getAggregateElement(I++);
1884 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1885 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1886 }
1887
1888 // For data pointers, we adjust the field offset directly. For functions, we
1889 // have a separate field.
1890 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1891 if (Adj) {
1892 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1893 llvm::Constant *&NVAdjustField =
1894 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1895 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1896 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1897 NVAdjustField = getZeroInt();
1898 if (IsDerivedToBase)
1899 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1900 else
1901 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1902 }
1903
1904 // FIXME PR15713: Support conversions through virtually derived classes.
1905
1906 // Recompose dst from the null struct and the adjusted fields from src.
1907 if (hasOnlyOneField(IsFunc, DstInheritance))
1908 return FirstField;
1909
1910 llvm::SmallVector<llvm::Constant *, 4> Fields;
1911 Fields.push_back(FirstField);
1912 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1913 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1914 if (hasVBPtrOffsetField(DstInheritance))
1915 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1916 if (hasVirtualBaseAdjustmentField(DstInheritance))
1917 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1918 return llvm::ConstantStruct::getAnon(Fields);
1919}
1920
Reid Kleckner2341ae32013-04-11 18:13:19 +00001921llvm::Value *
1922MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1923 llvm::Value *&This,
1924 llvm::Value *MemPtr,
1925 const MemberPointerType *MPT) {
1926 assert(MPT->isMemberFunctionPointer());
1927 const FunctionProtoType *FPT =
1928 MPT->getPointeeType()->castAs<FunctionProtoType>();
1929 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1930 llvm::FunctionType *FTy =
1931 CGM.getTypes().GetFunctionType(
1932 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1933 CGBuilderTy &Builder = CGF.Builder;
1934
1935 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1936
1937 // Extract the fields we need, regardless of model. We'll apply them if we
1938 // have them.
1939 llvm::Value *FunctionPointer = MemPtr;
1940 llvm::Value *NonVirtualBaseAdjustment = NULL;
1941 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1942 llvm::Value *VBPtrOffset = NULL;
1943 if (MemPtr->getType()->isStructTy()) {
1944 // We need to extract values.
1945 unsigned I = 0;
1946 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001947 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1948 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001949 if (hasVBPtrOffsetField(Inheritance))
1950 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001951 if (hasVirtualBaseAdjustmentField(Inheritance))
1952 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1953 }
1954
1955 if (VirtualBaseAdjustmentOffset) {
1956 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1957 VBPtrOffset);
1958 }
1959
1960 if (NonVirtualBaseAdjustment) {
1961 // Apply the adjustment and cast back to the original struct type.
1962 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1963 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1964 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1965 }
1966
1967 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1968}
1969
Charles Davis53c59df2010-08-16 03:33:14 +00001970CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00001971 return new MicrosoftCXXABI(CGM);
1972}