blob: 354887f446a44728cdfc9d58533229921e227f24 [file] [log] [blame]
Charles Davis3a811f12010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis3a811f12010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCallee79a4c2010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis3a811f12010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall0bab0cd2010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davis9ee494f2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall93d557b2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperba77cb92012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis3a811f12010-05-25 19:52:27 +000031
32using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000034
35namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall0bab0cd2010-08-23 01:21:21 +000037private:
Chris Lattner9cbe4f02011-07-09 17:41:47 +000038 llvm::IntegerType *PtrDiffTy;
John McCall93d557b2010-08-22 00:05:51 +000039protected:
John McCallbabc9a92010-08-22 00:59:17 +000040 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000041
42 // It's a little silly for us to cache this.
Chris Lattner9cbe4f02011-07-09 17:41:47 +000043 llvm::IntegerType *getPtrDiffTy() {
John McCall0bab0cd2010-08-23 01:21:21 +000044 if (!PtrDiffTy) {
John McCall9cb2cee2010-09-02 10:25:57 +000045 QualType T = getContext().getPointerDiffType();
Chris Lattner9cbe4f02011-07-09 17:41:47 +000046 llvm::Type *Ty = CGM.getTypes().ConvertType(T);
John McCall0bab0cd2010-08-23 01:21:21 +000047 PtrDiffTy = cast<llvm::IntegerType>(Ty);
48 }
49 return PtrDiffTy;
50 }
51
Charles Davis3a811f12010-05-25 19:52:27 +000052public:
John McCallbabc9a92010-08-22 00:59:17 +000053 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Peter Collingbourne14110472011-01-13 18:57:25 +000054 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000055
John McCallf16aa102010-08-22 21:01:12 +000056 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000057
Chris Lattner9cbe4f02011-07-09 17:41:47 +000058 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000059
John McCall93d557b2010-08-22 00:05:51 +000060 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
61 llvm::Value *&This,
62 llvm::Value *MemFnPtr,
63 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000064
John McCall6c2ab1d2010-08-31 21:07:20 +000065 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
66 llvm::Value *Base,
67 llvm::Value *MemPtr,
68 const MemberPointerType *MPT);
69
John McCall0bab0cd2010-08-23 01:21:21 +000070 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
71 const CastExpr *E,
72 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000073 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
74 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000075
John McCall0bab0cd2010-08-23 01:21:21 +000076 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000077
John McCall755d8492011-04-12 00:42:48 +000078 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000079 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
80 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000081 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
82 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
83 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000084
John McCall0bab0cd2010-08-23 01:21:21 +000085 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
86 llvm::Value *L,
87 llvm::Value *R,
88 const MemberPointerType *MPT,
89 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000090
John McCall0bab0cd2010-08-23 01:21:21 +000091 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
92 llvm::Value *Addr,
93 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000094
John McCallecd03b42012-09-25 10:10:39 +000095 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
96 llvm::Value *ptr,
97 QualType type);
98
John McCall4c40d982010-08-31 07:33:07 +000099 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
100 CXXCtorType T,
101 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000102 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000103
104 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
105 CXXDtorType T,
106 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000108
109 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
110 QualType &ResTy,
111 FunctionArgList &Params);
112
113 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000114
Joao Matos285baac2012-07-17 17:10:11 +0000115 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000116 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000117
John McCalle2b45e22012-05-01 05:23:51 +0000118 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000119 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
120 llvm::Value *NewPtr,
121 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000122 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000123 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000124 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
125 llvm::Value *allocPtr,
126 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000127
John McCall3030eb82010-11-06 09:44:32 +0000128 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000129 llvm::GlobalVariable *DeclPtr, bool PerformInit);
John McCall20bb1752012-05-01 06:13:13 +0000130 void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
131 llvm::Constant *addr);
Charles Davis3a811f12010-05-25 19:52:27 +0000132};
John McCallee79a4c2010-08-21 22:46:04 +0000133
134class ARMCXXABI : public ItaniumCXXABI {
135public:
John McCallbabc9a92010-08-22 00:59:17 +0000136 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000137
138 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
139 CXXCtorType T,
140 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000141 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000142
143 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
144 CXXDtorType T,
145 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000146 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000147
148 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
149 QualType &ResTy,
150 FunctionArgList &Params);
151
152 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
153
154 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
155
John McCalle2b45e22012-05-01 05:23:51 +0000156 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000157 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
158 llvm::Value *NewPtr,
159 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000160 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000161 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000162 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
163 CharUnits cookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000164
165private:
166 /// \brief Returns true if the given instance method is one of the
167 /// kinds that the ARM ABI says returns 'this'.
168 static bool HasThisReturn(GlobalDecl GD) {
169 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
170 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
171 (isa<CXXConstructorDecl>(MD)));
172 }
John McCallee79a4c2010-08-21 22:46:04 +0000173};
Charles Davis3a811f12010-05-25 19:52:27 +0000174}
175
Charles Davis071cc7d2010-08-16 03:33:14 +0000176CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall96fcde02013-01-25 23:36:14 +0000177 switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
178 // For IR-generation purposes, there's no significant difference
179 // between the ARM and iOS ABIs.
180 case TargetCXXABI::GenericARM:
181 case TargetCXXABI::iOS:
182 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000183
John McCall96fcde02013-01-25 23:36:14 +0000184 case TargetCXXABI::GenericItanium:
185 return new ItaniumCXXABI(CGM);
186
187 case TargetCXXABI::Microsoft:
188 llvm_unreachable("Microsoft ABI is not Itanium-based");
189 }
190 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000191}
192
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000193llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000194ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
195 if (MPT->isMemberDataPointer())
196 return getPtrDiffTy();
Chris Lattner7650d952011-06-18 22:49:11 +0000197 return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000198}
199
John McCallbabc9a92010-08-22 00:59:17 +0000200/// In the Itanium and ARM ABIs, method pointers have the form:
201/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
202///
203/// In the Itanium ABI:
204/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
205/// - the this-adjustment is (memptr.adj)
206/// - the virtual offset is (memptr.ptr - 1)
207///
208/// In the ARM ABI:
209/// - method pointers are virtual if (memptr.adj & 1) is nonzero
210/// - the this-adjustment is (memptr.adj >> 1)
211/// - the virtual offset is (memptr.ptr)
212/// ARM uses 'adj' for the virtual flag because Thumb functions
213/// may be only single-byte aligned.
214///
215/// If the member is virtual, the adjusted 'this' pointer points
216/// to a vtable pointer from which the virtual offset is applied.
217///
218/// If the member is non-virtual, memptr.ptr is the address of
219/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000220llvm::Value *
221ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
222 llvm::Value *&This,
223 llvm::Value *MemFnPtr,
224 const MemberPointerType *MPT) {
225 CGBuilderTy &Builder = CGF.Builder;
226
227 const FunctionProtoType *FPT =
228 MPT->getPointeeType()->getAs<FunctionProtoType>();
229 const CXXRecordDecl *RD =
230 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
231
Chris Lattner2acc6e32011-07-18 04:24:23 +0000232 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000233 CGM.getTypes().GetFunctionType(
234 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000235
Chris Lattner2acc6e32011-07-18 04:24:23 +0000236 llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000237 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000238
John McCallbabc9a92010-08-22 00:59:17 +0000239 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
240 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
241 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
242
John McCalld608cdb2010-08-22 10:59:02 +0000243 // Extract memptr.adj, which is in the second field.
244 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000245
246 // Compute the true adjustment.
247 llvm::Value *Adj = RawAdj;
248 if (IsARM)
249 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000250
251 // Apply the adjustment and cast back to the original struct type
252 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000253 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
254 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
255 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000256
257 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000258 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000259
260 // If the LSB in the function pointer is 1, the function pointer points to
261 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000262 llvm::Value *IsVirtual;
263 if (IsARM)
264 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
265 else
266 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
267 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000268 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
269
270 // In the virtual path, the adjustment left 'This' pointing to the
271 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000272 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000273 CGF.EmitBlock(FnVirtual);
274
275 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000276 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000277 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000278 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000279
280 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000281 llvm::Value *VTableOffset = FnAsInt;
282 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
283 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000284
285 // Load the virtual function to call.
286 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000287 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000288 CGF.EmitBranch(FnEnd);
289
290 // In the non-virtual path, the function pointer is actually a
291 // function pointer.
292 CGF.EmitBlock(FnNonVirtual);
293 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000294 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000295
296 // We're done.
297 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000298 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000299 Callee->addIncoming(VirtualFn, FnVirtual);
300 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
301 return Callee;
302}
John McCall3023def2010-08-22 03:04:22 +0000303
John McCall6c2ab1d2010-08-31 21:07:20 +0000304/// Compute an l-value by applying the given pointer-to-member to a
305/// base object.
306llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
307 llvm::Value *Base,
308 llvm::Value *MemPtr,
309 const MemberPointerType *MPT) {
310 assert(MemPtr->getType() == getPtrDiffTy());
311
312 CGBuilderTy &Builder = CGF.Builder;
313
Micah Villmow956a5a12012-10-25 15:39:14 +0000314 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000315
316 // Cast to char*.
317 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
318
319 // Apply the offset, which we assume is non-null.
320 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
321
322 // Cast the address to the appropriate pointer type, adopting the
323 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000324 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000325 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000326 return Builder.CreateBitCast(Addr, PType);
327}
328
John McCall4d4e5c12012-02-15 01:22:51 +0000329/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
330/// conversion.
331///
332/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000333///
334/// Obligatory offset/adjustment diagram:
335/// <-- offset --> <-- adjustment -->
336/// |--------------------------|----------------------|--------------------|
337/// ^Derived address point ^Base address point ^Member address point
338///
339/// So when converting a base member pointer to a derived member pointer,
340/// we add the offset to the adjustment because the address point has
341/// decreased; and conversely, when converting a derived MP to a base MP
342/// we subtract the offset from the adjustment because the address point
343/// has increased.
344///
345/// The standard forbids (at compile time) conversion to and from
346/// virtual bases, which is why we don't have to consider them here.
347///
348/// The standard forbids (at run time) casting a derived MP to a base
349/// MP when the derived MP does not point to a member of the base.
350/// This is why -1 is a reasonable choice for null data member
351/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000352llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000353ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
354 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000355 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000356 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000357 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
358 E->getCastKind() == CK_ReinterpretMemberPointer);
359
360 // Under Itanium, reinterprets don't require any additional processing.
361 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
362
363 // Use constant emission if we can.
364 if (isa<llvm::Constant>(src))
365 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
366
367 llvm::Constant *adj = getMemberPointerAdjustment(E);
368 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000369
370 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000371 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000372
John McCall4d4e5c12012-02-15 01:22:51 +0000373 const MemberPointerType *destTy =
374 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000375
John McCall0bab0cd2010-08-23 01:21:21 +0000376 // For member data pointers, this is just a matter of adding the
377 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000378 if (destTy->isMemberDataPointer()) {
379 llvm::Value *dst;
380 if (isDerivedToBase)
381 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000382 else
John McCall4d4e5c12012-02-15 01:22:51 +0000383 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000384
385 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000386 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
387 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
388 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000389 }
390
John McCalld608cdb2010-08-22 10:59:02 +0000391 // The this-adjustment is left-shifted by 1 on ARM.
392 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000393 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
394 offset <<= 1;
395 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000396 }
397
John McCall4d4e5c12012-02-15 01:22:51 +0000398 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
399 llvm::Value *dstAdj;
400 if (isDerivedToBase)
401 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000402 else
John McCall4d4e5c12012-02-15 01:22:51 +0000403 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000404
John McCall4d4e5c12012-02-15 01:22:51 +0000405 return Builder.CreateInsertValue(src, dstAdj, 1);
406}
407
408llvm::Constant *
409ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
410 llvm::Constant *src) {
411 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
412 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
413 E->getCastKind() == CK_ReinterpretMemberPointer);
414
415 // Under Itanium, reinterprets don't require any additional processing.
416 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
417
418 // If the adjustment is trivial, we don't need to do anything.
419 llvm::Constant *adj = getMemberPointerAdjustment(E);
420 if (!adj) return src;
421
422 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
423
424 const MemberPointerType *destTy =
425 E->getType()->castAs<MemberPointerType>();
426
427 // For member data pointers, this is just a matter of adding the
428 // offset if the source is non-null.
429 if (destTy->isMemberDataPointer()) {
430 // null maps to null.
431 if (src->isAllOnesValue()) return src;
432
433 if (isDerivedToBase)
434 return llvm::ConstantExpr::getNSWSub(src, adj);
435 else
436 return llvm::ConstantExpr::getNSWAdd(src, adj);
437 }
438
439 // The this-adjustment is left-shifted by 1 on ARM.
440 if (IsARM) {
441 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
442 offset <<= 1;
443 adj = llvm::ConstantInt::get(adj->getType(), offset);
444 }
445
446 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
447 llvm::Constant *dstAdj;
448 if (isDerivedToBase)
449 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
450 else
451 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
452
453 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000454}
John McCallcf2c85e2010-08-22 04:16:24 +0000455
456llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000457ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000458 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCall0bab0cd2010-08-23 01:21:21 +0000459
460 // Itanium C++ ABI 2.3:
461 // A NULL pointer is represented as -1.
462 if (MPT->isMemberDataPointer())
463 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000464
465 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
466 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000467 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000468}
469
John McCall5808ce42011-02-03 08:15:49 +0000470llvm::Constant *
471ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
472 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000473 // Itanium C++ ABI 2.3:
474 // A pointer to data member is an offset from the base address of
475 // the class object containing it, represented as a ptrdiff_t
John McCall5808ce42011-02-03 08:15:49 +0000476 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000477}
478
John McCall755d8492011-04-12 00:42:48 +0000479llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000480 return BuildMemberPointer(MD, CharUnits::Zero());
481}
482
483llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
484 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000485 assert(MD->isInstance() && "Member function must not be static!");
486 MD = MD->getCanonicalDecl();
487
488 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000489 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000490
491 // Get the function pointer (or index if this is a virtual function).
492 llvm::Constant *MemPtr[2];
493 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000494 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000495
Ken Dyck1246ba62011-04-09 01:30:02 +0000496 const ASTContext &Context = getContext();
497 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000498 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000499 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000500
501 if (IsARM) {
502 // ARM C++ ABI 3.2.1:
503 // This ABI specifies that adj contains twice the this
504 // adjustment, plus 1 if the member function is virtual. The
505 // least significant bit of adj then makes exactly the same
506 // discrimination as the least significant bit of ptr does for
507 // Itanium.
508 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000509 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
510 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000511 } else {
512 // Itanium C++ ABI 2.3:
513 // For a virtual function, [the pointer field] is 1 plus the
514 // virtual table offset (in bytes) of the function,
515 // represented as a ptrdiff_t.
516 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
Richard Smith2d6a5672012-01-14 04:30:29 +0000517 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
518 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000519 }
520 } else {
John McCall755d8492011-04-12 00:42:48 +0000521 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000522 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000523 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000524 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000525 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000526 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000527 } else {
John McCall755d8492011-04-12 00:42:48 +0000528 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
529 // function type is incomplete.
530 Ty = ptrdiff_t;
John McCalld608cdb2010-08-22 10:59:02 +0000531 }
John McCall755d8492011-04-12 00:42:48 +0000532 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000533
John McCall379b5152011-04-11 07:02:50 +0000534 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
Richard Smith2d6a5672012-01-14 04:30:29 +0000535 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
536 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000537 }
John McCall875ab102010-08-22 06:43:33 +0000538
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000539 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000540}
541
Richard Smith2d6a5672012-01-14 04:30:29 +0000542llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
543 QualType MPType) {
544 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
545 const ValueDecl *MPD = MP.getMemberPointerDecl();
546 if (!MPD)
547 return EmitNullMemberPointer(MPT);
548
549 // Compute the this-adjustment.
550 CharUnits ThisAdjustment = CharUnits::Zero();
551 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
552 bool DerivedMember = MP.isMemberPointerToDerivedMember();
553 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
554 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
555 const CXXRecordDecl *Base = RD;
556 const CXXRecordDecl *Derived = Path[I];
557 if (DerivedMember)
558 std::swap(Base, Derived);
559 ThisAdjustment +=
560 getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
561 RD = Path[I];
562 }
563 if (DerivedMember)
564 ThisAdjustment = -ThisAdjustment;
565
566 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
567 return BuildMemberPointer(MD, ThisAdjustment);
568
569 CharUnits FieldOffset =
570 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
571 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
572}
573
John McCalle9fd7eb2010-08-22 08:30:07 +0000574/// The comparison algorithm is pretty easy: the member pointers are
575/// the same if they're either bitwise identical *or* both null.
576///
577/// ARM is different here only because null-ness is more complicated.
578llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000579ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
580 llvm::Value *L,
581 llvm::Value *R,
582 const MemberPointerType *MPT,
583 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000584 CGBuilderTy &Builder = CGF.Builder;
585
John McCalle9fd7eb2010-08-22 08:30:07 +0000586 llvm::ICmpInst::Predicate Eq;
587 llvm::Instruction::BinaryOps And, Or;
588 if (Inequality) {
589 Eq = llvm::ICmpInst::ICMP_NE;
590 And = llvm::Instruction::Or;
591 Or = llvm::Instruction::And;
592 } else {
593 Eq = llvm::ICmpInst::ICMP_EQ;
594 And = llvm::Instruction::And;
595 Or = llvm::Instruction::Or;
596 }
597
John McCall0bab0cd2010-08-23 01:21:21 +0000598 // Member data pointers are easy because there's a unique null
599 // value, so it just comes down to bitwise equality.
600 if (MPT->isMemberDataPointer())
601 return Builder.CreateICmp(Eq, L, R);
602
603 // For member function pointers, the tautologies are more complex.
604 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000605 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000606 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000607 // (L == R) <==> (L.ptr == R.ptr &&
608 // (L.adj == R.adj ||
609 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000610 // The inequality tautologies have exactly the same structure, except
611 // applying De Morgan's laws.
612
613 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
614 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
615
John McCalle9fd7eb2010-08-22 08:30:07 +0000616 // This condition tests whether L.ptr == R.ptr. This must always be
617 // true for equality to hold.
618 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
619
620 // This condition, together with the assumption that L.ptr == R.ptr,
621 // tests whether the pointers are both null. ARM imposes an extra
622 // condition.
623 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
624 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
625
626 // This condition tests whether L.adj == R.adj. If this isn't
627 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000628 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
629 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000630 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
631
632 // Null member function pointers on ARM clear the low bit of Adj,
633 // so the zero condition has to check that neither low bit is set.
634 if (IsARM) {
635 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
636
637 // Compute (l.adj | r.adj) & 1 and test it against zero.
638 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
639 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
640 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
641 "cmp.or.adj");
642 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
643 }
644
645 // Tie together all our conditions.
646 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
647 Result = Builder.CreateBinOp(And, PtrEq, Result,
648 Inequality ? "memptr.ne" : "memptr.eq");
649 return Result;
650}
651
652llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000653ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
654 llvm::Value *MemPtr,
655 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000656 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000657
658 /// For member data pointers, this is just a check against -1.
659 if (MPT->isMemberDataPointer()) {
660 assert(MemPtr->getType() == getPtrDiffTy());
661 llvm::Value *NegativeOne =
662 llvm::Constant::getAllOnesValue(MemPtr->getType());
663 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
664 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000665
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000666 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000667 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000668
669 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
670 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
671
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000672 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
673 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000674 if (IsARM) {
675 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000676 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000677 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000678 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
679 "memptr.isvirtual");
680 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000681 }
682
683 return Result;
684}
John McCall875ab102010-08-22 06:43:33 +0000685
John McCallf16aa102010-08-22 21:01:12 +0000686/// The Itanium ABI requires non-zero initialization only for data
687/// member pointers, for which '0' is a valid offset.
688bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
689 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000690}
John McCall4c40d982010-08-31 07:33:07 +0000691
John McCallecd03b42012-09-25 10:10:39 +0000692/// The Itanium ABI always places an offset to the complete object
693/// at entry -2 in the vtable.
694llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
695 llvm::Value *ptr,
696 QualType type) {
697 // Grab the vtable pointer as an intptr_t*.
698 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
699
700 // Track back to entry -2 and pull out the offset there.
701 llvm::Value *offsetPtr =
702 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
703 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
704 offset->setAlignment(CGF.PointerAlignInBytes);
705
706 // Apply the offset.
707 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
708 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
709}
710
John McCall4c40d982010-08-31 07:33:07 +0000711/// The generic ABI passes 'this', plus a VTT if it's initializing a
712/// base subobject.
713void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
714 CXXCtorType Type,
715 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000716 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000717 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000718
719 // 'this' is already there.
720
721 // Check if we need to add a VTT parameter (which has type void **).
722 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
723 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
724}
725
726/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
727void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
728 CXXCtorType Type,
729 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000730 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000731 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
732 ResTy = ArgTys[0];
733}
734
735/// The generic ABI passes 'this', plus a VTT if it's destroying a
736/// base subobject.
737void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
738 CXXDtorType Type,
739 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000740 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000741 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000742
743 // 'this' is already there.
744
745 // Check if we need to add a VTT parameter (which has type void **).
746 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
747 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
748}
749
750/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
751/// for non-deleting destructors.
752void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
753 CXXDtorType Type,
754 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000755 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000756 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
757
758 if (Type != Dtor_Deleting)
759 ResTy = ArgTys[0];
760}
761
762void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
763 QualType &ResTy,
764 FunctionArgList &Params) {
765 /// Create the 'this' variable.
766 BuildThisParam(CGF, Params);
767
768 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
769 assert(MD->isInstance());
770
771 // Check if we need a VTT parameter as well.
772 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000773 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000774
775 // FIXME: avoid the fake decl
776 QualType T = Context.getPointerType(Context.VoidPtrTy);
777 ImplicitParamDecl *VTTDecl
778 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
779 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000780 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000781 getVTTDecl(CGF) = VTTDecl;
782 }
783}
784
785void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
786 QualType &ResTy,
787 FunctionArgList &Params) {
788 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
789
790 // Return 'this' from certain constructors and destructors.
791 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000792 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000793}
794
795void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
796 /// Initialize the 'this' slot.
797 EmitThisParam(CGF);
798
799 /// Initialize the 'vtt' slot if needed.
800 if (getVTTDecl(CGF)) {
801 getVTTValue(CGF)
802 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
803 "vtt");
804 }
805}
806
807void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
808 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
809
810 /// Initialize the return slot to 'this' at the start of the
811 /// function.
812 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000813 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000814}
815
816void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
817 RValue RV, QualType ResultType) {
818 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
819 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
820
821 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000822 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000823 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
824 RValue Undef = RValue::get(llvm::UndefValue::get(T));
825 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
826}
John McCall1e7fe752010-09-02 09:58:18 +0000827
828/************************** Array allocation cookies **************************/
829
John McCalle2b45e22012-05-01 05:23:51 +0000830CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
831 // The array cookie is a size_t; pad that up to the element alignment.
832 // The cookie is actually right-justified in that space.
833 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
834 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000835}
836
837llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
838 llvm::Value *NewPtr,
839 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000840 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000841 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000842 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000843
Micah Villmow956a5a12012-10-25 15:39:14 +0000844 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000845
John McCall9cb2cee2010-09-02 10:25:57 +0000846 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000847 QualType SizeTy = Ctx.getSizeType();
848 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
849
850 // The size of the cookie.
851 CharUnits CookieSize =
852 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000853 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000854
855 // Compute an offset to the cookie.
856 llvm::Value *CookiePtr = NewPtr;
857 CharUnits CookieOffset = CookieSize - SizeSize;
858 if (!CookieOffset.isZero())
859 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
860 CookieOffset.getQuantity());
861
862 // Write the number of elements into the appropriate slot.
863 llvm::Value *NumElementsPtr
864 = CGF.Builder.CreateBitCast(CookiePtr,
865 CGF.ConvertType(SizeTy)->getPointerTo(AS));
866 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
867
868 // Finally, compute a pointer to the actual data buffer by skipping
869 // over the cookie completely.
870 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
871 CookieSize.getQuantity());
872}
873
John McCalle2b45e22012-05-01 05:23:51 +0000874llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
875 llvm::Value *allocPtr,
876 CharUnits cookieSize) {
877 // The element size is right-justified in the cookie.
878 llvm::Value *numElementsPtr = allocPtr;
879 CharUnits numElementsOffset =
880 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
881 if (!numElementsOffset.isZero())
882 numElementsPtr =
883 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
884 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000885
Micah Villmow956a5a12012-10-25 15:39:14 +0000886 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000887 numElementsPtr =
888 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
889 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000890}
891
John McCalle2b45e22012-05-01 05:23:51 +0000892CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCall1e7fe752010-09-02 09:58:18 +0000893 // On ARM, the cookie is always:
894 // struct array_cookie {
895 // std::size_t element_size; // element_size != 0
896 // std::size_t element_count;
897 // };
898 // TODO: what should we do if the allocated type actually wants
899 // greater alignment?
John McCalle2b45e22012-05-01 05:23:51 +0000900 return CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000901}
902
903llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
904 llvm::Value *NewPtr,
905 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000906 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000907 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000908 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000909
910 // NewPtr is a char*.
911
Micah Villmow956a5a12012-10-25 15:39:14 +0000912 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000913
John McCall9cb2cee2010-09-02 10:25:57 +0000914 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000915 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000916 llvm::IntegerType *SizeTy =
John McCall1e7fe752010-09-02 09:58:18 +0000917 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
918
919 // The cookie is always at the start of the buffer.
920 llvm::Value *CookiePtr = NewPtr;
921
922 // The first element is the element size.
923 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
924 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
925 Ctx.getTypeSizeInChars(ElementType).getQuantity());
926 CGF.Builder.CreateStore(ElementSize, CookiePtr);
927
928 // The second element is the element count.
929 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
930 CGF.Builder.CreateStore(NumElements, CookiePtr);
931
932 // Finally, compute a pointer to the actual data buffer by skipping
933 // over the cookie completely.
934 CharUnits CookieSize = 2 * SizeSize;
935 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
936 CookieSize.getQuantity());
937}
938
John McCalle2b45e22012-05-01 05:23:51 +0000939llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
940 llvm::Value *allocPtr,
941 CharUnits cookieSize) {
942 // The number of elements is at offset sizeof(size_t) relative to
943 // the allocated pointer.
944 llvm::Value *numElementsPtr
945 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000946
Micah Villmow956a5a12012-10-25 15:39:14 +0000947 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000948 numElementsPtr =
949 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
950 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000951}
952
John McCall5cd91b52010-09-08 01:44:27 +0000953/*********************** Static local initialization **************************/
954
955static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000956 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000957 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000958 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +0000959 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +0000960 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000961 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling72390b32012-12-20 19:27:06 +0000962 llvm::Attribute::get(CGM.getLLVMContext(),
963 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000964}
965
966static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000967 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000968 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000969 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000970 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000971 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling72390b32012-12-20 19:27:06 +0000972 llvm::Attribute::get(CGM.getLLVMContext(),
973 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000974}
975
976static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000977 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000978 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000979 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000980 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000981 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling72390b32012-12-20 19:27:06 +0000982 llvm::Attribute::get(CGM.getLLVMContext(),
983 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000984}
985
986namespace {
987 struct CallGuardAbort : EHScopeStack::Cleanup {
988 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +0000989 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +0000990
John McCallad346f42011-07-12 20:27:29 +0000991 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5cd91b52010-09-08 01:44:27 +0000992 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
993 ->setDoesNotThrow();
994 }
995 };
996}
997
998/// The ARM code here follows the Itanium code closely enough that we
999/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001000void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1001 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001002 llvm::GlobalVariable *var,
1003 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001004 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001005
1006 // We only need to use thread-safe statics for local variables;
1007 // global initialization is always single-threaded.
John McCall0502a222011-06-17 07:33:57 +00001008 bool threadsafe =
David Blaikie4e4d0842012-03-11 07:00:24 +00001009 (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
Anders Carlsson173d5122011-04-27 04:37:08 +00001010
Anders Carlsson173d5122011-04-27 04:37:08 +00001011 // If we have a global variable with internal linkage and thread-safe statics
1012 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001013 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1014
1015 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001016 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001017 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001018 } else {
Anders Carlsson173d5122011-04-27 04:37:08 +00001019 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
John McCall355bba72012-03-30 21:00:39 +00001020 guardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001021 }
John McCall355bba72012-03-30 21:00:39 +00001022 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001023
John McCall355bba72012-03-30 21:00:39 +00001024 // Create the guard variable if we don't already have it (as we
1025 // might if we're double-emitting this function body).
1026 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1027 if (!guard) {
1028 // Mangle the name for the guard.
1029 SmallString<256> guardName;
1030 {
1031 llvm::raw_svector_ostream out(guardName);
1032 getMangleContext().mangleItaniumGuardVariable(&D, out);
1033 out.flush();
1034 }
John McCall112c9672010-11-02 21:04:24 +00001035
John McCall355bba72012-03-30 21:00:39 +00001036 // Create the guard variable with a zero-initializer.
1037 // Just absorb linkage and visibility from the guarded variable.
1038 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1039 false, var->getLinkage(),
1040 llvm::ConstantInt::get(guardTy, 0),
1041 guardName.str());
1042 guard->setVisibility(var->getVisibility());
1043
1044 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1045 }
John McCall49d26d22012-03-30 07:09:50 +00001046
John McCall5cd91b52010-09-08 01:44:27 +00001047 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001048 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001049
1050 // ARM C++ ABI 3.2.3.1:
1051 // To support the potential use of initialization guard variables
1052 // as semaphores that are the target of ARM SWP and LDREX/STREX
1053 // synchronizing instructions we define a static initialization
1054 // guard variable to be a 4-byte aligned, 4- byte word with the
1055 // following inline access protocol.
1056 // #define INITIALIZED 1
1057 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1058 // if (__cxa_guard_acquire(&obj_guard))
1059 // ...
1060 // }
John McCall0502a222011-06-17 07:33:57 +00001061 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001062 llvm::Value *V = Builder.CreateLoad(guard);
John McCall5cd91b52010-09-08 01:44:27 +00001063 V = Builder.CreateAnd(V, Builder.getInt32(1));
John McCall355bba72012-03-30 21:00:39 +00001064 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001065
1066 // Itanium C++ ABI 3.3.2:
1067 // The following is pseudo-code showing how these functions can be used:
1068 // if (obj_guard.first_byte == 0) {
1069 // if ( __cxa_guard_acquire (&obj_guard) ) {
1070 // try {
1071 // ... initialize the object ...;
1072 // } catch (...) {
1073 // __cxa_guard_abort (&obj_guard);
1074 // throw;
1075 // }
1076 // ... queue object destructor with __cxa_atexit() ...;
1077 // __cxa_guard_release (&obj_guard);
1078 // }
1079 // }
1080 } else {
1081 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001082 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001083 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001084 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001085
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001086 // Itanium ABI:
1087 // An implementation supporting thread-safety on multiprocessor
1088 // systems must also guarantee that references to the initialized
1089 // object do not occur before the load of the initialization flag.
1090 //
1091 // In LLVM, we do this by marking the load Acquire.
1092 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001093 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001094
John McCall355bba72012-03-30 21:00:39 +00001095 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001096 }
1097
1098 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1099 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1100
1101 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001102 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001103
1104 CGF.EmitBlock(InitCheckBlock);
1105
1106 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001107 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001108 // Call __cxa_guard_acquire.
1109 llvm::Value *V
John McCall355bba72012-03-30 21:00:39 +00001110 = Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001111
1112 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1113
1114 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1115 InitBlock, EndBlock);
1116
1117 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001118 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001119
1120 CGF.EmitBlock(InitBlock);
1121 }
1122
1123 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001124 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001125
John McCall0502a222011-06-17 07:33:57 +00001126 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001127 // Pop the guard-abort cleanup if we pushed one.
1128 CGF.PopCleanupBlock();
1129
1130 // Call __cxa_guard_release. This cannot throw.
John McCall355bba72012-03-30 21:00:39 +00001131 Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001132 } else {
John McCall355bba72012-03-30 21:00:39 +00001133 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001134 }
1135
1136 CGF.EmitBlock(EndBlock);
1137}
John McCall20bb1752012-05-01 06:13:13 +00001138
1139/// Register a global destructor using __cxa_atexit.
1140static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1141 llvm::Constant *dtor,
1142 llvm::Constant *addr) {
1143 // We're assuming that the destructor function is something we can
1144 // reasonably call with the default CC. Go ahead and cast it to the
1145 // right prototype.
1146 llvm::Type *dtorTy =
1147 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1148
1149 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1150 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1151 llvm::FunctionType *atexitTy =
1152 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1153
1154 // Fetch the actual function.
1155 llvm::Constant *atexit =
1156 CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
1157 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1158 fn->setDoesNotThrow();
1159
1160 // Create a variable that binds the atexit to this shared object.
1161 llvm::Constant *handle =
1162 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1163
1164 llvm::Value *args[] = {
1165 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1166 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1167 handle
1168 };
1169 CGF.Builder.CreateCall(atexit, args)->setDoesNotThrow();
1170}
1171
1172/// Register a global destructor as best as we know how.
1173void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1174 llvm::Constant *dtor,
1175 llvm::Constant *addr) {
1176 // Use __cxa_atexit if available.
1177 if (CGM.getCodeGenOpts().CXAAtExit) {
1178 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
1179 }
1180
1181 // In Apple kexts, we want to add a global destructor entry.
1182 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001183 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001184 // Generate a global destructor entry.
1185 return CGM.AddCXXDtorEntry(dtor, addr);
1186 }
1187
1188 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1189}