blob: bb2c93befc1a1f6baaa20771735ef0dd63e5d9c3 [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
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000115 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
116 const CXXDestructorDecl *Dtor,
117 CXXDtorType DtorType,
118 SourceLocation CallLoc,
119 ReturnValueSlot ReturnValue,
120 llvm::Value *This);
121
Joao Matos285baac2012-07-17 17:10:11 +0000122 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000123 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000124
John McCalle2b45e22012-05-01 05:23:51 +0000125 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000126 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
127 llvm::Value *NewPtr,
128 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000129 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000130 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000131 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
132 llvm::Value *allocPtr,
133 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000134
John McCall3030eb82010-11-06 09:44:32 +0000135 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000136 llvm::GlobalVariable *DeclPtr, bool PerformInit);
John McCall20bb1752012-05-01 06:13:13 +0000137 void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
138 llvm::Constant *addr);
Charles Davis3a811f12010-05-25 19:52:27 +0000139};
John McCallee79a4c2010-08-21 22:46:04 +0000140
141class ARMCXXABI : public ItaniumCXXABI {
142public:
John McCallbabc9a92010-08-22 00:59:17 +0000143 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000144
145 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
146 CXXCtorType T,
147 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000148 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000149
150 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
151 CXXDtorType T,
152 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000153 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000154
155 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
156 QualType &ResTy,
157 FunctionArgList &Params);
158
159 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
160
161 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
162
John McCalle2b45e22012-05-01 05:23:51 +0000163 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000164 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
165 llvm::Value *NewPtr,
166 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000167 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000168 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000169 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
170 CharUnits cookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000171
172private:
173 /// \brief Returns true if the given instance method is one of the
174 /// kinds that the ARM ABI says returns 'this'.
175 static bool HasThisReturn(GlobalDecl GD) {
176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
177 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
178 (isa<CXXConstructorDecl>(MD)));
179 }
John McCallee79a4c2010-08-21 22:46:04 +0000180};
Charles Davis3a811f12010-05-25 19:52:27 +0000181}
182
Charles Davis071cc7d2010-08-16 03:33:14 +0000183CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall96fcde02013-01-25 23:36:14 +0000184 switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
185 // For IR-generation purposes, there's no significant difference
186 // between the ARM and iOS ABIs.
187 case TargetCXXABI::GenericARM:
188 case TargetCXXABI::iOS:
189 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000190
Tim Northoverc264e162013-01-31 12:13:10 +0000191 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
192 // include the other 32-bit ARM oddities: constructor/destructor return values
193 // and array cookies.
194 case TargetCXXABI::GenericAArch64:
195 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
196
John McCall96fcde02013-01-25 23:36:14 +0000197 case TargetCXXABI::GenericItanium:
198 return new ItaniumCXXABI(CGM);
199
200 case TargetCXXABI::Microsoft:
201 llvm_unreachable("Microsoft ABI is not Itanium-based");
202 }
203 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000204}
205
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000206llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000207ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
208 if (MPT->isMemberDataPointer())
209 return getPtrDiffTy();
Chris Lattner7650d952011-06-18 22:49:11 +0000210 return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000211}
212
John McCallbabc9a92010-08-22 00:59:17 +0000213/// In the Itanium and ARM ABIs, method pointers have the form:
214/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
215///
216/// In the Itanium ABI:
217/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
218/// - the this-adjustment is (memptr.adj)
219/// - the virtual offset is (memptr.ptr - 1)
220///
221/// In the ARM ABI:
222/// - method pointers are virtual if (memptr.adj & 1) is nonzero
223/// - the this-adjustment is (memptr.adj >> 1)
224/// - the virtual offset is (memptr.ptr)
225/// ARM uses 'adj' for the virtual flag because Thumb functions
226/// may be only single-byte aligned.
227///
228/// If the member is virtual, the adjusted 'this' pointer points
229/// to a vtable pointer from which the virtual offset is applied.
230///
231/// If the member is non-virtual, memptr.ptr is the address of
232/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000233llvm::Value *
234ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
235 llvm::Value *&This,
236 llvm::Value *MemFnPtr,
237 const MemberPointerType *MPT) {
238 CGBuilderTy &Builder = CGF.Builder;
239
240 const FunctionProtoType *FPT =
241 MPT->getPointeeType()->getAs<FunctionProtoType>();
242 const CXXRecordDecl *RD =
243 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
244
Chris Lattner2acc6e32011-07-18 04:24:23 +0000245 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000246 CGM.getTypes().GetFunctionType(
247 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000248
Chris Lattner2acc6e32011-07-18 04:24:23 +0000249 llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000250 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000251
John McCallbabc9a92010-08-22 00:59:17 +0000252 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
253 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
254 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
255
John McCalld608cdb2010-08-22 10:59:02 +0000256 // Extract memptr.adj, which is in the second field.
257 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000258
259 // Compute the true adjustment.
260 llvm::Value *Adj = RawAdj;
261 if (IsARM)
262 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000263
264 // Apply the adjustment and cast back to the original struct type
265 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000266 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
267 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
268 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000269
270 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000271 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000272
273 // If the LSB in the function pointer is 1, the function pointer points to
274 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000275 llvm::Value *IsVirtual;
276 if (IsARM)
277 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
278 else
279 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
280 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000281 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
282
283 // In the virtual path, the adjustment left 'This' pointing to the
284 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000285 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000286 CGF.EmitBlock(FnVirtual);
287
288 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000289 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000290 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000291 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000292
293 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000294 llvm::Value *VTableOffset = FnAsInt;
295 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
296 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000297
298 // Load the virtual function to call.
299 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000300 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000301 CGF.EmitBranch(FnEnd);
302
303 // In the non-virtual path, the function pointer is actually a
304 // function pointer.
305 CGF.EmitBlock(FnNonVirtual);
306 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000307 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000308
309 // We're done.
310 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000311 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000312 Callee->addIncoming(VirtualFn, FnVirtual);
313 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
314 return Callee;
315}
John McCall3023def2010-08-22 03:04:22 +0000316
John McCall6c2ab1d2010-08-31 21:07:20 +0000317/// Compute an l-value by applying the given pointer-to-member to a
318/// base object.
319llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
320 llvm::Value *Base,
321 llvm::Value *MemPtr,
322 const MemberPointerType *MPT) {
323 assert(MemPtr->getType() == getPtrDiffTy());
324
325 CGBuilderTy &Builder = CGF.Builder;
326
Micah Villmow956a5a12012-10-25 15:39:14 +0000327 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000328
329 // Cast to char*.
330 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
331
332 // Apply the offset, which we assume is non-null.
333 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
334
335 // Cast the address to the appropriate pointer type, adopting the
336 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000337 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000338 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000339 return Builder.CreateBitCast(Addr, PType);
340}
341
John McCall4d4e5c12012-02-15 01:22:51 +0000342/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
343/// conversion.
344///
345/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000346///
347/// Obligatory offset/adjustment diagram:
348/// <-- offset --> <-- adjustment -->
349/// |--------------------------|----------------------|--------------------|
350/// ^Derived address point ^Base address point ^Member address point
351///
352/// So when converting a base member pointer to a derived member pointer,
353/// we add the offset to the adjustment because the address point has
354/// decreased; and conversely, when converting a derived MP to a base MP
355/// we subtract the offset from the adjustment because the address point
356/// has increased.
357///
358/// The standard forbids (at compile time) conversion to and from
359/// virtual bases, which is why we don't have to consider them here.
360///
361/// The standard forbids (at run time) casting a derived MP to a base
362/// MP when the derived MP does not point to a member of the base.
363/// This is why -1 is a reasonable choice for null data member
364/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000365llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000366ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
367 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000368 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000369 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000370 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
371 E->getCastKind() == CK_ReinterpretMemberPointer);
372
373 // Under Itanium, reinterprets don't require any additional processing.
374 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
375
376 // Use constant emission if we can.
377 if (isa<llvm::Constant>(src))
378 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
379
380 llvm::Constant *adj = getMemberPointerAdjustment(E);
381 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000382
383 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000384 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000385
John McCall4d4e5c12012-02-15 01:22:51 +0000386 const MemberPointerType *destTy =
387 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000388
John McCall0bab0cd2010-08-23 01:21:21 +0000389 // For member data pointers, this is just a matter of adding the
390 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000391 if (destTy->isMemberDataPointer()) {
392 llvm::Value *dst;
393 if (isDerivedToBase)
394 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000395 else
John McCall4d4e5c12012-02-15 01:22:51 +0000396 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000397
398 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000399 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
400 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
401 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000402 }
403
John McCalld608cdb2010-08-22 10:59:02 +0000404 // The this-adjustment is left-shifted by 1 on ARM.
405 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000406 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
407 offset <<= 1;
408 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000409 }
410
John McCall4d4e5c12012-02-15 01:22:51 +0000411 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
412 llvm::Value *dstAdj;
413 if (isDerivedToBase)
414 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000415 else
John McCall4d4e5c12012-02-15 01:22:51 +0000416 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000417
John McCall4d4e5c12012-02-15 01:22:51 +0000418 return Builder.CreateInsertValue(src, dstAdj, 1);
419}
420
421llvm::Constant *
422ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
423 llvm::Constant *src) {
424 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
425 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
426 E->getCastKind() == CK_ReinterpretMemberPointer);
427
428 // Under Itanium, reinterprets don't require any additional processing.
429 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
430
431 // If the adjustment is trivial, we don't need to do anything.
432 llvm::Constant *adj = getMemberPointerAdjustment(E);
433 if (!adj) return src;
434
435 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
436
437 const MemberPointerType *destTy =
438 E->getType()->castAs<MemberPointerType>();
439
440 // For member data pointers, this is just a matter of adding the
441 // offset if the source is non-null.
442 if (destTy->isMemberDataPointer()) {
443 // null maps to null.
444 if (src->isAllOnesValue()) return src;
445
446 if (isDerivedToBase)
447 return llvm::ConstantExpr::getNSWSub(src, adj);
448 else
449 return llvm::ConstantExpr::getNSWAdd(src, adj);
450 }
451
452 // The this-adjustment is left-shifted by 1 on ARM.
453 if (IsARM) {
454 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
455 offset <<= 1;
456 adj = llvm::ConstantInt::get(adj->getType(), offset);
457 }
458
459 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
460 llvm::Constant *dstAdj;
461 if (isDerivedToBase)
462 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
463 else
464 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
465
466 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000467}
John McCallcf2c85e2010-08-22 04:16:24 +0000468
469llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000470ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000471 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCall0bab0cd2010-08-23 01:21:21 +0000472
473 // Itanium C++ ABI 2.3:
474 // A NULL pointer is represented as -1.
475 if (MPT->isMemberDataPointer())
476 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000477
478 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
479 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000480 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000481}
482
John McCall5808ce42011-02-03 08:15:49 +0000483llvm::Constant *
484ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
485 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000486 // Itanium C++ ABI 2.3:
487 // A pointer to data member is an offset from the base address of
488 // the class object containing it, represented as a ptrdiff_t
John McCall5808ce42011-02-03 08:15:49 +0000489 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000490}
491
John McCall755d8492011-04-12 00:42:48 +0000492llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000493 return BuildMemberPointer(MD, CharUnits::Zero());
494}
495
496llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
497 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000498 assert(MD->isInstance() && "Member function must not be static!");
499 MD = MD->getCanonicalDecl();
500
501 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000502 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000503
504 // Get the function pointer (or index if this is a virtual function).
505 llvm::Constant *MemPtr[2];
506 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000507 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000508
Ken Dyck1246ba62011-04-09 01:30:02 +0000509 const ASTContext &Context = getContext();
510 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000512 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000513
514 if (IsARM) {
515 // ARM C++ ABI 3.2.1:
516 // This ABI specifies that adj contains twice the this
517 // adjustment, plus 1 if the member function is virtual. The
518 // least significant bit of adj then makes exactly the same
519 // discrimination as the least significant bit of ptr does for
520 // Itanium.
521 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000522 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
523 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000524 } else {
525 // Itanium C++ ABI 2.3:
526 // For a virtual function, [the pointer field] is 1 plus the
527 // virtual table offset (in bytes) of the function,
528 // represented as a ptrdiff_t.
529 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
Richard Smith2d6a5672012-01-14 04:30:29 +0000530 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
531 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000532 }
533 } else {
John McCall755d8492011-04-12 00:42:48 +0000534 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000535 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000536 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000537 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000538 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000539 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000540 } else {
John McCall755d8492011-04-12 00:42:48 +0000541 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
542 // function type is incomplete.
543 Ty = ptrdiff_t;
John McCalld608cdb2010-08-22 10:59:02 +0000544 }
John McCall755d8492011-04-12 00:42:48 +0000545 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000546
John McCall379b5152011-04-11 07:02:50 +0000547 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
Richard Smith2d6a5672012-01-14 04:30:29 +0000548 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
549 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000550 }
John McCall875ab102010-08-22 06:43:33 +0000551
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000552 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000553}
554
Richard Smith2d6a5672012-01-14 04:30:29 +0000555llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
556 QualType MPType) {
557 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
558 const ValueDecl *MPD = MP.getMemberPointerDecl();
559 if (!MPD)
560 return EmitNullMemberPointer(MPT);
561
562 // Compute the this-adjustment.
563 CharUnits ThisAdjustment = CharUnits::Zero();
564 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
565 bool DerivedMember = MP.isMemberPointerToDerivedMember();
566 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
567 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
568 const CXXRecordDecl *Base = RD;
569 const CXXRecordDecl *Derived = Path[I];
570 if (DerivedMember)
571 std::swap(Base, Derived);
572 ThisAdjustment +=
573 getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
574 RD = Path[I];
575 }
576 if (DerivedMember)
577 ThisAdjustment = -ThisAdjustment;
578
579 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
580 return BuildMemberPointer(MD, ThisAdjustment);
581
582 CharUnits FieldOffset =
583 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
584 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
585}
586
John McCalle9fd7eb2010-08-22 08:30:07 +0000587/// The comparison algorithm is pretty easy: the member pointers are
588/// the same if they're either bitwise identical *or* both null.
589///
590/// ARM is different here only because null-ness is more complicated.
591llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000592ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
593 llvm::Value *L,
594 llvm::Value *R,
595 const MemberPointerType *MPT,
596 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000597 CGBuilderTy &Builder = CGF.Builder;
598
John McCalle9fd7eb2010-08-22 08:30:07 +0000599 llvm::ICmpInst::Predicate Eq;
600 llvm::Instruction::BinaryOps And, Or;
601 if (Inequality) {
602 Eq = llvm::ICmpInst::ICMP_NE;
603 And = llvm::Instruction::Or;
604 Or = llvm::Instruction::And;
605 } else {
606 Eq = llvm::ICmpInst::ICMP_EQ;
607 And = llvm::Instruction::And;
608 Or = llvm::Instruction::Or;
609 }
610
John McCall0bab0cd2010-08-23 01:21:21 +0000611 // Member data pointers are easy because there's a unique null
612 // value, so it just comes down to bitwise equality.
613 if (MPT->isMemberDataPointer())
614 return Builder.CreateICmp(Eq, L, R);
615
616 // For member function pointers, the tautologies are more complex.
617 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000618 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000619 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000620 // (L == R) <==> (L.ptr == R.ptr &&
621 // (L.adj == R.adj ||
622 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000623 // The inequality tautologies have exactly the same structure, except
624 // applying De Morgan's laws.
625
626 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
627 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
628
John McCalle9fd7eb2010-08-22 08:30:07 +0000629 // This condition tests whether L.ptr == R.ptr. This must always be
630 // true for equality to hold.
631 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
632
633 // This condition, together with the assumption that L.ptr == R.ptr,
634 // tests whether the pointers are both null. ARM imposes an extra
635 // condition.
636 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
637 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
638
639 // This condition tests whether L.adj == R.adj. If this isn't
640 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000641 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
642 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000643 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
644
645 // Null member function pointers on ARM clear the low bit of Adj,
646 // so the zero condition has to check that neither low bit is set.
647 if (IsARM) {
648 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
649
650 // Compute (l.adj | r.adj) & 1 and test it against zero.
651 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
652 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
653 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
654 "cmp.or.adj");
655 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
656 }
657
658 // Tie together all our conditions.
659 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
660 Result = Builder.CreateBinOp(And, PtrEq, Result,
661 Inequality ? "memptr.ne" : "memptr.eq");
662 return Result;
663}
664
665llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000666ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
667 llvm::Value *MemPtr,
668 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000669 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000670
671 /// For member data pointers, this is just a check against -1.
672 if (MPT->isMemberDataPointer()) {
673 assert(MemPtr->getType() == getPtrDiffTy());
674 llvm::Value *NegativeOne =
675 llvm::Constant::getAllOnesValue(MemPtr->getType());
676 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
677 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000678
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000679 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000680 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000681
682 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
683 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
684
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000685 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
686 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000687 if (IsARM) {
688 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000689 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000690 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000691 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
692 "memptr.isvirtual");
693 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000694 }
695
696 return Result;
697}
John McCall875ab102010-08-22 06:43:33 +0000698
John McCallf16aa102010-08-22 21:01:12 +0000699/// The Itanium ABI requires non-zero initialization only for data
700/// member pointers, for which '0' is a valid offset.
701bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
702 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000703}
John McCall4c40d982010-08-31 07:33:07 +0000704
John McCallecd03b42012-09-25 10:10:39 +0000705/// The Itanium ABI always places an offset to the complete object
706/// at entry -2 in the vtable.
707llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
708 llvm::Value *ptr,
709 QualType type) {
710 // Grab the vtable pointer as an intptr_t*.
711 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
712
713 // Track back to entry -2 and pull out the offset there.
714 llvm::Value *offsetPtr =
715 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
716 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
717 offset->setAlignment(CGF.PointerAlignInBytes);
718
719 // Apply the offset.
720 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
721 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
722}
723
John McCall4c40d982010-08-31 07:33:07 +0000724/// The generic ABI passes 'this', plus a VTT if it's initializing a
725/// base subobject.
726void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
727 CXXCtorType Type,
728 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000729 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000730 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000731
732 // 'this' is already there.
733
734 // Check if we need to add a VTT parameter (which has type void **).
735 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
736 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
737}
738
739/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
740void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
741 CXXCtorType Type,
742 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000743 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000744 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
745 ResTy = ArgTys[0];
746}
747
748/// The generic ABI passes 'this', plus a VTT if it's destroying a
749/// base subobject.
750void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
751 CXXDtorType Type,
752 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000753 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000754 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000755
756 // 'this' is already there.
757
758 // Check if we need to add a VTT parameter (which has type void **).
759 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
760 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
761}
762
763/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
764/// for non-deleting destructors.
765void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
766 CXXDtorType Type,
767 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000768 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000769 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
770
771 if (Type != Dtor_Deleting)
772 ResTy = ArgTys[0];
773}
774
775void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
776 QualType &ResTy,
777 FunctionArgList &Params) {
778 /// Create the 'this' variable.
779 BuildThisParam(CGF, Params);
780
781 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
782 assert(MD->isInstance());
783
784 // Check if we need a VTT parameter as well.
785 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000786 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000787
788 // FIXME: avoid the fake decl
789 QualType T = Context.getPointerType(Context.VoidPtrTy);
790 ImplicitParamDecl *VTTDecl
791 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
792 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000793 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000794 getVTTDecl(CGF) = VTTDecl;
795 }
796}
797
798void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
799 QualType &ResTy,
800 FunctionArgList &Params) {
801 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
802
803 // Return 'this' from certain constructors and destructors.
804 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000805 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000806}
807
808void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
809 /// Initialize the 'this' slot.
810 EmitThisParam(CGF);
811
812 /// Initialize the 'vtt' slot if needed.
813 if (getVTTDecl(CGF)) {
814 getVTTValue(CGF)
815 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
816 "vtt");
817 }
818}
819
820void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
821 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
822
823 /// Initialize the return slot to 'this' at the start of the
824 /// function.
825 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000826 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000827}
828
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000829RValue ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
830 const CXXDestructorDecl *Dtor,
831 CXXDtorType DtorType,
832 SourceLocation CallLoc,
833 ReturnValueSlot ReturnValue,
834 llvm::Value *This) {
835 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
836
837 const CGFunctionInfo *FInfo
838 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
839 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
840 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, DtorType, This, Ty);
841
842 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
843 /*ImplicitParam=*/0, QualType(), 0, 0);
844}
845
John McCall4c40d982010-08-31 07:33:07 +0000846void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
847 RValue RV, QualType ResultType) {
848 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
849 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
850
851 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000852 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000853 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
854 RValue Undef = RValue::get(llvm::UndefValue::get(T));
855 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
856}
John McCall1e7fe752010-09-02 09:58:18 +0000857
858/************************** Array allocation cookies **************************/
859
John McCalle2b45e22012-05-01 05:23:51 +0000860CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
861 // The array cookie is a size_t; pad that up to the element alignment.
862 // The cookie is actually right-justified in that space.
863 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
864 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000865}
866
867llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
868 llvm::Value *NewPtr,
869 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000870 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000871 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000872 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000873
Micah Villmow956a5a12012-10-25 15:39:14 +0000874 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000875
John McCall9cb2cee2010-09-02 10:25:57 +0000876 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000877 QualType SizeTy = Ctx.getSizeType();
878 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
879
880 // The size of the cookie.
881 CharUnits CookieSize =
882 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000883 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000884
885 // Compute an offset to the cookie.
886 llvm::Value *CookiePtr = NewPtr;
887 CharUnits CookieOffset = CookieSize - SizeSize;
888 if (!CookieOffset.isZero())
889 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
890 CookieOffset.getQuantity());
891
892 // Write the number of elements into the appropriate slot.
893 llvm::Value *NumElementsPtr
894 = CGF.Builder.CreateBitCast(CookiePtr,
895 CGF.ConvertType(SizeTy)->getPointerTo(AS));
896 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
897
898 // Finally, compute a pointer to the actual data buffer by skipping
899 // over the cookie completely.
900 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
901 CookieSize.getQuantity());
902}
903
John McCalle2b45e22012-05-01 05:23:51 +0000904llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
905 llvm::Value *allocPtr,
906 CharUnits cookieSize) {
907 // The element size is right-justified in the cookie.
908 llvm::Value *numElementsPtr = allocPtr;
909 CharUnits numElementsOffset =
910 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
911 if (!numElementsOffset.isZero())
912 numElementsPtr =
913 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
914 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000915
Micah Villmow956a5a12012-10-25 15:39:14 +0000916 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000917 numElementsPtr =
918 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
919 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000920}
921
John McCalle2b45e22012-05-01 05:23:51 +0000922CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000923 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000924 // struct array_cookie {
925 // std::size_t element_size; // element_size != 0
926 // std::size_t element_count;
927 // };
John McCallf3bbb152013-01-25 23:36:19 +0000928 // But the base ABI doesn't give anything an alignment greater than
929 // 8, so we can dismiss this as typical ABI-author blindness to
930 // actual language complexity and round up to the element alignment.
931 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
932 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000933}
934
935llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000936 llvm::Value *newPtr,
937 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000938 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000939 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000940 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000941
John McCallf3bbb152013-01-25 23:36:19 +0000942 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
943 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000944
945 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000946 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000947
948 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000949 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
950 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
951 getContext().getTypeSizeInChars(elementType).getQuantity());
952 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000953
954 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000955 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
956 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000957
958 // Finally, compute a pointer to the actual data buffer by skipping
959 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000960 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
961 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
962 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000963}
964
John McCalle2b45e22012-05-01 05:23:51 +0000965llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
966 llvm::Value *allocPtr,
967 CharUnits cookieSize) {
968 // The number of elements is at offset sizeof(size_t) relative to
969 // the allocated pointer.
970 llvm::Value *numElementsPtr
971 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000972
Micah Villmow956a5a12012-10-25 15:39:14 +0000973 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000974 numElementsPtr =
975 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
976 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000977}
978
John McCall5cd91b52010-09-08 01:44:27 +0000979/*********************** Static local initialization **************************/
980
981static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000982 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000983 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000984 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +0000985 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +0000986 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000987 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +0000988 llvm::AttributeSet::get(CGM.getLLVMContext(),
989 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +0000990 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000991}
992
993static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000994 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000995 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000996 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000997 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000998 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +0000999 llvm::AttributeSet::get(CGM.getLLVMContext(),
1000 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001001 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001002}
1003
1004static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001005 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001006 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001007 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001008 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001009 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001010 llvm::AttributeSet::get(CGM.getLLVMContext(),
1011 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001012 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001013}
1014
1015namespace {
1016 struct CallGuardAbort : EHScopeStack::Cleanup {
1017 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001018 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001019
John McCallad346f42011-07-12 20:27:29 +00001020 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5cd91b52010-09-08 01:44:27 +00001021 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
1022 ->setDoesNotThrow();
1023 }
1024 };
1025}
1026
1027/// The ARM code here follows the Itanium code closely enough that we
1028/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001029void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1030 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001031 llvm::GlobalVariable *var,
1032 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001033 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001034
1035 // We only need to use thread-safe statics for local variables;
1036 // global initialization is always single-threaded.
John McCall0502a222011-06-17 07:33:57 +00001037 bool threadsafe =
David Blaikie4e4d0842012-03-11 07:00:24 +00001038 (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
Anders Carlsson173d5122011-04-27 04:37:08 +00001039
Anders Carlsson173d5122011-04-27 04:37:08 +00001040 // If we have a global variable with internal linkage and thread-safe statics
1041 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001042 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1043
1044 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001045 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001046 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001047 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001048 // Guard variables are 64 bits in the generic ABI and size width on ARM
1049 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1050 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001051 }
John McCall355bba72012-03-30 21:00:39 +00001052 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001053
John McCall355bba72012-03-30 21:00:39 +00001054 // Create the guard variable if we don't already have it (as we
1055 // might if we're double-emitting this function body).
1056 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1057 if (!guard) {
1058 // Mangle the name for the guard.
1059 SmallString<256> guardName;
1060 {
1061 llvm::raw_svector_ostream out(guardName);
1062 getMangleContext().mangleItaniumGuardVariable(&D, out);
1063 out.flush();
1064 }
John McCall112c9672010-11-02 21:04:24 +00001065
John McCall355bba72012-03-30 21:00:39 +00001066 // Create the guard variable with a zero-initializer.
1067 // Just absorb linkage and visibility from the guarded variable.
1068 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1069 false, var->getLinkage(),
1070 llvm::ConstantInt::get(guardTy, 0),
1071 guardName.str());
1072 guard->setVisibility(var->getVisibility());
1073
1074 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1075 }
John McCall49d26d22012-03-30 07:09:50 +00001076
John McCall5cd91b52010-09-08 01:44:27 +00001077 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001078 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001079
1080 // ARM C++ ABI 3.2.3.1:
1081 // To support the potential use of initialization guard variables
1082 // as semaphores that are the target of ARM SWP and LDREX/STREX
1083 // synchronizing instructions we define a static initialization
1084 // guard variable to be a 4-byte aligned, 4- byte word with the
1085 // following inline access protocol.
1086 // #define INITIALIZED 1
1087 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1088 // if (__cxa_guard_acquire(&obj_guard))
1089 // ...
1090 // }
John McCall0502a222011-06-17 07:33:57 +00001091 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001092 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001093 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1094 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001095 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001096
1097 // Itanium C++ ABI 3.3.2:
1098 // The following is pseudo-code showing how these functions can be used:
1099 // if (obj_guard.first_byte == 0) {
1100 // if ( __cxa_guard_acquire (&obj_guard) ) {
1101 // try {
1102 // ... initialize the object ...;
1103 // } catch (...) {
1104 // __cxa_guard_abort (&obj_guard);
1105 // throw;
1106 // }
1107 // ... queue object destructor with __cxa_atexit() ...;
1108 // __cxa_guard_release (&obj_guard);
1109 // }
1110 // }
1111 } else {
1112 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001113 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001114 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001115 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001116
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001117 // Itanium ABI:
1118 // An implementation supporting thread-safety on multiprocessor
1119 // systems must also guarantee that references to the initialized
1120 // object do not occur before the load of the initialization flag.
1121 //
1122 // In LLVM, we do this by marking the load Acquire.
1123 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001124 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001125
John McCall355bba72012-03-30 21:00:39 +00001126 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001127 }
1128
1129 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1130 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1131
1132 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001133 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001134
1135 CGF.EmitBlock(InitCheckBlock);
1136
1137 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001138 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001139 // Call __cxa_guard_acquire.
1140 llvm::Value *V
John McCall355bba72012-03-30 21:00:39 +00001141 = Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001142
1143 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1144
1145 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1146 InitBlock, EndBlock);
1147
1148 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001149 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001150
1151 CGF.EmitBlock(InitBlock);
1152 }
1153
1154 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001155 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001156
John McCall0502a222011-06-17 07:33:57 +00001157 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001158 // Pop the guard-abort cleanup if we pushed one.
1159 CGF.PopCleanupBlock();
1160
1161 // Call __cxa_guard_release. This cannot throw.
John McCall355bba72012-03-30 21:00:39 +00001162 Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001163 } else {
John McCall355bba72012-03-30 21:00:39 +00001164 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001165 }
1166
1167 CGF.EmitBlock(EndBlock);
1168}
John McCall20bb1752012-05-01 06:13:13 +00001169
1170/// Register a global destructor using __cxa_atexit.
1171static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1172 llvm::Constant *dtor,
1173 llvm::Constant *addr) {
1174 // We're assuming that the destructor function is something we can
1175 // reasonably call with the default CC. Go ahead and cast it to the
1176 // right prototype.
1177 llvm::Type *dtorTy =
1178 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1179
1180 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1181 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1182 llvm::FunctionType *atexitTy =
1183 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1184
1185 // Fetch the actual function.
1186 llvm::Constant *atexit =
1187 CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
1188 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1189 fn->setDoesNotThrow();
1190
1191 // Create a variable that binds the atexit to this shared object.
1192 llvm::Constant *handle =
1193 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1194
1195 llvm::Value *args[] = {
1196 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1197 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1198 handle
1199 };
1200 CGF.Builder.CreateCall(atexit, args)->setDoesNotThrow();
1201}
1202
1203/// Register a global destructor as best as we know how.
1204void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1205 llvm::Constant *dtor,
1206 llvm::Constant *addr) {
1207 // Use __cxa_atexit if available.
1208 if (CGM.getCodeGenOpts().CXAAtExit) {
1209 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
1210 }
1211
1212 // In Apple kexts, we want to add a global destructor entry.
1213 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001214 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001215 // Generate a global destructor entry.
1216 return CGM.AddCXXDtorEntry(dtor, addr);
1217 }
1218
1219 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1220}