blob: b08e9b7462c744a0818b553f5701c78bdcd3aa8b [file] [log] [blame]
Charles Davis3a811f12010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis3a811f12010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCallee79a4c2010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis3a811f12010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall0bab0cd2010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davis9ee494f2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall93d557b2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperba77cb92012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis3a811f12010-05-25 19:52:27 +000031
32using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000034
35namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall93d557b2010-08-22 00:05:51 +000037protected:
Mark Seaborn21fe4502013-07-24 16:25:13 +000038 bool UseARMMethodPtrABI;
39 bool UseARMGuardVarABI;
John McCall0bab0cd2010-08-23 01:21:21 +000040
Charles Davis3a811f12010-05-25 19:52:27 +000041public:
Mark Seaborn21fe4502013-07-24 16:25:13 +000042 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
43 bool UseARMMethodPtrABI = false,
44 bool UseARMGuardVarABI = false) :
45 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
46 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall93d557b2010-08-22 00:05:51 +000047
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000048 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
49 // Structures with either a non-trivial destructor or a non-trivial
50 // copy constructor are always indirect.
51 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
52 }
53
54 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
55 // Structures with either a non-trivial destructor or a non-trivial
56 // copy constructor are always indirect.
57 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
58 return RAA_Indirect;
59 return RAA_Default;
60 }
61
John McCallf16aa102010-08-22 21:01:12 +000062 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000063
Chris Lattner9cbe4f02011-07-09 17:41:47 +000064 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000065
John McCall93d557b2010-08-22 00:05:51 +000066 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
67 llvm::Value *&This,
68 llvm::Value *MemFnPtr,
69 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000070
John McCall6c2ab1d2010-08-31 21:07:20 +000071 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
72 llvm::Value *Base,
73 llvm::Value *MemPtr,
74 const MemberPointerType *MPT);
75
John McCall0bab0cd2010-08-23 01:21:21 +000076 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
77 const CastExpr *E,
78 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000079 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
80 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000081
John McCall0bab0cd2010-08-23 01:21:21 +000082 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000083
John McCall755d8492011-04-12 00:42:48 +000084 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000085 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
86 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000087 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
88 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
89 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000090
John McCall0bab0cd2010-08-23 01:21:21 +000091 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
92 llvm::Value *L,
93 llvm::Value *R,
94 const MemberPointerType *MPT,
95 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000096
John McCall0bab0cd2010-08-23 01:21:21 +000097 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
98 llvm::Value *Addr,
99 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +0000100
John McCallecd03b42012-09-25 10:10:39 +0000101 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
102 llvm::Value *ptr,
103 QualType type);
104
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000105 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
106 llvm::Value *This,
107 const CXXRecordDecl *ClassDecl,
108 const CXXRecordDecl *BaseClassDecl);
109
John McCall4c40d982010-08-31 07:33:07 +0000110 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
111 CXXCtorType T,
112 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000113 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000114
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000115 void EmitCXXConstructors(const CXXConstructorDecl *D);
116
John McCall4c40d982010-08-31 07:33:07 +0000117 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
118 CXXDtorType T,
119 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000121
Reid Klecknera4130ba2013-07-22 13:51:44 +0000122 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
123 CXXDtorType DT) const {
124 // Itanium does not emit any destructor variant as an inline thunk.
125 // Delegating may occur as an optimization, but all variants are either
126 // emitted with external linkage or as linkonce if they are inline and used.
127 return false;
128 }
129
130 void EmitCXXDestructors(const CXXDestructorDecl *D);
131
John McCall4c40d982010-08-31 07:33:07 +0000132 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
133 QualType &ResTy,
134 FunctionArgList &Params);
135
136 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000137
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000138 void EmitConstructorCall(CodeGenFunction &CGF,
139 const CXXConstructorDecl *D, CXXCtorType Type,
140 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000141 llvm::Value *This,
142 CallExpr::const_arg_iterator ArgBeg,
143 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000144
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000145 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
146 llvm::Value *This, llvm::Type *Ty);
147
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000148 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
149 const CXXDestructorDecl *Dtor,
150 CXXDtorType DtorType, SourceLocation CallLoc,
151 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000152
Reid Kleckner90633022013-06-19 15:20:38 +0000153 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
154 const CXXRecordDecl *RD);
155
Joao Matos285baac2012-07-17 17:10:11 +0000156 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000157 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000158
John McCalle2b45e22012-05-01 05:23:51 +0000159 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000160 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
161 llvm::Value *NewPtr,
162 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000163 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000164 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000165 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
166 llvm::Value *allocPtr,
167 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000168
John McCall3030eb82010-11-06 09:44:32 +0000169 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000170 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000171 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
172 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000173
174 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
175 llvm::GlobalVariable *Var);
176 void EmitThreadLocalInitFuncs(
177 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
178 llvm::Function *InitFunc);
179 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
180 const DeclRefExpr *DRE);
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000181
182 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis3a811f12010-05-25 19:52:27 +0000183};
John McCallee79a4c2010-08-21 22:46:04 +0000184
185class ARMCXXABI : public ItaniumCXXABI {
186public:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000187 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
188 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
189 /* UseARMGuardVarABI = */ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000190
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000191 bool HasThisReturn(GlobalDecl GD) const {
192 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
193 isa<CXXDestructorDecl>(GD.getDecl()) &&
194 GD.getDtorType() != Dtor_Deleting));
195 }
John McCall4c40d982010-08-31 07:33:07 +0000196
197 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
198
John McCalle2b45e22012-05-01 05:23:51 +0000199 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000200 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
201 llvm::Value *NewPtr,
202 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000203 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000204 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000205 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
206 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000207};
Charles Davis3a811f12010-05-25 19:52:27 +0000208}
209
Charles Davis071cc7d2010-08-16 03:33:14 +0000210CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000211 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000212 // For IR-generation purposes, there's no significant difference
213 // between the ARM and iOS ABIs.
214 case TargetCXXABI::GenericARM:
215 case TargetCXXABI::iOS:
216 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000217
Tim Northoverc264e162013-01-31 12:13:10 +0000218 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
219 // include the other 32-bit ARM oddities: constructor/destructor return values
220 // and array cookies.
221 case TargetCXXABI::GenericAArch64:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000222 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
223 /* UseARMGuardVarABI = */ true);
Tim Northoverc264e162013-01-31 12:13:10 +0000224
John McCall96fcde02013-01-25 23:36:14 +0000225 case TargetCXXABI::GenericItanium:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000226 if (CGM.getContext().getTargetInfo().getTriple().getArch()
227 == llvm::Triple::le32) {
228 // For PNaCl, use ARM-style method pointers so that PNaCl code
229 // does not assume anything about the alignment of function
230 // pointers.
231 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
232 /* UseARMGuardVarABI = */ false);
233 }
John McCall96fcde02013-01-25 23:36:14 +0000234 return new ItaniumCXXABI(CGM);
235
236 case TargetCXXABI::Microsoft:
237 llvm_unreachable("Microsoft ABI is not Itanium-based");
238 }
239 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000240}
241
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000242llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000243ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
244 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000245 return CGM.PtrDiffTy;
246 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000247}
248
John McCallbabc9a92010-08-22 00:59:17 +0000249/// In the Itanium and ARM ABIs, method pointers have the form:
250/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
251///
252/// In the Itanium ABI:
253/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
254/// - the this-adjustment is (memptr.adj)
255/// - the virtual offset is (memptr.ptr - 1)
256///
257/// In the ARM ABI:
258/// - method pointers are virtual if (memptr.adj & 1) is nonzero
259/// - the this-adjustment is (memptr.adj >> 1)
260/// - the virtual offset is (memptr.ptr)
261/// ARM uses 'adj' for the virtual flag because Thumb functions
262/// may be only single-byte aligned.
263///
264/// If the member is virtual, the adjusted 'this' pointer points
265/// to a vtable pointer from which the virtual offset is applied.
266///
267/// If the member is non-virtual, memptr.ptr is the address of
268/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000269llvm::Value *
270ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
271 llvm::Value *&This,
272 llvm::Value *MemFnPtr,
273 const MemberPointerType *MPT) {
274 CGBuilderTy &Builder = CGF.Builder;
275
276 const FunctionProtoType *FPT =
277 MPT->getPointeeType()->getAs<FunctionProtoType>();
278 const CXXRecordDecl *RD =
279 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
280
Chris Lattner2acc6e32011-07-18 04:24:23 +0000281 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000282 CGM.getTypes().GetFunctionType(
283 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000284
Reid Kleckner92e44d92013-03-22 16:13:10 +0000285 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000286
John McCallbabc9a92010-08-22 00:59:17 +0000287 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
288 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
289 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
290
John McCalld608cdb2010-08-22 10:59:02 +0000291 // Extract memptr.adj, which is in the second field.
292 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000293
294 // Compute the true adjustment.
295 llvm::Value *Adj = RawAdj;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000296 if (UseARMMethodPtrABI)
John McCallbabc9a92010-08-22 00:59:17 +0000297 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000298
299 // Apply the adjustment and cast back to the original struct type
300 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000301 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
302 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
303 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000304
305 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000306 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000307
308 // If the LSB in the function pointer is 1, the function pointer points to
309 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000310 llvm::Value *IsVirtual;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000311 if (UseARMMethodPtrABI)
John McCallbabc9a92010-08-22 00:59:17 +0000312 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
313 else
314 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
315 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000316 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
317
318 // In the virtual path, the adjustment left 'This' pointing to the
319 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000320 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000321 CGF.EmitBlock(FnVirtual);
322
323 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000324 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000325 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000326 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000327
328 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000329 llvm::Value *VTableOffset = FnAsInt;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000330 if (!UseARMMethodPtrABI)
331 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCallbabc9a92010-08-22 00:59:17 +0000332 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000333
334 // Load the virtual function to call.
335 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000336 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000337 CGF.EmitBranch(FnEnd);
338
339 // In the non-virtual path, the function pointer is actually a
340 // function pointer.
341 CGF.EmitBlock(FnNonVirtual);
342 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000343 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000344
345 // We're done.
346 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000347 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000348 Callee->addIncoming(VirtualFn, FnVirtual);
349 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
350 return Callee;
351}
John McCall3023def2010-08-22 03:04:22 +0000352
John McCall6c2ab1d2010-08-31 21:07:20 +0000353/// Compute an l-value by applying the given pointer-to-member to a
354/// base object.
355llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
356 llvm::Value *Base,
357 llvm::Value *MemPtr,
358 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000359 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000360
361 CGBuilderTy &Builder = CGF.Builder;
362
Micah Villmow956a5a12012-10-25 15:39:14 +0000363 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000364
365 // Cast to char*.
366 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
367
368 // Apply the offset, which we assume is non-null.
369 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
370
371 // Cast the address to the appropriate pointer type, adopting the
372 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000373 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000374 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000375 return Builder.CreateBitCast(Addr, PType);
376}
377
John McCall4d4e5c12012-02-15 01:22:51 +0000378/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
379/// conversion.
380///
381/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000382///
383/// Obligatory offset/adjustment diagram:
384/// <-- offset --> <-- adjustment -->
385/// |--------------------------|----------------------|--------------------|
386/// ^Derived address point ^Base address point ^Member address point
387///
388/// So when converting a base member pointer to a derived member pointer,
389/// we add the offset to the adjustment because the address point has
390/// decreased; and conversely, when converting a derived MP to a base MP
391/// we subtract the offset from the adjustment because the address point
392/// has increased.
393///
394/// The standard forbids (at compile time) conversion to and from
395/// virtual bases, which is why we don't have to consider them here.
396///
397/// The standard forbids (at run time) casting a derived MP to a base
398/// MP when the derived MP does not point to a member of the base.
399/// This is why -1 is a reasonable choice for null data member
400/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000401llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000402ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
403 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000404 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000405 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000406 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
407 E->getCastKind() == CK_ReinterpretMemberPointer);
408
409 // Under Itanium, reinterprets don't require any additional processing.
410 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
411
412 // Use constant emission if we can.
413 if (isa<llvm::Constant>(src))
414 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
415
416 llvm::Constant *adj = getMemberPointerAdjustment(E);
417 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000418
419 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000420 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000421
John McCall4d4e5c12012-02-15 01:22:51 +0000422 const MemberPointerType *destTy =
423 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000424
John McCall0bab0cd2010-08-23 01:21:21 +0000425 // For member data pointers, this is just a matter of adding the
426 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000427 if (destTy->isMemberDataPointer()) {
428 llvm::Value *dst;
429 if (isDerivedToBase)
430 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000431 else
John McCall4d4e5c12012-02-15 01:22:51 +0000432 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000433
434 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000435 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
436 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
437 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000438 }
439
John McCalld608cdb2010-08-22 10:59:02 +0000440 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000441 if (UseARMMethodPtrABI) {
John McCall4d4e5c12012-02-15 01:22:51 +0000442 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
443 offset <<= 1;
444 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000445 }
446
John McCall4d4e5c12012-02-15 01:22:51 +0000447 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
448 llvm::Value *dstAdj;
449 if (isDerivedToBase)
450 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000451 else
John McCall4d4e5c12012-02-15 01:22:51 +0000452 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000453
John McCall4d4e5c12012-02-15 01:22:51 +0000454 return Builder.CreateInsertValue(src, dstAdj, 1);
455}
456
457llvm::Constant *
458ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
459 llvm::Constant *src) {
460 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
461 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
462 E->getCastKind() == CK_ReinterpretMemberPointer);
463
464 // Under Itanium, reinterprets don't require any additional processing.
465 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
466
467 // If the adjustment is trivial, we don't need to do anything.
468 llvm::Constant *adj = getMemberPointerAdjustment(E);
469 if (!adj) return src;
470
471 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
472
473 const MemberPointerType *destTy =
474 E->getType()->castAs<MemberPointerType>();
475
476 // For member data pointers, this is just a matter of adding the
477 // offset if the source is non-null.
478 if (destTy->isMemberDataPointer()) {
479 // null maps to null.
480 if (src->isAllOnesValue()) return src;
481
482 if (isDerivedToBase)
483 return llvm::ConstantExpr::getNSWSub(src, adj);
484 else
485 return llvm::ConstantExpr::getNSWAdd(src, adj);
486 }
487
488 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000489 if (UseARMMethodPtrABI) {
John McCall4d4e5c12012-02-15 01:22:51 +0000490 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
491 offset <<= 1;
492 adj = llvm::ConstantInt::get(adj->getType(), offset);
493 }
494
495 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
496 llvm::Constant *dstAdj;
497 if (isDerivedToBase)
498 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
499 else
500 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
501
502 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000503}
John McCallcf2c85e2010-08-22 04:16:24 +0000504
505llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000506ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000507 // Itanium C++ ABI 2.3:
508 // A NULL pointer is represented as -1.
509 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000510 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000511
Reid Kleckner92e44d92013-03-22 16:13:10 +0000512 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000513 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000514 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000515}
516
John McCall5808ce42011-02-03 08:15:49 +0000517llvm::Constant *
518ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
519 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000520 // Itanium C++ ABI 2.3:
521 // A pointer to data member is an offset from the base address of
522 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000523 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000524}
525
John McCall755d8492011-04-12 00:42:48 +0000526llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000527 return BuildMemberPointer(MD, CharUnits::Zero());
528}
529
530llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
531 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000532 assert(MD->isInstance() && "Member function must not be static!");
533 MD = MD->getCanonicalDecl();
534
535 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000536
537 // Get the function pointer (or index if this is a virtual function).
538 llvm::Constant *MemPtr[2];
539 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000540 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000541
Ken Dyck1246ba62011-04-09 01:30:02 +0000542 const ASTContext &Context = getContext();
543 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000544 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000545 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000546
Mark Seaborn21fe4502013-07-24 16:25:13 +0000547 if (UseARMMethodPtrABI) {
John McCalld608cdb2010-08-22 10:59:02 +0000548 // ARM C++ ABI 3.2.1:
549 // This ABI specifies that adj contains twice the this
550 // adjustment, plus 1 if the member function is virtual. The
551 // least significant bit of adj then makes exactly the same
552 // discrimination as the least significant bit of ptr does for
553 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000554 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
555 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000556 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000557 } else {
558 // Itanium C++ ABI 2.3:
559 // For a virtual function, [the pointer field] is 1 plus the
560 // virtual table offset (in bytes) of the function,
561 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000562 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
563 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000564 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000565 }
566 } else {
John McCall755d8492011-04-12 00:42:48 +0000567 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000568 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000569 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000570 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000571 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000572 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000573 } else {
John McCall755d8492011-04-12 00:42:48 +0000574 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
575 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000576 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000577 }
John McCall755d8492011-04-12 00:42:48 +0000578 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000579
Reid Kleckner92e44d92013-03-22 16:13:10 +0000580 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seaborn21fe4502013-07-24 16:25:13 +0000581 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
582 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000583 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000584 }
John McCall875ab102010-08-22 06:43:33 +0000585
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000586 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000587}
588
Richard Smith2d6a5672012-01-14 04:30:29 +0000589llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
590 QualType MPType) {
591 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
592 const ValueDecl *MPD = MP.getMemberPointerDecl();
593 if (!MPD)
594 return EmitNullMemberPointer(MPT);
595
Reid Klecknerf6327302013-05-09 21:01:17 +0000596 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000597
598 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
599 return BuildMemberPointer(MD, ThisAdjustment);
600
601 CharUnits FieldOffset =
602 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
603 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
604}
605
John McCalle9fd7eb2010-08-22 08:30:07 +0000606/// The comparison algorithm is pretty easy: the member pointers are
607/// the same if they're either bitwise identical *or* both null.
608///
609/// ARM is different here only because null-ness is more complicated.
610llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000611ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
612 llvm::Value *L,
613 llvm::Value *R,
614 const MemberPointerType *MPT,
615 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000616 CGBuilderTy &Builder = CGF.Builder;
617
John McCalle9fd7eb2010-08-22 08:30:07 +0000618 llvm::ICmpInst::Predicate Eq;
619 llvm::Instruction::BinaryOps And, Or;
620 if (Inequality) {
621 Eq = llvm::ICmpInst::ICMP_NE;
622 And = llvm::Instruction::Or;
623 Or = llvm::Instruction::And;
624 } else {
625 Eq = llvm::ICmpInst::ICMP_EQ;
626 And = llvm::Instruction::And;
627 Or = llvm::Instruction::Or;
628 }
629
John McCall0bab0cd2010-08-23 01:21:21 +0000630 // Member data pointers are easy because there's a unique null
631 // value, so it just comes down to bitwise equality.
632 if (MPT->isMemberDataPointer())
633 return Builder.CreateICmp(Eq, L, R);
634
635 // For member function pointers, the tautologies are more complex.
636 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000637 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000638 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000639 // (L == R) <==> (L.ptr == R.ptr &&
640 // (L.adj == R.adj ||
641 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000642 // The inequality tautologies have exactly the same structure, except
643 // applying De Morgan's laws.
644
645 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
646 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
647
John McCalle9fd7eb2010-08-22 08:30:07 +0000648 // This condition tests whether L.ptr == R.ptr. This must always be
649 // true for equality to hold.
650 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
651
652 // This condition, together with the assumption that L.ptr == R.ptr,
653 // tests whether the pointers are both null. ARM imposes an extra
654 // condition.
655 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
656 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
657
658 // This condition tests whether L.adj == R.adj. If this isn't
659 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000660 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
661 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000662 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
663
664 // Null member function pointers on ARM clear the low bit of Adj,
665 // so the zero condition has to check that neither low bit is set.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000666 if (UseARMMethodPtrABI) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000667 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
668
669 // Compute (l.adj | r.adj) & 1 and test it against zero.
670 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
671 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
672 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
673 "cmp.or.adj");
674 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
675 }
676
677 // Tie together all our conditions.
678 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
679 Result = Builder.CreateBinOp(And, PtrEq, Result,
680 Inequality ? "memptr.ne" : "memptr.eq");
681 return Result;
682}
683
684llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000685ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
686 llvm::Value *MemPtr,
687 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000688 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000689
690 /// For member data pointers, this is just a check against -1.
691 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000692 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000693 llvm::Value *NegativeOne =
694 llvm::Constant::getAllOnesValue(MemPtr->getType());
695 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
696 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000697
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000698 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000699 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000700
701 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
702 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
703
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000704 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
705 // (the virtual bit) is set.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000706 if (UseARMMethodPtrABI) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000707 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000708 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000709 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000710 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
711 "memptr.isvirtual");
712 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000713 }
714
715 return Result;
716}
John McCall875ab102010-08-22 06:43:33 +0000717
John McCallf16aa102010-08-22 21:01:12 +0000718/// The Itanium ABI requires non-zero initialization only for data
719/// member pointers, for which '0' is a valid offset.
720bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
721 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000722}
John McCall4c40d982010-08-31 07:33:07 +0000723
John McCallecd03b42012-09-25 10:10:39 +0000724/// The Itanium ABI always places an offset to the complete object
725/// at entry -2 in the vtable.
726llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
727 llvm::Value *ptr,
728 QualType type) {
729 // Grab the vtable pointer as an intptr_t*.
730 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
731
732 // Track back to entry -2 and pull out the offset there.
733 llvm::Value *offsetPtr =
734 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
735 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
736 offset->setAlignment(CGF.PointerAlignInBytes);
737
738 // Apply the offset.
739 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
740 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
741}
742
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000743llvm::Value *
744ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
745 llvm::Value *This,
746 const CXXRecordDecl *ClassDecl,
747 const CXXRecordDecl *BaseClassDecl) {
748 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
749 CharUnits VBaseOffsetOffset =
750 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
751
752 llvm::Value *VBaseOffsetPtr =
753 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
754 "vbase.offset.ptr");
755 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
756 CGM.PtrDiffTy->getPointerTo());
757
758 llvm::Value *VBaseOffset =
759 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
760
761 return VBaseOffset;
762}
763
John McCall4c40d982010-08-31 07:33:07 +0000764/// The generic ABI passes 'this', plus a VTT if it's initializing a
765/// base subobject.
766void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
767 CXXCtorType Type,
768 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000769 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000770 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000771
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000772 // 'this' parameter is already there, as well as 'this' return if
773 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000774
775 // Check if we need to add a VTT parameter (which has type void **).
776 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
777 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
778}
779
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000780void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
781 // Just make sure we're in sync with TargetCXXABI.
782 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
783
784 // The constructor used for constructing this as a complete class;
785 // constucts the virtual bases, then calls the base constructor.
786 if (!D->getParent()->isAbstract()) {
787 // We don't need to emit the complete ctor if the class is abstract.
788 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
789 }
790
791 // The constructor used for constructing this as a base class;
792 // ignores virtual bases.
793 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
794}
795
John McCall4c40d982010-08-31 07:33:07 +0000796/// The generic ABI passes 'this', plus a VTT if it's destroying a
797/// base subobject.
798void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
799 CXXDtorType Type,
800 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000801 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000802 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000803
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000804 // 'this' parameter is already there, as well as 'this' return if
805 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000806
807 // Check if we need to add a VTT parameter (which has type void **).
808 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
809 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
810}
811
Reid Klecknera4130ba2013-07-22 13:51:44 +0000812void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
813 // The destructor in a virtual table is always a 'deleting'
814 // destructor, which calls the complete destructor and then uses the
815 // appropriate operator delete.
816 if (D->isVirtual())
817 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
818
819 // The destructor used for destructing this as a most-derived class;
820 // call the base destructor and then destructs any virtual bases.
821 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
822
823 // The destructor used for destructing this as a base class; ignores
824 // virtual bases.
825 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
826}
827
John McCall4c40d982010-08-31 07:33:07 +0000828void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
829 QualType &ResTy,
830 FunctionArgList &Params) {
831 /// Create the 'this' variable.
832 BuildThisParam(CGF, Params);
833
834 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
835 assert(MD->isInstance());
836
837 // Check if we need a VTT parameter as well.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000838 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000839 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000840
841 // FIXME: avoid the fake decl
842 QualType T = Context.getPointerType(Context.VoidPtrTy);
843 ImplicitParamDecl *VTTDecl
844 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
845 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000846 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000847 getVTTDecl(CGF) = VTTDecl;
848 }
849}
850
John McCall4c40d982010-08-31 07:33:07 +0000851void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
852 /// Initialize the 'this' slot.
853 EmitThisParam(CGF);
854
855 /// Initialize the 'vtt' slot if needed.
856 if (getVTTDecl(CGF)) {
857 getVTTValue(CGF)
858 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
859 "vtt");
860 }
John McCall4c40d982010-08-31 07:33:07 +0000861
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000862 /// If this is a function that the ABI specifies returns 'this', initialize
863 /// the return slot to 'this' at the start of the function.
864 ///
865 /// Unlike the setting of return types, this is done within the ABI
866 /// implementation instead of by clients of CGCXXABI because:
867 /// 1) getThisValue is currently protected
868 /// 2) in theory, an ABI could implement 'this' returns some other way;
869 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000870 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000871 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000872}
873
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000874void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000875 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000876 CXXCtorType Type,
877 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000878 llvm::Value *This,
879 CallExpr::const_arg_iterator ArgBeg,
880 CallExpr::const_arg_iterator ArgEnd) {
881 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
882 Delegating);
883 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
884 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
885
886 // FIXME: Provide a source location here.
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000887 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
888 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000889}
890
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000891llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
892 GlobalDecl GD,
893 llvm::Value *This,
894 llvm::Type *Ty) {
895 GD = GD.getCanonicalDecl();
896 Ty = Ty->getPointerTo()->getPointerTo();
897 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
898
899 uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(GD);
900 llvm::Value *VFuncPtr =
901 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
902 return CGF.Builder.CreateLoad(VFuncPtr);
903}
904
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000905void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
906 const CXXDestructorDecl *Dtor,
907 CXXDtorType DtorType,
908 SourceLocation CallLoc,
909 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000910 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
911
912 const CGFunctionInfo *FInfo
913 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
914 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000915 llvm::Value *Callee =
916 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000917
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000918 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
919 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000920}
921
Reid Kleckner90633022013-06-19 15:20:38 +0000922void ItaniumCXXABI::EmitVirtualInheritanceTables(
923 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
924 CodeGenVTables &VTables = CGM.getVTables();
925 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
926 VTables.EmitVTTDefinition(VTT, Linkage, RD);
927}
928
John McCall4c40d982010-08-31 07:33:07 +0000929void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
930 RValue RV, QualType ResultType) {
931 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
932 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
933
934 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000935 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000936 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
937 RValue Undef = RValue::get(llvm::UndefValue::get(T));
938 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
939}
John McCall1e7fe752010-09-02 09:58:18 +0000940
941/************************** Array allocation cookies **************************/
942
John McCalle2b45e22012-05-01 05:23:51 +0000943CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
944 // The array cookie is a size_t; pad that up to the element alignment.
945 // The cookie is actually right-justified in that space.
946 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
947 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000948}
949
950llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
951 llvm::Value *NewPtr,
952 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000953 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000954 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000955 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000956
Micah Villmow956a5a12012-10-25 15:39:14 +0000957 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000958
John McCall9cb2cee2010-09-02 10:25:57 +0000959 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000960 QualType SizeTy = Ctx.getSizeType();
961 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
962
963 // The size of the cookie.
964 CharUnits CookieSize =
965 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000966 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000967
968 // Compute an offset to the cookie.
969 llvm::Value *CookiePtr = NewPtr;
970 CharUnits CookieOffset = CookieSize - SizeSize;
971 if (!CookieOffset.isZero())
972 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
973 CookieOffset.getQuantity());
974
975 // Write the number of elements into the appropriate slot.
976 llvm::Value *NumElementsPtr
977 = CGF.Builder.CreateBitCast(CookiePtr,
978 CGF.ConvertType(SizeTy)->getPointerTo(AS));
979 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
980
981 // Finally, compute a pointer to the actual data buffer by skipping
982 // over the cookie completely.
983 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
984 CookieSize.getQuantity());
985}
986
John McCalle2b45e22012-05-01 05:23:51 +0000987llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
988 llvm::Value *allocPtr,
989 CharUnits cookieSize) {
990 // The element size is right-justified in the cookie.
991 llvm::Value *numElementsPtr = allocPtr;
992 CharUnits numElementsOffset =
993 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
994 if (!numElementsOffset.isZero())
995 numElementsPtr =
996 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
997 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000998
Micah Villmow956a5a12012-10-25 15:39:14 +0000999 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001000 numElementsPtr =
1001 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1002 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001003}
1004
John McCalle2b45e22012-05-01 05:23:51 +00001005CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +00001006 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +00001007 // struct array_cookie {
1008 // std::size_t element_size; // element_size != 0
1009 // std::size_t element_count;
1010 // };
John McCallf3bbb152013-01-25 23:36:19 +00001011 // But the base ABI doesn't give anything an alignment greater than
1012 // 8, so we can dismiss this as typical ABI-author blindness to
1013 // actual language complexity and round up to the element alignment.
1014 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1015 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +00001016}
1017
1018llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +00001019 llvm::Value *newPtr,
1020 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +00001021 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +00001022 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +00001023 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +00001024
John McCallf3bbb152013-01-25 23:36:19 +00001025 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1026 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +00001027
1028 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +00001029 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +00001030
1031 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +00001032 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1033 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1034 getContext().getTypeSizeInChars(elementType).getQuantity());
1035 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +00001036
1037 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +00001038 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1039 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +00001040
1041 // Finally, compute a pointer to the actual data buffer by skipping
1042 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +00001043 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1044 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1045 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +00001046}
1047
John McCalle2b45e22012-05-01 05:23:51 +00001048llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1049 llvm::Value *allocPtr,
1050 CharUnits cookieSize) {
1051 // The number of elements is at offset sizeof(size_t) relative to
1052 // the allocated pointer.
1053 llvm::Value *numElementsPtr
1054 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +00001055
Micah Villmow956a5a12012-10-25 15:39:14 +00001056 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001057 numElementsPtr =
1058 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1059 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001060}
1061
John McCall5cd91b52010-09-08 01:44:27 +00001062/*********************** Static local initialization **************************/
1063
1064static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001065 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001066 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001067 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001068 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001069 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001070 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001071 llvm::AttributeSet::get(CGM.getLLVMContext(),
1072 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001073 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001074}
1075
1076static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001077 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001078 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001079 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001080 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001081 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001082 llvm::AttributeSet::get(CGM.getLLVMContext(),
1083 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001084 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001085}
1086
1087static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001088 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001089 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001090 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001091 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001092 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001093 llvm::AttributeSet::get(CGM.getLLVMContext(),
1094 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001095 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001096}
1097
1098namespace {
1099 struct CallGuardAbort : EHScopeStack::Cleanup {
1100 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001101 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001102
John McCallad346f42011-07-12 20:27:29 +00001103 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001104 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1105 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001106 }
1107 };
1108}
1109
1110/// The ARM code here follows the Itanium code closely enough that we
1111/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001112void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1113 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001114 llvm::GlobalVariable *var,
1115 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001116 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001117
Richard Smith04e51762013-04-14 23:01:42 +00001118 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001119 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001120 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1121 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001122
Anders Carlsson173d5122011-04-27 04:37:08 +00001123 // If we have a global variable with internal linkage and thread-safe statics
1124 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001125 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1126
1127 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001128 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001129 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001130 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001131 // Guard variables are 64 bits in the generic ABI and size width on ARM
1132 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seaborn21fe4502013-07-24 16:25:13 +00001133 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001134 }
John McCall355bba72012-03-30 21:00:39 +00001135 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001136
John McCall355bba72012-03-30 21:00:39 +00001137 // Create the guard variable if we don't already have it (as we
1138 // might if we're double-emitting this function body).
1139 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1140 if (!guard) {
1141 // Mangle the name for the guard.
1142 SmallString<256> guardName;
1143 {
1144 llvm::raw_svector_ostream out(guardName);
Reid Kleckner942f9fe2013-09-10 20:14:30 +00001145 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCall355bba72012-03-30 21:00:39 +00001146 out.flush();
1147 }
John McCall112c9672010-11-02 21:04:24 +00001148
John McCall355bba72012-03-30 21:00:39 +00001149 // Create the guard variable with a zero-initializer.
1150 // Just absorb linkage and visibility from the guarded variable.
1151 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1152 false, var->getLinkage(),
1153 llvm::ConstantInt::get(guardTy, 0),
1154 guardName.str());
1155 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001156 // If the variable is thread-local, so is its guard variable.
1157 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001158
1159 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1160 }
John McCall49d26d22012-03-30 07:09:50 +00001161
John McCall5cd91b52010-09-08 01:44:27 +00001162 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001163 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001164
1165 // ARM C++ ABI 3.2.3.1:
1166 // To support the potential use of initialization guard variables
1167 // as semaphores that are the target of ARM SWP and LDREX/STREX
1168 // synchronizing instructions we define a static initialization
1169 // guard variable to be a 4-byte aligned, 4- byte word with the
1170 // following inline access protocol.
1171 // #define INITIALIZED 1
1172 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1173 // if (__cxa_guard_acquire(&obj_guard))
1174 // ...
1175 // }
Mark Seaborn21fe4502013-07-24 16:25:13 +00001176 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001177 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001178 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1179 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001180 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001181
1182 // Itanium C++ ABI 3.3.2:
1183 // The following is pseudo-code showing how these functions can be used:
1184 // if (obj_guard.first_byte == 0) {
1185 // if ( __cxa_guard_acquire (&obj_guard) ) {
1186 // try {
1187 // ... initialize the object ...;
1188 // } catch (...) {
1189 // __cxa_guard_abort (&obj_guard);
1190 // throw;
1191 // }
1192 // ... queue object destructor with __cxa_atexit() ...;
1193 // __cxa_guard_release (&obj_guard);
1194 // }
1195 // }
1196 } else {
1197 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001198 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001199 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001200 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001201
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001202 // Itanium ABI:
1203 // An implementation supporting thread-safety on multiprocessor
1204 // systems must also guarantee that references to the initialized
1205 // object do not occur before the load of the initialization flag.
1206 //
1207 // In LLVM, we do this by marking the load Acquire.
1208 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001209 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001210
John McCall355bba72012-03-30 21:00:39 +00001211 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001212 }
1213
1214 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1215 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1216
1217 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001218 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001219
1220 CGF.EmitBlock(InitCheckBlock);
1221
1222 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001223 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001224 // Call __cxa_guard_acquire.
1225 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001226 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001227
1228 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1229
1230 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1231 InitBlock, EndBlock);
1232
1233 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001234 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001235
1236 CGF.EmitBlock(InitBlock);
1237 }
1238
1239 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001240 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001241
John McCall0502a222011-06-17 07:33:57 +00001242 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001243 // Pop the guard-abort cleanup if we pushed one.
1244 CGF.PopCleanupBlock();
1245
1246 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001247 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001248 } else {
John McCall355bba72012-03-30 21:00:39 +00001249 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001250 }
1251
1252 CGF.EmitBlock(EndBlock);
1253}
John McCall20bb1752012-05-01 06:13:13 +00001254
1255/// Register a global destructor using __cxa_atexit.
1256static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1257 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001258 llvm::Constant *addr,
1259 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001260 const char *Name = "__cxa_atexit";
1261 if (TLS) {
1262 const llvm::Triple &T = CGF.getTarget().getTriple();
1263 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1264 }
Richard Smith04e51762013-04-14 23:01:42 +00001265
John McCall20bb1752012-05-01 06:13:13 +00001266 // We're assuming that the destructor function is something we can
1267 // reasonably call with the default CC. Go ahead and cast it to the
1268 // right prototype.
1269 llvm::Type *dtorTy =
1270 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1271
1272 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1273 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1274 llvm::FunctionType *atexitTy =
1275 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1276
1277 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001278 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001279 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1280 fn->setDoesNotThrow();
1281
1282 // Create a variable that binds the atexit to this shared object.
1283 llvm::Constant *handle =
1284 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1285
1286 llvm::Value *args[] = {
1287 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1288 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1289 handle
1290 };
John McCallbd7370a2013-02-28 19:01:20 +00001291 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001292}
1293
1294/// Register a global destructor as best as we know how.
1295void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001296 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001297 llvm::Constant *dtor,
1298 llvm::Constant *addr) {
1299 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001300 if (CGM.getCodeGenOpts().CXAAtExit)
1301 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1302
1303 if (D.getTLSKind())
1304 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001305
1306 // In Apple kexts, we want to add a global destructor entry.
1307 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001308 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001309 // Generate a global destructor entry.
1310 return CGM.AddCXXDtorEntry(dtor, addr);
1311 }
1312
David Blaikiec7971a92013-08-27 23:57:18 +00001313 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCall20bb1752012-05-01 06:13:13 +00001314}
Richard Smithb80a16e2013-04-19 16:42:07 +00001315
1316/// Get the appropriate linkage for the wrapper function. This is essentially
1317/// the weak form of the variable's linkage; every translation unit which wneeds
1318/// the wrapper emits a copy, and we want the linker to merge them.
1319static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1320 llvm::GlobalValue::LinkageTypes VarLinkage) {
1321 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1322 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1323 // For internal linkage variables, we don't need an external or weak wrapper.
1324 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1325 return VarLinkage;
1326 return llvm::GlobalValue::WeakODRLinkage;
1327}
1328
1329llvm::Function *
1330ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1331 llvm::GlobalVariable *Var) {
1332 // Mangle the name for the thread_local wrapper function.
1333 SmallString<256> WrapperName;
1334 {
1335 llvm::raw_svector_ostream Out(WrapperName);
1336 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1337 Out.flush();
1338 }
1339
1340 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1341 return cast<llvm::Function>(V);
1342
1343 llvm::Type *RetTy = Var->getType();
1344 if (VD->getType()->isReferenceType())
1345 RetTy = RetTy->getPointerElementType();
1346
1347 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1348 llvm::Function *Wrapper = llvm::Function::Create(
1349 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1350 &CGM.getModule());
1351 // Always resolve references to the wrapper at link time.
1352 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1353 return Wrapper;
1354}
1355
1356void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1357 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1358 llvm::Function *InitFunc) {
1359 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1360 const VarDecl *VD = Decls[I].first;
1361 llvm::GlobalVariable *Var = Decls[I].second;
1362
1363 // Mangle the name for the thread_local initialization function.
1364 SmallString<256> InitFnName;
1365 {
1366 llvm::raw_svector_ostream Out(InitFnName);
1367 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1368 Out.flush();
1369 }
1370
1371 // If we have a definition for the variable, emit the initialization
1372 // function as an alias to the global Init function (if any). Otherwise,
1373 // produce a declaration of the initialization function.
1374 llvm::GlobalValue *Init = 0;
1375 bool InitIsInitFunc = false;
1376 if (VD->hasDefinition()) {
1377 InitIsInitFunc = true;
1378 if (InitFunc)
1379 Init =
1380 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1381 InitFnName.str(), InitFunc, &CGM.getModule());
1382 } else {
1383 // Emit a weak global function referring to the initialization function.
1384 // This function will not exist if the TU defining the thread_local
1385 // variable in question does not need any dynamic initialization for
1386 // its thread_local variables.
1387 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1388 Init = llvm::Function::Create(
1389 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1390 &CGM.getModule());
1391 }
1392
1393 if (Init)
1394 Init->setVisibility(Var->getVisibility());
1395
1396 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1397 llvm::LLVMContext &Context = CGM.getModule().getContext();
1398 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1399 CGBuilderTy Builder(Entry);
1400 if (InitIsInitFunc) {
1401 if (Init)
1402 Builder.CreateCall(Init);
1403 } else {
1404 // Don't know whether we have an init function. Call it if it exists.
1405 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1406 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1407 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1408 Builder.CreateCondBr(Have, InitBB, ExitBB);
1409
1410 Builder.SetInsertPoint(InitBB);
1411 Builder.CreateCall(Init);
1412 Builder.CreateBr(ExitBB);
1413
1414 Builder.SetInsertPoint(ExitBB);
1415 }
1416
1417 // For a reference, the result of the wrapper function is a pointer to
1418 // the referenced object.
1419 llvm::Value *Val = Var;
1420 if (VD->getType()->isReferenceType()) {
1421 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1422 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1423 Val = LI;
1424 }
1425
1426 Builder.CreateRet(Val);
1427 }
1428}
1429
1430LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1431 const DeclRefExpr *DRE) {
1432 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1433 QualType T = VD->getType();
1434 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1435 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1436 llvm::Function *Wrapper =
1437 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1438
1439 Val = CGF.Builder.CreateCall(Wrapper);
1440
1441 LValue LV;
1442 if (VD->getType()->isReferenceType())
1443 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1444 else
1445 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1446 CGF.getContext().getDeclAlign(VD));
1447 // FIXME: need setObjCGCLValueClass?
1448 return LV;
1449}
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001450
1451/// Return whether the given global decl needs a VTT parameter, which it does
1452/// if it's a base constructor or destructor with virtual bases.
1453bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1454 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1455
1456 // We don't have any virtual bases, just return early.
1457 if (!MD->getParent()->getNumVBases())
1458 return false;
1459
1460 // Check if we have a base constructor.
1461 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1462 return true;
1463
1464 // Check if we have a base destructor.
1465 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1466 return true;
1467
1468 return false;
1469}