blob: 382aa4795747ab2704ef9d1fa884ef442c19e8c3 [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 McCall93d557b2010-08-22 00:05:51 +000037protected:
John McCallbabc9a92010-08-22 00:59:17 +000038 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000039
Charles Davis3a811f12010-05-25 19:52:27 +000040public:
John McCallbabc9a92010-08-22 00:59:17 +000041 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Reid Kleckner92e44d92013-03-22 16:13:10 +000042 CGCXXABI(CGM), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000043
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000044 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
45 // Structures with either a non-trivial destructor or a non-trivial
46 // copy constructor are always indirect.
47 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
48 }
49
50 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
51 // Structures with either a non-trivial destructor or a non-trivial
52 // copy constructor are always indirect.
53 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
54 return RAA_Indirect;
55 return RAA_Default;
56 }
57
John McCallf16aa102010-08-22 21:01:12 +000058 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000059
Chris Lattner9cbe4f02011-07-09 17:41:47 +000060 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000061
John McCall93d557b2010-08-22 00:05:51 +000062 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
63 llvm::Value *&This,
64 llvm::Value *MemFnPtr,
65 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000066
John McCall6c2ab1d2010-08-31 21:07:20 +000067 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
68 llvm::Value *Base,
69 llvm::Value *MemPtr,
70 const MemberPointerType *MPT);
71
John McCall0bab0cd2010-08-23 01:21:21 +000072 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
73 const CastExpr *E,
74 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000075 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
76 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000077
John McCall0bab0cd2010-08-23 01:21:21 +000078 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000079
John McCall755d8492011-04-12 00:42:48 +000080 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000081 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
82 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000083 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
84 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
85 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000086
John McCall0bab0cd2010-08-23 01:21:21 +000087 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
88 llvm::Value *L,
89 llvm::Value *R,
90 const MemberPointerType *MPT,
91 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000092
John McCall0bab0cd2010-08-23 01:21:21 +000093 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
94 llvm::Value *Addr,
95 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000096
John McCallecd03b42012-09-25 10:10:39 +000097 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
98 llvm::Value *ptr,
99 QualType type);
100
John McCall4c40d982010-08-31 07:33:07 +0000101 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
102 CXXCtorType T,
103 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000104 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000105
106 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
107 CXXDtorType T,
108 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000110
111 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
112 QualType &ResTy,
113 FunctionArgList &Params);
114
115 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000116
Manman Ren63fd4082013-03-20 16:59:38 +0000117 llvm::Value *EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000118 const CXXConstructorDecl *D,
119 CXXCtorType Type, bool ForVirtualBase,
120 bool Delegating,
121 llvm::Value *This,
122 CallExpr::const_arg_iterator ArgBeg,
123 CallExpr::const_arg_iterator ArgEnd);
124
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000125 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
126 const CXXDestructorDecl *Dtor,
127 CXXDtorType DtorType,
128 SourceLocation CallLoc,
129 ReturnValueSlot ReturnValue,
130 llvm::Value *This);
131
Joao Matos285baac2012-07-17 17:10:11 +0000132 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000133 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000134
John McCalle2b45e22012-05-01 05:23:51 +0000135 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000136 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
137 llvm::Value *NewPtr,
138 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000139 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000140 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000141 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
142 llvm::Value *allocPtr,
143 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000144
John McCall3030eb82010-11-06 09:44:32 +0000145 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000146 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000147 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
148 llvm::Constant *dtor, llvm::Constant *addr);
Charles Davis3a811f12010-05-25 19:52:27 +0000149};
John McCallee79a4c2010-08-21 22:46:04 +0000150
151class ARMCXXABI : public ItaniumCXXABI {
152public:
John McCallbabc9a92010-08-22 00:59:17 +0000153 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000154
155 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
156 CXXCtorType T,
157 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000158 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000159
160 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
161 CXXDtorType T,
162 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000163 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000164
165 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
166 QualType &ResTy,
167 FunctionArgList &Params);
168
169 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
170
171 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
172
John McCalle2b45e22012-05-01 05:23:51 +0000173 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000174 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
175 llvm::Value *NewPtr,
176 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000177 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000178 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000179 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
180 CharUnits cookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000181
John McCall4c40d982010-08-31 07:33:07 +0000182 /// \brief Returns true if the given instance method is one of the
183 /// kinds that the ARM ABI says returns 'this'.
Manman Ren63fd4082013-03-20 16:59:38 +0000184 bool HasThisReturn(GlobalDecl GD) const {
185 const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(GD.getDecl());
186 if (!MD) return false;
John McCall4c40d982010-08-31 07:33:07 +0000187 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
188 (isa<CXXConstructorDecl>(MD)));
189 }
John McCallee79a4c2010-08-21 22:46:04 +0000190};
Charles Davis3a811f12010-05-25 19:52:27 +0000191}
192
Charles Davis071cc7d2010-08-16 03:33:14 +0000193CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000194 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000195 // For IR-generation purposes, there's no significant difference
196 // between the ARM and iOS ABIs.
197 case TargetCXXABI::GenericARM:
198 case TargetCXXABI::iOS:
199 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000200
Tim Northoverc264e162013-01-31 12:13:10 +0000201 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
202 // include the other 32-bit ARM oddities: constructor/destructor return values
203 // and array cookies.
204 case TargetCXXABI::GenericAArch64:
205 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
206
John McCall96fcde02013-01-25 23:36:14 +0000207 case TargetCXXABI::GenericItanium:
208 return new ItaniumCXXABI(CGM);
209
210 case TargetCXXABI::Microsoft:
211 llvm_unreachable("Microsoft ABI is not Itanium-based");
212 }
213 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000214}
215
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000216llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000217ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
218 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000219 return CGM.PtrDiffTy;
220 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000221}
222
John McCallbabc9a92010-08-22 00:59:17 +0000223/// In the Itanium and ARM ABIs, method pointers have the form:
224/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
225///
226/// In the Itanium ABI:
227/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
228/// - the this-adjustment is (memptr.adj)
229/// - the virtual offset is (memptr.ptr - 1)
230///
231/// In the ARM ABI:
232/// - method pointers are virtual if (memptr.adj & 1) is nonzero
233/// - the this-adjustment is (memptr.adj >> 1)
234/// - the virtual offset is (memptr.ptr)
235/// ARM uses 'adj' for the virtual flag because Thumb functions
236/// may be only single-byte aligned.
237///
238/// If the member is virtual, the adjusted 'this' pointer points
239/// to a vtable pointer from which the virtual offset is applied.
240///
241/// If the member is non-virtual, memptr.ptr is the address of
242/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000243llvm::Value *
244ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
245 llvm::Value *&This,
246 llvm::Value *MemFnPtr,
247 const MemberPointerType *MPT) {
248 CGBuilderTy &Builder = CGF.Builder;
249
250 const FunctionProtoType *FPT =
251 MPT->getPointeeType()->getAs<FunctionProtoType>();
252 const CXXRecordDecl *RD =
253 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
254
Chris Lattner2acc6e32011-07-18 04:24:23 +0000255 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000256 CGM.getTypes().GetFunctionType(
257 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000258
Reid Kleckner92e44d92013-03-22 16:13:10 +0000259 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000260
John McCallbabc9a92010-08-22 00:59:17 +0000261 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
262 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
263 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
264
John McCalld608cdb2010-08-22 10:59:02 +0000265 // Extract memptr.adj, which is in the second field.
266 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000267
268 // Compute the true adjustment.
269 llvm::Value *Adj = RawAdj;
270 if (IsARM)
271 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000272
273 // Apply the adjustment and cast back to the original struct type
274 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000275 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
276 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
277 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000278
279 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000280 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000281
282 // If the LSB in the function pointer is 1, the function pointer points to
283 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000284 llvm::Value *IsVirtual;
285 if (IsARM)
286 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
287 else
288 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
289 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000290 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
291
292 // In the virtual path, the adjustment left 'This' pointing to the
293 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000294 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000295 CGF.EmitBlock(FnVirtual);
296
297 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000298 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000299 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000300 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000301
302 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000303 llvm::Value *VTableOffset = FnAsInt;
304 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
305 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000306
307 // Load the virtual function to call.
308 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000309 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000310 CGF.EmitBranch(FnEnd);
311
312 // In the non-virtual path, the function pointer is actually a
313 // function pointer.
314 CGF.EmitBlock(FnNonVirtual);
315 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000316 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000317
318 // We're done.
319 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000320 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000321 Callee->addIncoming(VirtualFn, FnVirtual);
322 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
323 return Callee;
324}
John McCall3023def2010-08-22 03:04:22 +0000325
John McCall6c2ab1d2010-08-31 21:07:20 +0000326/// Compute an l-value by applying the given pointer-to-member to a
327/// base object.
328llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
329 llvm::Value *Base,
330 llvm::Value *MemPtr,
331 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000332 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000333
334 CGBuilderTy &Builder = CGF.Builder;
335
Micah Villmow956a5a12012-10-25 15:39:14 +0000336 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000337
338 // Cast to char*.
339 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
340
341 // Apply the offset, which we assume is non-null.
342 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
343
344 // Cast the address to the appropriate pointer type, adopting the
345 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000346 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000347 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000348 return Builder.CreateBitCast(Addr, PType);
349}
350
John McCall4d4e5c12012-02-15 01:22:51 +0000351/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
352/// conversion.
353///
354/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000355///
356/// Obligatory offset/adjustment diagram:
357/// <-- offset --> <-- adjustment -->
358/// |--------------------------|----------------------|--------------------|
359/// ^Derived address point ^Base address point ^Member address point
360///
361/// So when converting a base member pointer to a derived member pointer,
362/// we add the offset to the adjustment because the address point has
363/// decreased; and conversely, when converting a derived MP to a base MP
364/// we subtract the offset from the adjustment because the address point
365/// has increased.
366///
367/// The standard forbids (at compile time) conversion to and from
368/// virtual bases, which is why we don't have to consider them here.
369///
370/// The standard forbids (at run time) casting a derived MP to a base
371/// MP when the derived MP does not point to a member of the base.
372/// This is why -1 is a reasonable choice for null data member
373/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000374llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000375ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
376 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000377 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000378 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000379 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
380 E->getCastKind() == CK_ReinterpretMemberPointer);
381
382 // Under Itanium, reinterprets don't require any additional processing.
383 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
384
385 // Use constant emission if we can.
386 if (isa<llvm::Constant>(src))
387 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
388
389 llvm::Constant *adj = getMemberPointerAdjustment(E);
390 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000391
392 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000393 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000394
John McCall4d4e5c12012-02-15 01:22:51 +0000395 const MemberPointerType *destTy =
396 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000397
John McCall0bab0cd2010-08-23 01:21:21 +0000398 // For member data pointers, this is just a matter of adding the
399 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000400 if (destTy->isMemberDataPointer()) {
401 llvm::Value *dst;
402 if (isDerivedToBase)
403 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000404 else
John McCall4d4e5c12012-02-15 01:22:51 +0000405 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000406
407 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000408 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
409 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
410 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000411 }
412
John McCalld608cdb2010-08-22 10:59:02 +0000413 // The this-adjustment is left-shifted by 1 on ARM.
414 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000415 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
416 offset <<= 1;
417 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000418 }
419
John McCall4d4e5c12012-02-15 01:22:51 +0000420 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
421 llvm::Value *dstAdj;
422 if (isDerivedToBase)
423 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000424 else
John McCall4d4e5c12012-02-15 01:22:51 +0000425 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000426
John McCall4d4e5c12012-02-15 01:22:51 +0000427 return Builder.CreateInsertValue(src, dstAdj, 1);
428}
429
430llvm::Constant *
431ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
432 llvm::Constant *src) {
433 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
434 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
435 E->getCastKind() == CK_ReinterpretMemberPointer);
436
437 // Under Itanium, reinterprets don't require any additional processing.
438 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
439
440 // If the adjustment is trivial, we don't need to do anything.
441 llvm::Constant *adj = getMemberPointerAdjustment(E);
442 if (!adj) return src;
443
444 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
445
446 const MemberPointerType *destTy =
447 E->getType()->castAs<MemberPointerType>();
448
449 // For member data pointers, this is just a matter of adding the
450 // offset if the source is non-null.
451 if (destTy->isMemberDataPointer()) {
452 // null maps to null.
453 if (src->isAllOnesValue()) return src;
454
455 if (isDerivedToBase)
456 return llvm::ConstantExpr::getNSWSub(src, adj);
457 else
458 return llvm::ConstantExpr::getNSWAdd(src, adj);
459 }
460
461 // The this-adjustment is left-shifted by 1 on ARM.
462 if (IsARM) {
463 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
464 offset <<= 1;
465 adj = llvm::ConstantInt::get(adj->getType(), offset);
466 }
467
468 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
469 llvm::Constant *dstAdj;
470 if (isDerivedToBase)
471 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
472 else
473 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
474
475 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000476}
John McCallcf2c85e2010-08-22 04:16:24 +0000477
478llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000479ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000480 // Itanium C++ ABI 2.3:
481 // A NULL pointer is represented as -1.
482 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000483 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000484
Reid Kleckner92e44d92013-03-22 16:13:10 +0000485 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000486 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000487 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000488}
489
John McCall5808ce42011-02-03 08:15:49 +0000490llvm::Constant *
491ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
492 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000493 // Itanium C++ ABI 2.3:
494 // A pointer to data member is an offset from the base address of
495 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000496 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000497}
498
John McCall755d8492011-04-12 00:42:48 +0000499llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000500 return BuildMemberPointer(MD, CharUnits::Zero());
501}
502
503llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
504 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000505 assert(MD->isInstance() && "Member function must not be static!");
506 MD = MD->getCanonicalDecl();
507
508 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000509
510 // Get the function pointer (or index if this is a virtual function).
511 llvm::Constant *MemPtr[2];
512 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000513 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000514
Ken Dyck1246ba62011-04-09 01:30:02 +0000515 const ASTContext &Context = getContext();
516 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000517 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000518 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000519
520 if (IsARM) {
521 // ARM C++ ABI 3.2.1:
522 // This ABI specifies that adj contains twice the this
523 // adjustment, plus 1 if the member function is virtual. The
524 // least significant bit of adj then makes exactly the same
525 // discrimination as the least significant bit of ptr does for
526 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000527 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
528 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000529 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000530 } else {
531 // Itanium C++ ABI 2.3:
532 // For a virtual function, [the pointer field] is 1 plus the
533 // virtual table offset (in bytes) of the function,
534 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000535 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
536 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000537 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000538 }
539 } else {
John McCall755d8492011-04-12 00:42:48 +0000540 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000541 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000542 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000543 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000544 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000545 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000546 } else {
John McCall755d8492011-04-12 00:42:48 +0000547 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
548 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000549 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000550 }
John McCall755d8492011-04-12 00:42:48 +0000551 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000552
Reid Kleckner92e44d92013-03-22 16:13:10 +0000553 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
554 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, (IsARM ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000555 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000556 }
John McCall875ab102010-08-22 06:43:33 +0000557
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000558 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000559}
560
Richard Smith2d6a5672012-01-14 04:30:29 +0000561llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
562 QualType MPType) {
563 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
564 const ValueDecl *MPD = MP.getMemberPointerDecl();
565 if (!MPD)
566 return EmitNullMemberPointer(MPT);
567
568 // Compute the this-adjustment.
569 CharUnits ThisAdjustment = CharUnits::Zero();
570 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
571 bool DerivedMember = MP.isMemberPointerToDerivedMember();
572 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
573 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
574 const CXXRecordDecl *Base = RD;
575 const CXXRecordDecl *Derived = Path[I];
576 if (DerivedMember)
577 std::swap(Base, Derived);
578 ThisAdjustment +=
579 getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
580 RD = Path[I];
581 }
582 if (DerivedMember)
583 ThisAdjustment = -ThisAdjustment;
584
585 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
586 return BuildMemberPointer(MD, ThisAdjustment);
587
588 CharUnits FieldOffset =
589 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
590 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
591}
592
John McCalle9fd7eb2010-08-22 08:30:07 +0000593/// The comparison algorithm is pretty easy: the member pointers are
594/// the same if they're either bitwise identical *or* both null.
595///
596/// ARM is different here only because null-ness is more complicated.
597llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000598ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
599 llvm::Value *L,
600 llvm::Value *R,
601 const MemberPointerType *MPT,
602 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000603 CGBuilderTy &Builder = CGF.Builder;
604
John McCalle9fd7eb2010-08-22 08:30:07 +0000605 llvm::ICmpInst::Predicate Eq;
606 llvm::Instruction::BinaryOps And, Or;
607 if (Inequality) {
608 Eq = llvm::ICmpInst::ICMP_NE;
609 And = llvm::Instruction::Or;
610 Or = llvm::Instruction::And;
611 } else {
612 Eq = llvm::ICmpInst::ICMP_EQ;
613 And = llvm::Instruction::And;
614 Or = llvm::Instruction::Or;
615 }
616
John McCall0bab0cd2010-08-23 01:21:21 +0000617 // Member data pointers are easy because there's a unique null
618 // value, so it just comes down to bitwise equality.
619 if (MPT->isMemberDataPointer())
620 return Builder.CreateICmp(Eq, L, R);
621
622 // For member function pointers, the tautologies are more complex.
623 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000624 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000625 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000626 // (L == R) <==> (L.ptr == R.ptr &&
627 // (L.adj == R.adj ||
628 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000629 // The inequality tautologies have exactly the same structure, except
630 // applying De Morgan's laws.
631
632 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
633 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
634
John McCalle9fd7eb2010-08-22 08:30:07 +0000635 // This condition tests whether L.ptr == R.ptr. This must always be
636 // true for equality to hold.
637 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
638
639 // This condition, together with the assumption that L.ptr == R.ptr,
640 // tests whether the pointers are both null. ARM imposes an extra
641 // condition.
642 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
643 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
644
645 // This condition tests whether L.adj == R.adj. If this isn't
646 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000647 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
648 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000649 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
650
651 // Null member function pointers on ARM clear the low bit of Adj,
652 // so the zero condition has to check that neither low bit is set.
653 if (IsARM) {
654 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
655
656 // Compute (l.adj | r.adj) & 1 and test it against zero.
657 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
658 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
659 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
660 "cmp.or.adj");
661 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
662 }
663
664 // Tie together all our conditions.
665 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
666 Result = Builder.CreateBinOp(And, PtrEq, Result,
667 Inequality ? "memptr.ne" : "memptr.eq");
668 return Result;
669}
670
671llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000672ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
673 llvm::Value *MemPtr,
674 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000675 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000676
677 /// For member data pointers, this is just a check against -1.
678 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000679 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000680 llvm::Value *NegativeOne =
681 llvm::Constant::getAllOnesValue(MemPtr->getType());
682 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
683 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000684
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000685 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000686 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000687
688 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
689 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
690
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000691 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
692 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000693 if (IsARM) {
694 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000695 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000696 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000697 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
698 "memptr.isvirtual");
699 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000700 }
701
702 return Result;
703}
John McCall875ab102010-08-22 06:43:33 +0000704
John McCallf16aa102010-08-22 21:01:12 +0000705/// The Itanium ABI requires non-zero initialization only for data
706/// member pointers, for which '0' is a valid offset.
707bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
708 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000709}
John McCall4c40d982010-08-31 07:33:07 +0000710
John McCallecd03b42012-09-25 10:10:39 +0000711/// The Itanium ABI always places an offset to the complete object
712/// at entry -2 in the vtable.
713llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
714 llvm::Value *ptr,
715 QualType type) {
716 // Grab the vtable pointer as an intptr_t*.
717 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
718
719 // Track back to entry -2 and pull out the offset there.
720 llvm::Value *offsetPtr =
721 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
722 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
723 offset->setAlignment(CGF.PointerAlignInBytes);
724
725 // Apply the offset.
726 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
727 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
728}
729
John McCall4c40d982010-08-31 07:33:07 +0000730/// The generic ABI passes 'this', plus a VTT if it's initializing a
731/// base subobject.
732void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
733 CXXCtorType Type,
734 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000735 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000736 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000737
738 // 'this' is already there.
739
740 // Check if we need to add a VTT parameter (which has type void **).
741 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
742 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
743}
744
745/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
746void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
747 CXXCtorType Type,
748 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000749 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000750 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
751 ResTy = ArgTys[0];
752}
753
754/// The generic ABI passes 'this', plus a VTT if it's destroying a
755/// base subobject.
756void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
757 CXXDtorType Type,
758 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000759 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000760 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000761
762 // 'this' is already there.
763
764 // Check if we need to add a VTT parameter (which has type void **).
765 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
766 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
767}
768
769/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
770/// for non-deleting destructors.
771void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
772 CXXDtorType Type,
773 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000774 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000775 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
776
777 if (Type != Dtor_Deleting)
778 ResTy = ArgTys[0];
779}
780
781void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
782 QualType &ResTy,
783 FunctionArgList &Params) {
784 /// Create the 'this' variable.
785 BuildThisParam(CGF, Params);
786
787 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
788 assert(MD->isInstance());
789
790 // Check if we need a VTT parameter as well.
791 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000792 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000793
794 // FIXME: avoid the fake decl
795 QualType T = Context.getPointerType(Context.VoidPtrTy);
796 ImplicitParamDecl *VTTDecl
797 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
798 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000799 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000800 getVTTDecl(CGF) = VTTDecl;
801 }
802}
803
804void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
805 QualType &ResTy,
806 FunctionArgList &Params) {
807 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
808
809 // Return 'this' from certain constructors and destructors.
810 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000811 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000812}
813
814void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
815 /// Initialize the 'this' slot.
816 EmitThisParam(CGF);
817
818 /// Initialize the 'vtt' slot if needed.
819 if (getVTTDecl(CGF)) {
820 getVTTValue(CGF)
821 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
822 "vtt");
823 }
824}
825
826void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
827 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
828
829 /// Initialize the return slot to 'this' at the start of the
830 /// function.
831 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000832 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000833}
834
Manman Ren63fd4082013-03-20 16:59:38 +0000835llvm::Value *ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000836 const CXXConstructorDecl *D,
837 CXXCtorType Type, bool ForVirtualBase,
838 bool Delegating,
839 llvm::Value *This,
840 CallExpr::const_arg_iterator ArgBeg,
841 CallExpr::const_arg_iterator ArgEnd) {
842 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
843 Delegating);
844 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
845 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
846
847 // FIXME: Provide a source location here.
848 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
849 VTT, VTTTy, ArgBeg, ArgEnd);
Manman Ren63fd4082013-03-20 16:59:38 +0000850 return Callee;
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000851}
852
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000853RValue ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
854 const CXXDestructorDecl *Dtor,
855 CXXDtorType DtorType,
856 SourceLocation CallLoc,
857 ReturnValueSlot ReturnValue,
858 llvm::Value *This) {
859 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
860
861 const CGFunctionInfo *FInfo
862 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
863 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
864 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, DtorType, This, Ty);
865
866 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
867 /*ImplicitParam=*/0, QualType(), 0, 0);
868}
869
John McCall4c40d982010-08-31 07:33:07 +0000870void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
871 RValue RV, QualType ResultType) {
872 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
873 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
874
875 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000876 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000877 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
878 RValue Undef = RValue::get(llvm::UndefValue::get(T));
879 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
880}
John McCall1e7fe752010-09-02 09:58:18 +0000881
882/************************** Array allocation cookies **************************/
883
John McCalle2b45e22012-05-01 05:23:51 +0000884CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
885 // The array cookie is a size_t; pad that up to the element alignment.
886 // The cookie is actually right-justified in that space.
887 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
888 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000889}
890
891llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
892 llvm::Value *NewPtr,
893 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000894 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000895 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000896 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000897
Micah Villmow956a5a12012-10-25 15:39:14 +0000898 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000899
John McCall9cb2cee2010-09-02 10:25:57 +0000900 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000901 QualType SizeTy = Ctx.getSizeType();
902 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
903
904 // The size of the cookie.
905 CharUnits CookieSize =
906 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000907 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000908
909 // Compute an offset to the cookie.
910 llvm::Value *CookiePtr = NewPtr;
911 CharUnits CookieOffset = CookieSize - SizeSize;
912 if (!CookieOffset.isZero())
913 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
914 CookieOffset.getQuantity());
915
916 // Write the number of elements into the appropriate slot.
917 llvm::Value *NumElementsPtr
918 = CGF.Builder.CreateBitCast(CookiePtr,
919 CGF.ConvertType(SizeTy)->getPointerTo(AS));
920 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
921
922 // Finally, compute a pointer to the actual data buffer by skipping
923 // over the cookie completely.
924 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
925 CookieSize.getQuantity());
926}
927
John McCalle2b45e22012-05-01 05:23:51 +0000928llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
929 llvm::Value *allocPtr,
930 CharUnits cookieSize) {
931 // The element size is right-justified in the cookie.
932 llvm::Value *numElementsPtr = allocPtr;
933 CharUnits numElementsOffset =
934 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
935 if (!numElementsOffset.isZero())
936 numElementsPtr =
937 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
938 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000939
Micah Villmow956a5a12012-10-25 15:39:14 +0000940 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000941 numElementsPtr =
942 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
943 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000944}
945
John McCalle2b45e22012-05-01 05:23:51 +0000946CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000947 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000948 // struct array_cookie {
949 // std::size_t element_size; // element_size != 0
950 // std::size_t element_count;
951 // };
John McCallf3bbb152013-01-25 23:36:19 +0000952 // But the base ABI doesn't give anything an alignment greater than
953 // 8, so we can dismiss this as typical ABI-author blindness to
954 // actual language complexity and round up to the element alignment.
955 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
956 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000957}
958
959llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000960 llvm::Value *newPtr,
961 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000962 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000963 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000964 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000965
John McCallf3bbb152013-01-25 23:36:19 +0000966 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
967 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000968
969 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000970 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000971
972 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000973 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
974 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
975 getContext().getTypeSizeInChars(elementType).getQuantity());
976 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000977
978 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000979 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
980 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000981
982 // Finally, compute a pointer to the actual data buffer by skipping
983 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000984 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
985 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
986 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000987}
988
John McCalle2b45e22012-05-01 05:23:51 +0000989llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
990 llvm::Value *allocPtr,
991 CharUnits cookieSize) {
992 // The number of elements is at offset sizeof(size_t) relative to
993 // the allocated pointer.
994 llvm::Value *numElementsPtr
995 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000996
Micah Villmow956a5a12012-10-25 15:39:14 +0000997 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000998 numElementsPtr =
999 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1000 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001001}
1002
John McCall5cd91b52010-09-08 01:44:27 +00001003/*********************** Static local initialization **************************/
1004
1005static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001006 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001007 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001008 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001009 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001010 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001011 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001012 llvm::AttributeSet::get(CGM.getLLVMContext(),
1013 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001014 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001015}
1016
1017static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001018 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001019 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001020 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001021 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001022 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001023 llvm::AttributeSet::get(CGM.getLLVMContext(),
1024 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001025 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001026}
1027
1028static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001029 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001030 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001031 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001032 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001033 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001034 llvm::AttributeSet::get(CGM.getLLVMContext(),
1035 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001036 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001037}
1038
1039namespace {
1040 struct CallGuardAbort : EHScopeStack::Cleanup {
1041 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001042 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001043
John McCallad346f42011-07-12 20:27:29 +00001044 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001045 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1046 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001047 }
1048 };
1049}
1050
1051/// The ARM code here follows the Itanium code closely enough that we
1052/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001053void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1054 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001055 llvm::GlobalVariable *var,
1056 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001057 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001058
Richard Smith04e51762013-04-14 23:01:42 +00001059 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001060 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001061 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1062 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001063
Anders Carlsson173d5122011-04-27 04:37:08 +00001064 // If we have a global variable with internal linkage and thread-safe statics
1065 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001066 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1067
1068 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001069 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001070 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001071 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001072 // Guard variables are 64 bits in the generic ABI and size width on ARM
1073 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1074 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001075 }
John McCall355bba72012-03-30 21:00:39 +00001076 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001077
John McCall355bba72012-03-30 21:00:39 +00001078 // Create the guard variable if we don't already have it (as we
1079 // might if we're double-emitting this function body).
1080 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1081 if (!guard) {
1082 // Mangle the name for the guard.
1083 SmallString<256> guardName;
1084 {
1085 llvm::raw_svector_ostream out(guardName);
1086 getMangleContext().mangleItaniumGuardVariable(&D, out);
1087 out.flush();
1088 }
John McCall112c9672010-11-02 21:04:24 +00001089
John McCall355bba72012-03-30 21:00:39 +00001090 // Create the guard variable with a zero-initializer.
1091 // Just absorb linkage and visibility from the guarded variable.
1092 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1093 false, var->getLinkage(),
1094 llvm::ConstantInt::get(guardTy, 0),
1095 guardName.str());
1096 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001097 // If the variable is thread-local, so is its guard variable.
1098 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001099
1100 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1101 }
John McCall49d26d22012-03-30 07:09:50 +00001102
John McCall5cd91b52010-09-08 01:44:27 +00001103 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001104 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001105
1106 // ARM C++ ABI 3.2.3.1:
1107 // To support the potential use of initialization guard variables
1108 // as semaphores that are the target of ARM SWP and LDREX/STREX
1109 // synchronizing instructions we define a static initialization
1110 // guard variable to be a 4-byte aligned, 4- byte word with the
1111 // following inline access protocol.
1112 // #define INITIALIZED 1
1113 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1114 // if (__cxa_guard_acquire(&obj_guard))
1115 // ...
1116 // }
John McCall0502a222011-06-17 07:33:57 +00001117 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001118 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001119 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1120 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001121 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001122
1123 // Itanium C++ ABI 3.3.2:
1124 // The following is pseudo-code showing how these functions can be used:
1125 // if (obj_guard.first_byte == 0) {
1126 // if ( __cxa_guard_acquire (&obj_guard) ) {
1127 // try {
1128 // ... initialize the object ...;
1129 // } catch (...) {
1130 // __cxa_guard_abort (&obj_guard);
1131 // throw;
1132 // }
1133 // ... queue object destructor with __cxa_atexit() ...;
1134 // __cxa_guard_release (&obj_guard);
1135 // }
1136 // }
1137 } else {
1138 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001139 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001140 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001141 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001142
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001143 // Itanium ABI:
1144 // An implementation supporting thread-safety on multiprocessor
1145 // systems must also guarantee that references to the initialized
1146 // object do not occur before the load of the initialization flag.
1147 //
1148 // In LLVM, we do this by marking the load Acquire.
1149 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001150 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001151
John McCall355bba72012-03-30 21:00:39 +00001152 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001153 }
1154
1155 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1156 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1157
1158 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001159 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001160
1161 CGF.EmitBlock(InitCheckBlock);
1162
1163 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001164 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001165 // Call __cxa_guard_acquire.
1166 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001167 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001168
1169 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1170
1171 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1172 InitBlock, EndBlock);
1173
1174 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001175 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001176
1177 CGF.EmitBlock(InitBlock);
1178 }
1179
1180 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001181 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001182
John McCall0502a222011-06-17 07:33:57 +00001183 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001184 // Pop the guard-abort cleanup if we pushed one.
1185 CGF.PopCleanupBlock();
1186
1187 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001188 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001189 } else {
John McCall355bba72012-03-30 21:00:39 +00001190 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001191 }
1192
1193 CGF.EmitBlock(EndBlock);
1194}
John McCall20bb1752012-05-01 06:13:13 +00001195
1196/// Register a global destructor using __cxa_atexit.
1197static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1198 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001199 llvm::Constant *addr,
1200 bool TLS) {
1201 const char *Name = TLS ? "__cxa_thread_atexit" : "__cxa_atexit";
1202
John McCall20bb1752012-05-01 06:13:13 +00001203 // We're assuming that the destructor function is something we can
1204 // reasonably call with the default CC. Go ahead and cast it to the
1205 // right prototype.
1206 llvm::Type *dtorTy =
1207 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1208
1209 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1210 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1211 llvm::FunctionType *atexitTy =
1212 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1213
1214 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001215 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001216 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1217 fn->setDoesNotThrow();
1218
1219 // Create a variable that binds the atexit to this shared object.
1220 llvm::Constant *handle =
1221 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1222
1223 llvm::Value *args[] = {
1224 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1225 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1226 handle
1227 };
John McCallbd7370a2013-02-28 19:01:20 +00001228 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001229}
1230
1231/// Register a global destructor as best as we know how.
1232void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001233 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001234 llvm::Constant *dtor,
1235 llvm::Constant *addr) {
1236 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001237 if (CGM.getCodeGenOpts().CXAAtExit)
1238 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1239
1240 if (D.getTLSKind())
1241 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001242
1243 // In Apple kexts, we want to add a global destructor entry.
1244 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001245 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001246 // Generate a global destructor entry.
1247 return CGM.AddCXXDtorEntry(dtor, addr);
1248 }
1249
1250 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1251}