blob: db9e35db4e51497439fff7bef7bf1adc7dfbe318 [file] [log] [blame]
Charles Davis4e786dd2010-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 Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-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 McCall86353412010-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 Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall7a9aac22010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000031
32using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000034
35namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000037 /// VTables - All the vtables which have been defined.
38 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
39
John McCall475999d2010-08-22 00:05:51 +000040protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000041 bool UseARMMethodPtrABI;
42 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000043
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000044 ItaniumMangleContext &getMangleContext() {
45 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
46 }
47
Charles Davis4e786dd2010-05-25 19:52:27 +000048public:
Mark Seabornedf0d382013-07-24 16:25:13 +000049 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
50 bool UseARMMethodPtrABI = false,
51 bool UseARMGuardVarABI = false) :
52 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
53 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000054
Craig Topper4f12f102014-03-12 06:41:41 +000055 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const override {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000056 // Structures with either a non-trivial destructor or a non-trivial
57 // copy constructor are always indirect.
58 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
59 }
60
Craig Topper4f12f102014-03-12 06:41:41 +000061 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062 // Structures with either a non-trivial destructor or a non-trivial
63 // copy constructor are always indirect.
64 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
65 return RAA_Indirect;
66 return RAA_Default;
67 }
68
Craig Topper4f12f102014-03-12 06:41:41 +000069 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000070
Craig Topper4f12f102014-03-12 06:41:41 +000071 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000072
Craig Topper4f12f102014-03-12 06:41:41 +000073 llvm::Value *
74 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
75 const Expr *E,
76 llvm::Value *&This,
77 llvm::Value *MemFnPtr,
78 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000079
Craig Topper4f12f102014-03-12 06:41:41 +000080 llvm::Value *
81 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
82 llvm::Value *Base,
83 llvm::Value *MemPtr,
84 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000085
John McCall7a9aac22010-08-23 01:21:21 +000086 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
87 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000088 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000089 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000090 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000091
Craig Topper4f12f102014-03-12 06:41:41 +000092 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000093
Craig Topper4f12f102014-03-12 06:41:41 +000094 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000095 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000096 CharUnits offset) override;
97 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +000098 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
99 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000100
John McCall7a9aac22010-08-23 01:21:21 +0000101 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000102 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000103 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000104 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000105
John McCall7a9aac22010-08-23 01:21:21 +0000106 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000107 llvm::Value *Addr,
108 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000109
Craig Topper4f12f102014-03-12 06:41:41 +0000110 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
111 QualType type) override;
John McCall82fb8922012-09-25 10:10:39 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Value *
114 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
115 const CXXRecordDecl *ClassDecl,
116 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000117
John McCall5d865c322010-08-31 07:33:07 +0000118 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
Craig Topper4f12f102014-03-12 06:41:41 +0000119 CXXCtorType T, CanQualType &ResTy,
120 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000121
Craig Topper4f12f102014-03-12 06:41:41 +0000122 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000123
John McCall5d865c322010-08-31 07:33:07 +0000124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000125 CXXDtorType T, CanQualType &ResTy,
126 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000127
Reid Klecknere7de47e2013-07-22 13:51:44 +0000128 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000129 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000130 // Itanium does not emit any destructor variant as an inline thunk.
131 // Delegating may occur as an optimization, but all variants are either
132 // emitted with external linkage or as linkonce if they are inline and used.
133 return false;
134 }
135
Craig Topper4f12f102014-03-12 06:41:41 +0000136 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000137
Reid Kleckner89077a12013-12-17 19:46:40 +0000138 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000140
Craig Topper4f12f102014-03-12 06:41:41 +0000141 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000142
Reid Kleckner89077a12013-12-17 19:46:40 +0000143 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
144 const CXXConstructorDecl *D,
145 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000146 bool Delegating,
147 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000148
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000149 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
150 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000151 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000152
Craig Topper4f12f102014-03-12 06:41:41 +0000153 void emitVTableDefinitions(CodeGenVTables &CGVT,
154 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000155
156 llvm::Value *getVTableAddressPointInStructor(
157 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
158 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000159 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000160
161 llvm::Constant *
162 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000163 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000164
165 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000166 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000167
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000168 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000169 llvm::Value *This,
170 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000172 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
173 const CXXDestructorDecl *Dtor,
174 CXXDtorType DtorType, SourceLocation CallLoc,
Craig Topper4f12f102014-03-12 06:41:41 +0000175 llvm::Value *This) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000176
Craig Topper4f12f102014-03-12 06:41:41 +0000177 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000178
Craig Topper4f12f102014-03-12 06:41:41 +0000179 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000180 // Allow inlining of thunks by emitting them with available_externally
181 // linkage together with vtables when needed.
182 if (ForVTable)
183 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
184 }
185
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000186 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000188
189 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000190 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000191
Craig Topper4f12f102014-03-12 06:41:41 +0000192 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
193 StringRef GetDeletedVirtualCallName() override
194 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000195
Craig Topper4f12f102014-03-12 06:41:41 +0000196 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000197 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
198 llvm::Value *NewPtr,
199 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000200 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000201 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000202 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
203 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000204 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000205
John McCallcdf7ef52010-11-06 09:44:32 +0000206 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000207 llvm::GlobalVariable *DeclPtr,
208 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000209 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000211
212 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
213 llvm::GlobalVariable *Var);
214 void EmitThreadLocalInitFuncs(
215 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000216 llvm::Function *InitFunc) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000217 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000218 const DeclRefExpr *DRE) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000219
Craig Topper4f12f102014-03-12 06:41:41 +0000220 bool NeedsVTTParameter(GlobalDecl GD) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000221};
John McCall86353412010-08-21 22:46:04 +0000222
223class ARMCXXABI : public ItaniumCXXABI {
224public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000225 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
226 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
227 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000228
Craig Topper4f12f102014-03-12 06:41:41 +0000229 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000230 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
231 isa<CXXDestructorDecl>(GD.getDecl()) &&
232 GD.getDtorType() != Dtor_Deleting));
233 }
John McCall5d865c322010-08-31 07:33:07 +0000234
Craig Topper4f12f102014-03-12 06:41:41 +0000235 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
236 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000239 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
240 llvm::Value *NewPtr,
241 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000242 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000243 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000244 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000245 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000246};
Charles Davis4e786dd2010-05-25 19:52:27 +0000247}
248
Charles Davis53c59df2010-08-16 03:33:14 +0000249CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000250 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000251 // For IR-generation purposes, there's no significant difference
252 // between the ARM and iOS ABIs.
253 case TargetCXXABI::GenericARM:
254 case TargetCXXABI::iOS:
255 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000256
Tim Northover9bb857a2013-01-31 12:13:10 +0000257 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
258 // include the other 32-bit ARM oddities: constructor/destructor return values
259 // and array cookies.
260 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000261 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
262 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000263
John McCall57625922013-01-25 23:36:14 +0000264 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000265 if (CGM.getContext().getTargetInfo().getTriple().getArch()
266 == llvm::Triple::le32) {
267 // For PNaCl, use ARM-style method pointers so that PNaCl code
268 // does not assume anything about the alignment of function
269 // pointers.
270 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
271 /* UseARMGuardVarABI = */ false);
272 }
John McCall57625922013-01-25 23:36:14 +0000273 return new ItaniumCXXABI(CGM);
274
275 case TargetCXXABI::Microsoft:
276 llvm_unreachable("Microsoft ABI is not Itanium-based");
277 }
278 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000279}
280
Chris Lattnera5f58b02011-07-09 17:41:47 +0000281llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000282ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
283 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000284 return CGM.PtrDiffTy;
285 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000286}
287
John McCalld9c6c0b2010-08-22 00:59:17 +0000288/// In the Itanium and ARM ABIs, method pointers have the form:
289/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
290///
291/// In the Itanium ABI:
292/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
293/// - the this-adjustment is (memptr.adj)
294/// - the virtual offset is (memptr.ptr - 1)
295///
296/// In the ARM ABI:
297/// - method pointers are virtual if (memptr.adj & 1) is nonzero
298/// - the this-adjustment is (memptr.adj >> 1)
299/// - the virtual offset is (memptr.ptr)
300/// ARM uses 'adj' for the virtual flag because Thumb functions
301/// may be only single-byte aligned.
302///
303/// If the member is virtual, the adjusted 'this' pointer points
304/// to a vtable pointer from which the virtual offset is applied.
305///
306/// If the member is non-virtual, memptr.ptr is the address of
307/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000308llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
309 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
310 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000311 CGBuilderTy &Builder = CGF.Builder;
312
313 const FunctionProtoType *FPT =
314 MPT->getPointeeType()->getAs<FunctionProtoType>();
315 const CXXRecordDecl *RD =
316 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
317
Chris Lattner2192fe52011-07-18 04:24:23 +0000318 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000319 CGM.getTypes().GetFunctionType(
320 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000321
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000322 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000323
John McCalld9c6c0b2010-08-22 00:59:17 +0000324 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
325 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
326 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
327
John McCalla1dee5302010-08-22 10:59:02 +0000328 // Extract memptr.adj, which is in the second field.
329 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000330
331 // Compute the true adjustment.
332 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000333 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000334 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000335
336 // Apply the adjustment and cast back to the original struct type
337 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000338 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
339 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
340 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000341
342 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000343 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000344
345 // If the LSB in the function pointer is 1, the function pointer points to
346 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000347 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000348 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000349 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
350 else
351 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
352 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000353 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
354
355 // In the virtual path, the adjustment left 'This' pointing to the
356 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000357 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000358 CGF.EmitBlock(FnVirtual);
359
360 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000361 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall475999d2010-08-22 00:05:51 +0000362 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000363 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall475999d2010-08-22 00:05:51 +0000364
365 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000366 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000367 if (!UseARMMethodPtrABI)
368 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000369 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000370
371 // Load the virtual function to call.
372 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000373 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000374 CGF.EmitBranch(FnEnd);
375
376 // In the non-virtual path, the function pointer is actually a
377 // function pointer.
378 CGF.EmitBlock(FnNonVirtual);
379 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000380 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000381
382 // We're done.
383 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000384 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000385 Callee->addIncoming(VirtualFn, FnVirtual);
386 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
387 return Callee;
388}
John McCalla8bbb822010-08-22 03:04:22 +0000389
John McCallc134eb52010-08-31 21:07:20 +0000390/// Compute an l-value by applying the given pointer-to-member to a
391/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000392llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
393 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
394 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000395 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000396
397 CGBuilderTy &Builder = CGF.Builder;
398
Micah Villmowea2fea22012-10-25 15:39:14 +0000399 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000400
401 // Cast to char*.
402 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
403
404 // Apply the offset, which we assume is non-null.
405 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
406
407 // Cast the address to the appropriate pointer type, adopting the
408 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000409 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000410 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000411 return Builder.CreateBitCast(Addr, PType);
412}
413
John McCallc62bb392012-02-15 01:22:51 +0000414/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
415/// conversion.
416///
417/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000418///
419/// Obligatory offset/adjustment diagram:
420/// <-- offset --> <-- adjustment -->
421/// |--------------------------|----------------------|--------------------|
422/// ^Derived address point ^Base address point ^Member address point
423///
424/// So when converting a base member pointer to a derived member pointer,
425/// we add the offset to the adjustment because the address point has
426/// decreased; and conversely, when converting a derived MP to a base MP
427/// we subtract the offset from the adjustment because the address point
428/// has increased.
429///
430/// The standard forbids (at compile time) conversion to and from
431/// virtual bases, which is why we don't have to consider them here.
432///
433/// The standard forbids (at run time) casting a derived MP to a base
434/// MP when the derived MP does not point to a member of the base.
435/// This is why -1 is a reasonable choice for null data member
436/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000437llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000438ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
439 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000440 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000441 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000442 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
443 E->getCastKind() == CK_ReinterpretMemberPointer);
444
445 // Under Itanium, reinterprets don't require any additional processing.
446 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
447
448 // Use constant emission if we can.
449 if (isa<llvm::Constant>(src))
450 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
451
452 llvm::Constant *adj = getMemberPointerAdjustment(E);
453 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000454
455 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000456 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000457
John McCallc62bb392012-02-15 01:22:51 +0000458 const MemberPointerType *destTy =
459 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000460
John McCall7a9aac22010-08-23 01:21:21 +0000461 // For member data pointers, this is just a matter of adding the
462 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000463 if (destTy->isMemberDataPointer()) {
464 llvm::Value *dst;
465 if (isDerivedToBase)
466 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000467 else
John McCallc62bb392012-02-15 01:22:51 +0000468 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000469
470 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000471 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
472 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
473 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000474 }
475
John McCalla1dee5302010-08-22 10:59:02 +0000476 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000477 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000478 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
479 offset <<= 1;
480 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000481 }
482
John McCallc62bb392012-02-15 01:22:51 +0000483 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
484 llvm::Value *dstAdj;
485 if (isDerivedToBase)
486 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000487 else
John McCallc62bb392012-02-15 01:22:51 +0000488 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000489
John McCallc62bb392012-02-15 01:22:51 +0000490 return Builder.CreateInsertValue(src, dstAdj, 1);
491}
492
493llvm::Constant *
494ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
495 llvm::Constant *src) {
496 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
497 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
498 E->getCastKind() == CK_ReinterpretMemberPointer);
499
500 // Under Itanium, reinterprets don't require any additional processing.
501 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
502
503 // If the adjustment is trivial, we don't need to do anything.
504 llvm::Constant *adj = getMemberPointerAdjustment(E);
505 if (!adj) return src;
506
507 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
508
509 const MemberPointerType *destTy =
510 E->getType()->castAs<MemberPointerType>();
511
512 // For member data pointers, this is just a matter of adding the
513 // offset if the source is non-null.
514 if (destTy->isMemberDataPointer()) {
515 // null maps to null.
516 if (src->isAllOnesValue()) return src;
517
518 if (isDerivedToBase)
519 return llvm::ConstantExpr::getNSWSub(src, adj);
520 else
521 return llvm::ConstantExpr::getNSWAdd(src, adj);
522 }
523
524 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000525 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000526 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
527 offset <<= 1;
528 adj = llvm::ConstantInt::get(adj->getType(), offset);
529 }
530
531 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
532 llvm::Constant *dstAdj;
533 if (isDerivedToBase)
534 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
535 else
536 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
537
538 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000539}
John McCall84fa5102010-08-22 04:16:24 +0000540
541llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000542ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000543 // Itanium C++ ABI 2.3:
544 // A NULL pointer is represented as -1.
545 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000546 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000547
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000548 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000549 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000550 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000551}
552
John McCallf3a88602011-02-03 08:15:49 +0000553llvm::Constant *
554ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
555 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000556 // Itanium C++ ABI 2.3:
557 // A pointer to data member is an offset from the base address of
558 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000559 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000560}
561
John McCall2979fe02011-04-12 00:42:48 +0000562llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000563 return BuildMemberPointer(MD, CharUnits::Zero());
564}
565
566llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
567 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000568 assert(MD->isInstance() && "Member function must not be static!");
569 MD = MD->getCanonicalDecl();
570
571 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000572
573 // Get the function pointer (or index if this is a virtual function).
574 llvm::Constant *MemPtr[2];
575 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000576 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000577
Ken Dyckdf016282011-04-09 01:30:02 +0000578 const ASTContext &Context = getContext();
579 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000580 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000581 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000582
Mark Seabornedf0d382013-07-24 16:25:13 +0000583 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000584 // ARM C++ ABI 3.2.1:
585 // This ABI specifies that adj contains twice the this
586 // adjustment, plus 1 if the member function is virtual. The
587 // least significant bit of adj then makes exactly the same
588 // discrimination as the least significant bit of ptr does for
589 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000590 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
591 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000592 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000593 } else {
594 // Itanium C++ ABI 2.3:
595 // For a virtual function, [the pointer field] is 1 plus the
596 // virtual table offset (in bytes) of the function,
597 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000598 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
599 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000600 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000601 }
602 } else {
John McCall2979fe02011-04-12 00:42:48 +0000603 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000604 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000605 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000606 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000607 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000608 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000609 } else {
John McCall2979fe02011-04-12 00:42:48 +0000610 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
611 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000612 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000613 }
John McCall2979fe02011-04-12 00:42:48 +0000614 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000615
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000616 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000617 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
618 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000619 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000620 }
John McCall1c456c82010-08-22 06:43:33 +0000621
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000622 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000623}
624
Richard Smithdafff942012-01-14 04:30:29 +0000625llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
626 QualType MPType) {
627 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
628 const ValueDecl *MPD = MP.getMemberPointerDecl();
629 if (!MPD)
630 return EmitNullMemberPointer(MPT);
631
Reid Kleckner452abac2013-05-09 21:01:17 +0000632 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000633
634 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
635 return BuildMemberPointer(MD, ThisAdjustment);
636
637 CharUnits FieldOffset =
638 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
639 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
640}
641
John McCall131d97d2010-08-22 08:30:07 +0000642/// The comparison algorithm is pretty easy: the member pointers are
643/// the same if they're either bitwise identical *or* both null.
644///
645/// ARM is different here only because null-ness is more complicated.
646llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000647ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
648 llvm::Value *L,
649 llvm::Value *R,
650 const MemberPointerType *MPT,
651 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000652 CGBuilderTy &Builder = CGF.Builder;
653
John McCall131d97d2010-08-22 08:30:07 +0000654 llvm::ICmpInst::Predicate Eq;
655 llvm::Instruction::BinaryOps And, Or;
656 if (Inequality) {
657 Eq = llvm::ICmpInst::ICMP_NE;
658 And = llvm::Instruction::Or;
659 Or = llvm::Instruction::And;
660 } else {
661 Eq = llvm::ICmpInst::ICMP_EQ;
662 And = llvm::Instruction::And;
663 Or = llvm::Instruction::Or;
664 }
665
John McCall7a9aac22010-08-23 01:21:21 +0000666 // Member data pointers are easy because there's a unique null
667 // value, so it just comes down to bitwise equality.
668 if (MPT->isMemberDataPointer())
669 return Builder.CreateICmp(Eq, L, R);
670
671 // For member function pointers, the tautologies are more complex.
672 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000673 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000674 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000675 // (L == R) <==> (L.ptr == R.ptr &&
676 // (L.adj == R.adj ||
677 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000678 // The inequality tautologies have exactly the same structure, except
679 // applying De Morgan's laws.
680
681 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
682 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
683
John McCall131d97d2010-08-22 08:30:07 +0000684 // This condition tests whether L.ptr == R.ptr. This must always be
685 // true for equality to hold.
686 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
687
688 // This condition, together with the assumption that L.ptr == R.ptr,
689 // tests whether the pointers are both null. ARM imposes an extra
690 // condition.
691 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
692 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
693
694 // This condition tests whether L.adj == R.adj. If this isn't
695 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000696 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
697 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000698 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
699
700 // Null member function pointers on ARM clear the low bit of Adj,
701 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000702 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000703 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
704
705 // Compute (l.adj | r.adj) & 1 and test it against zero.
706 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
707 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
708 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
709 "cmp.or.adj");
710 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
711 }
712
713 // Tie together all our conditions.
714 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
715 Result = Builder.CreateBinOp(And, PtrEq, Result,
716 Inequality ? "memptr.ne" : "memptr.eq");
717 return Result;
718}
719
720llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000721ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
722 llvm::Value *MemPtr,
723 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000724 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000725
726 /// For member data pointers, this is just a check against -1.
727 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000728 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000729 llvm::Value *NegativeOne =
730 llvm::Constant::getAllOnesValue(MemPtr->getType());
731 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
732 }
John McCall131d97d2010-08-22 08:30:07 +0000733
Daniel Dunbar914bc412011-04-19 23:10:47 +0000734 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000735 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000736
737 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
738 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
739
Daniel Dunbar914bc412011-04-19 23:10:47 +0000740 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
741 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000742 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000743 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000744 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000745 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000746 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
747 "memptr.isvirtual");
748 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000749 }
750
751 return Result;
752}
John McCall1c456c82010-08-22 06:43:33 +0000753
John McCall614dbdc2010-08-22 21:01:12 +0000754/// The Itanium ABI requires non-zero initialization only for data
755/// member pointers, for which '0' is a valid offset.
756bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
757 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000758}
John McCall5d865c322010-08-31 07:33:07 +0000759
John McCall82fb8922012-09-25 10:10:39 +0000760/// The Itanium ABI always places an offset to the complete object
761/// at entry -2 in the vtable.
762llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
763 llvm::Value *ptr,
764 QualType type) {
765 // Grab the vtable pointer as an intptr_t*.
766 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
767
768 // Track back to entry -2 and pull out the offset there.
769 llvm::Value *offsetPtr =
770 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
771 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
772 offset->setAlignment(CGF.PointerAlignInBytes);
773
774 // Apply the offset.
775 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
776 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
777}
778
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000779llvm::Value *
780ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
781 llvm::Value *This,
782 const CXXRecordDecl *ClassDecl,
783 const CXXRecordDecl *BaseClassDecl) {
784 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
785 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000786 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
787 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000788
789 llvm::Value *VBaseOffsetPtr =
790 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
791 "vbase.offset.ptr");
792 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
793 CGM.PtrDiffTy->getPointerTo());
794
795 llvm::Value *VBaseOffset =
796 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
797
798 return VBaseOffset;
799}
800
John McCall5d865c322010-08-31 07:33:07 +0000801/// The generic ABI passes 'this', plus a VTT if it's initializing a
802/// base subobject.
Reid Kleckner89077a12013-12-17 19:46:40 +0000803void
804ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
805 CXXCtorType Type, CanQualType &ResTy,
806 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000807 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000808
Reid Kleckner89077a12013-12-17 19:46:40 +0000809 // All parameters are already in place except VTT, which goes after 'this'.
810 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +0000811
812 // Check if we need to add a VTT parameter (which has type void **).
813 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
Reid Kleckner89077a12013-12-17 19:46:40 +0000814 ArgTys.insert(ArgTys.begin() + 1,
815 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +0000816}
817
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000818void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
819 // Just make sure we're in sync with TargetCXXABI.
820 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
821
Rafael Espindolac3cde362013-12-09 14:51:17 +0000822 // The constructor used for constructing this as a base class;
823 // ignores virtual bases.
824 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
825
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000826 // The constructor used for constructing this as a complete class;
827 // constucts the virtual bases, then calls the base constructor.
828 if (!D->getParent()->isAbstract()) {
829 // We don't need to emit the complete ctor if the class is abstract.
830 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
831 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000832}
833
John McCall5d865c322010-08-31 07:33:07 +0000834/// The generic ABI passes 'this', plus a VTT if it's destroying a
835/// base subobject.
836void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
837 CXXDtorType Type,
838 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000839 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000840 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000841
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000842 // 'this' parameter is already there, as well as 'this' return if
843 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000844
845 // Check if we need to add a VTT parameter (which has type void **).
846 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
847 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
848}
849
Reid Klecknere7de47e2013-07-22 13:51:44 +0000850void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +0000851 // The destructor used for destructing this as a base class; ignores
852 // virtual bases.
853 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000854
855 // The destructor used for destructing this as a most-derived class;
856 // call the base destructor and then destructs any virtual bases.
857 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
858
Rafael Espindolac3cde362013-12-09 14:51:17 +0000859 // The destructor in a virtual table is always a 'deleting'
860 // destructor, which calls the complete destructor and then uses the
861 // appropriate operator delete.
862 if (D->isVirtual())
863 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000864}
865
Reid Kleckner89077a12013-12-17 19:46:40 +0000866void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
867 QualType &ResTy,
868 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +0000869 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000870 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +0000871
872 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000873 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000874 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000875
876 // FIXME: avoid the fake decl
877 QualType T = Context.getPointerType(Context.VoidPtrTy);
878 ImplicitParamDecl *VTTDecl
879 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
880 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +0000881 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +0000882 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +0000883 }
884}
885
John McCall5d865c322010-08-31 07:33:07 +0000886void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
887 /// Initialize the 'this' slot.
888 EmitThisParam(CGF);
889
890 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +0000891 if (getStructorImplicitParamDecl(CGF)) {
892 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
893 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +0000894 }
John McCall5d865c322010-08-31 07:33:07 +0000895
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000896 /// If this is a function that the ABI specifies returns 'this', initialize
897 /// the return slot to 'this' at the start of the function.
898 ///
899 /// Unlike the setting of return types, this is done within the ABI
900 /// implementation instead of by clients of CGCXXABI because:
901 /// 1) getThisValue is currently protected
902 /// 2) in theory, an ABI could implement 'this' returns some other way;
903 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000904 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000905 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000906}
907
Reid Kleckner89077a12013-12-17 19:46:40 +0000908unsigned ItaniumCXXABI::addImplicitConstructorArgs(
909 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
910 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
911 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
912 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000913
Reid Kleckner89077a12013-12-17 19:46:40 +0000914 // Insert the implicit 'vtt' argument as the second argument.
915 llvm::Value *VTT =
916 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
917 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
918 Args.insert(Args.begin() + 1,
919 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
920 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000921}
922
923void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
924 const CXXDestructorDecl *DD,
925 CXXDtorType Type, bool ForVirtualBase,
926 bool Delegating, llvm::Value *This) {
927 GlobalDecl GD(DD, Type);
928 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
929 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
930
931 llvm::Value *Callee = 0;
932 if (getContext().getLangOpts().AppleKext)
933 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
934
935 if (!Callee)
936 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
937
938 if (DD->isVirtual())
939 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
940
941 // FIXME: Provide a source location here.
942 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
943 VTT, VTTTy, 0, 0);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000944}
945
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000946void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
947 const CXXRecordDecl *RD) {
948 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
949 if (VTable->hasInitializer())
950 return;
951
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000952 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000953 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
954 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
955
956 // Create and set the initializer.
957 llvm::Constant *Init = CGVT.CreateVTableInitializer(
958 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
959 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
960 VTable->setInitializer(Init);
961
962 // Set the correct linkage.
963 VTable->setLinkage(Linkage);
964
965 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +0000966 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000967
968 // If this is the magic class __cxxabiv1::__fundamental_type_info,
969 // we will emit the typeinfo for the fundamental types. This is the
970 // same behaviour as GCC.
971 const DeclContext *DC = RD->getDeclContext();
972 if (RD->getIdentifier() &&
973 RD->getIdentifier()->isStr("__fundamental_type_info") &&
974 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
975 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
976 DC->getParent()->isTranslationUnit())
977 CGM.EmitFundamentalRTTIDescriptors();
978}
979
980llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
981 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
982 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
983 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
984 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
985
986 llvm::Value *VTableAddressPoint;
987 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
988 // Get the secondary vpointer index.
989 uint64_t VirtualPointerIndex =
990 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
991
992 /// Load the VTT.
993 llvm::Value *VTT = CGF.LoadCXXVTT();
994 if (VirtualPointerIndex)
995 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
996
997 // And load the address point from the VTT.
998 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
999 } else {
1000 llvm::Constant *VTable =
1001 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001002 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1003 .getVTableLayout(VTableClass)
1004 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001005 VTableAddressPoint =
1006 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1007 }
1008
1009 return VTableAddressPoint;
1010}
1011
1012llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1013 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1014 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1015
1016 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001017 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1018 .getVTableLayout(VTableClass)
1019 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001020 llvm::Value *Indices[] = {
1021 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1022 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1023 };
1024
1025 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1026}
1027
1028llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1029 CharUnits VPtrOffset) {
1030 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1031
1032 llvm::GlobalVariable *&VTable = VTables[RD];
1033 if (VTable)
1034 return VTable;
1035
1036 // Queue up this v-table for possible deferred emission.
1037 CGM.addDeferredVTable(RD);
1038
1039 SmallString<256> OutName;
1040 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001041 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001042 Out.flush();
1043 StringRef Name = OutName.str();
1044
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001045 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001046 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1047 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1048
1049 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1050 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1051 VTable->setUnnamedAddr(true);
1052 return VTable;
1053}
1054
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001055llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1056 GlobalDecl GD,
1057 llvm::Value *This,
1058 llvm::Type *Ty) {
1059 GD = GD.getCanonicalDecl();
1060 Ty = Ty->getPointerTo()->getPointerTo();
1061 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1062
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001063 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001064 llvm::Value *VFuncPtr =
1065 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1066 return CGF.Builder.CreateLoad(VFuncPtr);
1067}
1068
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001069void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1070 const CXXDestructorDecl *Dtor,
1071 CXXDtorType DtorType,
1072 SourceLocation CallLoc,
1073 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001074 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1075
1076 const CGFunctionInfo *FInfo
1077 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1078 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001079 llvm::Value *Callee =
1080 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001081
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001082 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1083 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001084}
1085
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001086void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001087 CodeGenVTables &VTables = CGM.getVTables();
1088 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001089 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001090}
1091
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001092static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1093 llvm::Value *Ptr,
1094 int64_t NonVirtualAdjustment,
1095 int64_t VirtualAdjustment,
1096 bool IsReturnAdjustment) {
1097 if (!NonVirtualAdjustment && !VirtualAdjustment)
1098 return Ptr;
1099
1100 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1101 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1102
1103 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1104 // Perform the non-virtual adjustment for a base-to-derived cast.
1105 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1106 }
1107
1108 if (VirtualAdjustment) {
1109 llvm::Type *PtrDiffTy =
1110 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1111
1112 // Perform the virtual adjustment.
1113 llvm::Value *VTablePtrPtr =
1114 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1115
1116 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1117
1118 llvm::Value *OffsetPtr =
1119 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1120
1121 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1122
1123 // Load the adjustment offset from the vtable.
1124 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1125
1126 // Adjust our pointer.
1127 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1128 }
1129
1130 if (NonVirtualAdjustment && IsReturnAdjustment) {
1131 // Perform the non-virtual adjustment for a derived-to-base cast.
1132 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1133 }
1134
1135 // Cast back to the original type.
1136 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1137}
1138
1139llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1140 llvm::Value *This,
1141 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001142 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1143 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001144 /*IsReturnAdjustment=*/false);
1145}
1146
1147llvm::Value *
1148ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1149 const ReturnAdjustment &RA) {
1150 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1151 RA.Virtual.Itanium.VBaseOffsetOffset,
1152 /*IsReturnAdjustment=*/true);
1153}
1154
John McCall5d865c322010-08-31 07:33:07 +00001155void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1156 RValue RV, QualType ResultType) {
1157 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1158 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1159
1160 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001161 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001162 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1163 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1164 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1165}
John McCall8ed55a52010-09-02 09:58:18 +00001166
1167/************************** Array allocation cookies **************************/
1168
John McCallb91cd662012-05-01 05:23:51 +00001169CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1170 // The array cookie is a size_t; pad that up to the element alignment.
1171 // The cookie is actually right-justified in that space.
1172 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1173 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001174}
1175
1176llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1177 llvm::Value *NewPtr,
1178 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001179 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001180 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001181 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001182
Micah Villmowea2fea22012-10-25 15:39:14 +00001183 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001184
John McCall9bca9232010-09-02 10:25:57 +00001185 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001186 QualType SizeTy = Ctx.getSizeType();
1187 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1188
1189 // The size of the cookie.
1190 CharUnits CookieSize =
1191 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001192 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001193
1194 // Compute an offset to the cookie.
1195 llvm::Value *CookiePtr = NewPtr;
1196 CharUnits CookieOffset = CookieSize - SizeSize;
1197 if (!CookieOffset.isZero())
1198 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1199 CookieOffset.getQuantity());
1200
1201 // Write the number of elements into the appropriate slot.
1202 llvm::Value *NumElementsPtr
1203 = CGF.Builder.CreateBitCast(CookiePtr,
1204 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1205 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1206
1207 // Finally, compute a pointer to the actual data buffer by skipping
1208 // over the cookie completely.
1209 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1210 CookieSize.getQuantity());
1211}
1212
John McCallb91cd662012-05-01 05:23:51 +00001213llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1214 llvm::Value *allocPtr,
1215 CharUnits cookieSize) {
1216 // The element size is right-justified in the cookie.
1217 llvm::Value *numElementsPtr = allocPtr;
1218 CharUnits numElementsOffset =
1219 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1220 if (!numElementsOffset.isZero())
1221 numElementsPtr =
1222 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1223 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001224
Micah Villmowea2fea22012-10-25 15:39:14 +00001225 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001226 numElementsPtr =
1227 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1228 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001229}
1230
John McCallb91cd662012-05-01 05:23:51 +00001231CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001232 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001233 // struct array_cookie {
1234 // std::size_t element_size; // element_size != 0
1235 // std::size_t element_count;
1236 // };
John McCallc19c7062013-01-25 23:36:19 +00001237 // But the base ABI doesn't give anything an alignment greater than
1238 // 8, so we can dismiss this as typical ABI-author blindness to
1239 // actual language complexity and round up to the element alignment.
1240 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1241 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001242}
1243
1244llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001245 llvm::Value *newPtr,
1246 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001247 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001248 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001249 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001250
John McCallc19c7062013-01-25 23:36:19 +00001251 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1252 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001253
1254 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001255 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001256
1257 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001258 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1259 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1260 getContext().getTypeSizeInChars(elementType).getQuantity());
1261 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001262
1263 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001264 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1265 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001266
1267 // Finally, compute a pointer to the actual data buffer by skipping
1268 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001269 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1270 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1271 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001272}
1273
John McCallb91cd662012-05-01 05:23:51 +00001274llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1275 llvm::Value *allocPtr,
1276 CharUnits cookieSize) {
1277 // The number of elements is at offset sizeof(size_t) relative to
1278 // the allocated pointer.
1279 llvm::Value *numElementsPtr
1280 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001281
Micah Villmowea2fea22012-10-25 15:39:14 +00001282 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001283 numElementsPtr =
1284 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1285 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001286}
1287
John McCall68ff0372010-09-08 01:44:27 +00001288/*********************** Static local initialization **************************/
1289
1290static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001291 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001292 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001293 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001294 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001295 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001296 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001297 llvm::AttributeSet::get(CGM.getLLVMContext(),
1298 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001299 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001300}
1301
1302static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001303 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001304 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001305 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001306 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001307 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001308 llvm::AttributeSet::get(CGM.getLLVMContext(),
1309 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001310 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001311}
1312
1313static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001314 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001315 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001316 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001317 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001318 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001319 llvm::AttributeSet::get(CGM.getLLVMContext(),
1320 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001321 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001322}
1323
1324namespace {
1325 struct CallGuardAbort : EHScopeStack::Cleanup {
1326 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001327 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001328
Craig Topper4f12f102014-03-12 06:41:41 +00001329 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001330 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1331 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001332 }
1333 };
1334}
1335
1336/// The ARM code here follows the Itanium code closely enough that we
1337/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001338void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1339 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001340 llvm::GlobalVariable *var,
1341 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001342 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001343
Richard Smithdbf74ba2013-04-14 23:01:42 +00001344 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001345 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001346 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1347 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001348
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001349 // If we have a global variable with internal linkage and thread-safe statics
1350 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001351 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1352
1353 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001354 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001355 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001356 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001357 // Guard variables are 64 bits in the generic ABI and size width on ARM
1358 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001359 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001360 }
John McCallb88a5662012-03-30 21:00:39 +00001361 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001362
John McCallb88a5662012-03-30 21:00:39 +00001363 // Create the guard variable if we don't already have it (as we
1364 // might if we're double-emitting this function body).
1365 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1366 if (!guard) {
1367 // Mangle the name for the guard.
1368 SmallString<256> guardName;
1369 {
1370 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001371 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001372 out.flush();
1373 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001374
John McCallb88a5662012-03-30 21:00:39 +00001375 // Create the guard variable with a zero-initializer.
1376 // Just absorb linkage and visibility from the guarded variable.
1377 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1378 false, var->getLinkage(),
1379 llvm::ConstantInt::get(guardTy, 0),
1380 guardName.str());
1381 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001382 // If the variable is thread-local, so is its guard variable.
1383 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001384
1385 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1386 }
John McCall87590e62012-03-30 07:09:50 +00001387
John McCall68ff0372010-09-08 01:44:27 +00001388 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001389 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001390
1391 // ARM C++ ABI 3.2.3.1:
1392 // To support the potential use of initialization guard variables
1393 // as semaphores that are the target of ARM SWP and LDREX/STREX
1394 // synchronizing instructions we define a static initialization
1395 // guard variable to be a 4-byte aligned, 4- byte word with the
1396 // following inline access protocol.
1397 // #define INITIALIZED 1
1398 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1399 // if (__cxa_guard_acquire(&obj_guard))
1400 // ...
1401 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001402 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001403 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001404 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1405 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001406 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001407
1408 // Itanium C++ ABI 3.3.2:
1409 // The following is pseudo-code showing how these functions can be used:
1410 // if (obj_guard.first_byte == 0) {
1411 // if ( __cxa_guard_acquire (&obj_guard) ) {
1412 // try {
1413 // ... initialize the object ...;
1414 // } catch (...) {
1415 // __cxa_guard_abort (&obj_guard);
1416 // throw;
1417 // }
1418 // ... queue object destructor with __cxa_atexit() ...;
1419 // __cxa_guard_release (&obj_guard);
1420 // }
1421 // }
1422 } else {
1423 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001424 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001425 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001426 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001427
Eli Friedman84d28122011-09-13 22:21:56 +00001428 // Itanium ABI:
1429 // An implementation supporting thread-safety on multiprocessor
1430 // systems must also guarantee that references to the initialized
1431 // object do not occur before the load of the initialization flag.
1432 //
1433 // In LLVM, we do this by marking the load Acquire.
1434 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001435 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001436
John McCallb88a5662012-03-30 21:00:39 +00001437 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001438 }
1439
1440 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1441 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1442
1443 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001444 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001445
1446 CGF.EmitBlock(InitCheckBlock);
1447
1448 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001449 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001450 // Call __cxa_guard_acquire.
1451 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001452 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001453
1454 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1455
1456 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1457 InitBlock, EndBlock);
1458
1459 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001460 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001461
1462 CGF.EmitBlock(InitBlock);
1463 }
1464
1465 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001466 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001467
John McCall5aa52592011-06-17 07:33:57 +00001468 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001469 // Pop the guard-abort cleanup if we pushed one.
1470 CGF.PopCleanupBlock();
1471
1472 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001473 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001474 } else {
John McCallb88a5662012-03-30 21:00:39 +00001475 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001476 }
1477
1478 CGF.EmitBlock(EndBlock);
1479}
John McCallc84ed6a2012-05-01 06:13:13 +00001480
1481/// Register a global destructor using __cxa_atexit.
1482static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1483 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001484 llvm::Constant *addr,
1485 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001486 const char *Name = "__cxa_atexit";
1487 if (TLS) {
1488 const llvm::Triple &T = CGF.getTarget().getTriple();
1489 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1490 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001491
John McCallc84ed6a2012-05-01 06:13:13 +00001492 // We're assuming that the destructor function is something we can
1493 // reasonably call with the default CC. Go ahead and cast it to the
1494 // right prototype.
1495 llvm::Type *dtorTy =
1496 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1497
1498 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1499 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1500 llvm::FunctionType *atexitTy =
1501 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1502
1503 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001504 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001505 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1506 fn->setDoesNotThrow();
1507
1508 // Create a variable that binds the atexit to this shared object.
1509 llvm::Constant *handle =
1510 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1511
1512 llvm::Value *args[] = {
1513 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1514 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1515 handle
1516 };
John McCall882987f2013-02-28 19:01:20 +00001517 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001518}
1519
1520/// Register a global destructor as best as we know how.
1521void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001522 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001523 llvm::Constant *dtor,
1524 llvm::Constant *addr) {
1525 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001526 if (CGM.getCodeGenOpts().CXAAtExit)
1527 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1528
1529 if (D.getTLSKind())
1530 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001531
1532 // In Apple kexts, we want to add a global destructor entry.
1533 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001534 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001535 // Generate a global destructor entry.
1536 return CGM.AddCXXDtorEntry(dtor, addr);
1537 }
1538
David Blaikieebe87e12013-08-27 23:57:18 +00001539 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001540}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001541
1542/// Get the appropriate linkage for the wrapper function. This is essentially
1543/// the weak form of the variable's linkage; every translation unit which wneeds
1544/// the wrapper emits a copy, and we want the linker to merge them.
1545static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1546 llvm::GlobalValue::LinkageTypes VarLinkage) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001547 // For internal linkage variables, we don't need an external or weak wrapper.
1548 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1549 return VarLinkage;
1550 return llvm::GlobalValue::WeakODRLinkage;
1551}
1552
1553llvm::Function *
1554ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1555 llvm::GlobalVariable *Var) {
1556 // Mangle the name for the thread_local wrapper function.
1557 SmallString<256> WrapperName;
1558 {
1559 llvm::raw_svector_ostream Out(WrapperName);
1560 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1561 Out.flush();
1562 }
1563
1564 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1565 return cast<llvm::Function>(V);
1566
1567 llvm::Type *RetTy = Var->getType();
1568 if (VD->getType()->isReferenceType())
1569 RetTy = RetTy->getPointerElementType();
1570
1571 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1572 llvm::Function *Wrapper = llvm::Function::Create(
1573 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1574 &CGM.getModule());
1575 // Always resolve references to the wrapper at link time.
1576 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1577 return Wrapper;
1578}
1579
1580void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1581 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1582 llvm::Function *InitFunc) {
1583 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1584 const VarDecl *VD = Decls[I].first;
1585 llvm::GlobalVariable *Var = Decls[I].second;
1586
1587 // Mangle the name for the thread_local initialization function.
1588 SmallString<256> InitFnName;
1589 {
1590 llvm::raw_svector_ostream Out(InitFnName);
1591 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1592 Out.flush();
1593 }
1594
1595 // If we have a definition for the variable, emit the initialization
1596 // function as an alias to the global Init function (if any). Otherwise,
1597 // produce a declaration of the initialization function.
1598 llvm::GlobalValue *Init = 0;
1599 bool InitIsInitFunc = false;
1600 if (VD->hasDefinition()) {
1601 InitIsInitFunc = true;
1602 if (InitFunc)
1603 Init =
1604 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1605 InitFnName.str(), InitFunc, &CGM.getModule());
1606 } else {
1607 // Emit a weak global function referring to the initialization function.
1608 // This function will not exist if the TU defining the thread_local
1609 // variable in question does not need any dynamic initialization for
1610 // its thread_local variables.
1611 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1612 Init = llvm::Function::Create(
1613 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1614 &CGM.getModule());
1615 }
1616
1617 if (Init)
1618 Init->setVisibility(Var->getVisibility());
1619
1620 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1621 llvm::LLVMContext &Context = CGM.getModule().getContext();
1622 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1623 CGBuilderTy Builder(Entry);
1624 if (InitIsInitFunc) {
1625 if (Init)
1626 Builder.CreateCall(Init);
1627 } else {
1628 // Don't know whether we have an init function. Call it if it exists.
1629 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1630 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1631 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1632 Builder.CreateCondBr(Have, InitBB, ExitBB);
1633
1634 Builder.SetInsertPoint(InitBB);
1635 Builder.CreateCall(Init);
1636 Builder.CreateBr(ExitBB);
1637
1638 Builder.SetInsertPoint(ExitBB);
1639 }
1640
1641 // For a reference, the result of the wrapper function is a pointer to
1642 // the referenced object.
1643 llvm::Value *Val = Var;
1644 if (VD->getType()->isReferenceType()) {
1645 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1646 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1647 Val = LI;
1648 }
1649
1650 Builder.CreateRet(Val);
1651 }
1652}
1653
1654LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1655 const DeclRefExpr *DRE) {
1656 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1657 QualType T = VD->getType();
1658 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1659 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1660 llvm::Function *Wrapper =
1661 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1662
1663 Val = CGF.Builder.CreateCall(Wrapper);
1664
1665 LValue LV;
1666 if (VD->getType()->isReferenceType())
1667 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1668 else
1669 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1670 CGF.getContext().getDeclAlign(VD));
1671 // FIXME: need setObjCGCLValueClass?
1672 return LV;
1673}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001674
1675/// Return whether the given global decl needs a VTT parameter, which it does
1676/// if it's a base constructor or destructor with virtual bases.
1677bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1678 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1679
1680 // We don't have any virtual bases, just return early.
1681 if (!MD->getParent()->getNumVBases())
1682 return false;
1683
1684 // Check if we have a base constructor.
1685 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1686 return true;
1687
1688 // Check if we have a base destructor.
1689 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1690 return true;
1691
1692 return false;
1693}