blob: 6ffc39e2643885de52a62986d5e1fd8a3b2e96fb [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 {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +000037 /// VTables - All the vtables which have been defined.
38 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
39
John McCall93d557b2010-08-22 00:05:51 +000040protected:
Mark Seaborn21fe4502013-07-24 16:25:13 +000041 bool UseARMMethodPtrABI;
42 bool UseARMGuardVarABI;
John McCall0bab0cd2010-08-23 01:21:21 +000043
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +000044 ItaniumMangleContext &getMangleContext() {
45 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
46 }
47
Charles Davis3a811f12010-05-25 19:52:27 +000048public:
Mark Seaborn21fe4502013-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 McCall93d557b2010-08-22 00:05:51 +000054
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000055 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
56 // 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
61 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
62 // 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
John McCallf16aa102010-08-22 21:01:12 +000069 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000070
Chris Lattner9cbe4f02011-07-09 17:41:47 +000071 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000072
John McCall93d557b2010-08-22 00:05:51 +000073 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74 llvm::Value *&This,
75 llvm::Value *MemFnPtr,
76 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000077
John McCall6c2ab1d2010-08-31 21:07:20 +000078 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
79 llvm::Value *Base,
80 llvm::Value *MemPtr,
81 const MemberPointerType *MPT);
82
John McCall0bab0cd2010-08-23 01:21:21 +000083 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
84 const CastExpr *E,
85 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000086 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
87 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000088
John McCall0bab0cd2010-08-23 01:21:21 +000089 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000090
John McCall755d8492011-04-12 00:42:48 +000091 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000092 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
93 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000094 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
95 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
96 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000097
John McCall0bab0cd2010-08-23 01:21:21 +000098 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
99 llvm::Value *L,
100 llvm::Value *R,
101 const MemberPointerType *MPT,
102 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +0000103
John McCall0bab0cd2010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
105 llvm::Value *Addr,
106 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +0000107
John McCallecd03b42012-09-25 10:10:39 +0000108 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
109 llvm::Value *ptr,
110 QualType type);
111
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000112 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
113 llvm::Value *This,
114 const CXXRecordDecl *ClassDecl,
115 const CXXRecordDecl *BaseClassDecl);
116
John McCall4c40d982010-08-31 07:33:07 +0000117 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
118 CXXCtorType T,
119 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000121
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000122 void EmitCXXConstructors(const CXXConstructorDecl *D);
123
John McCall4c40d982010-08-31 07:33:07 +0000124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
125 CXXDtorType T,
126 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000128
Reid Klecknera4130ba2013-07-22 13:51:44 +0000129 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
130 CXXDtorType DT) const {
131 // Itanium does not emit any destructor variant as an inline thunk.
132 // Delegating may occur as an optimization, but all variants are either
133 // emitted with external linkage or as linkonce if they are inline and used.
134 return false;
135 }
136
137 void EmitCXXDestructors(const CXXDestructorDecl *D);
138
John McCall4c40d982010-08-31 07:33:07 +0000139 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
140 QualType &ResTy,
141 FunctionArgList &Params);
142
143 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000144
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000145 void EmitConstructorCall(CodeGenFunction &CGF,
146 const CXXConstructorDecl *D, CXXCtorType Type,
147 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000148 llvm::Value *This,
149 CallExpr::const_arg_iterator ArgBeg,
150 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000151
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000152 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
153
154 llvm::Value *getVTableAddressPointInStructor(
155 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
156 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
157 bool &NeedsVirtualOffset);
158
159 llvm::Constant *
160 getVTableAddressPointForConstExpr(BaseSubobject Base,
161 const CXXRecordDecl *VTableClass);
162
163 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
164 CharUnits VPtrOffset);
165
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000166 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
167 llvm::Value *This, llvm::Type *Ty);
168
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000169 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
170 const CXXDestructorDecl *Dtor,
171 CXXDtorType DtorType, SourceLocation CallLoc,
172 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000173
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000174 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner90633022013-06-19 15:20:38 +0000175
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000176 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
177 // Allow inlining of thunks by emitting them with available_externally
178 // linkage together with vtables when needed.
179 if (ForVTable)
180 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
181 }
182
Joao Matos285baac2012-07-17 17:10:11 +0000183 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000184 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000185
John McCalle2b45e22012-05-01 05:23:51 +0000186 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000187 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
188 llvm::Value *NewPtr,
189 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000190 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000191 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000192 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
193 llvm::Value *allocPtr,
194 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000195
John McCall3030eb82010-11-06 09:44:32 +0000196 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000197 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000198 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
199 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000200
201 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
202 llvm::GlobalVariable *Var);
203 void EmitThreadLocalInitFuncs(
204 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
205 llvm::Function *InitFunc);
206 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
207 const DeclRefExpr *DRE);
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000208
209 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis3a811f12010-05-25 19:52:27 +0000210};
John McCallee79a4c2010-08-21 22:46:04 +0000211
212class ARMCXXABI : public ItaniumCXXABI {
213public:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000214 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
215 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
216 /* UseARMGuardVarABI = */ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000217
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000218 bool HasThisReturn(GlobalDecl GD) const {
219 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
220 isa<CXXDestructorDecl>(GD.getDecl()) &&
221 GD.getDtorType() != Dtor_Deleting));
222 }
John McCall4c40d982010-08-31 07:33:07 +0000223
224 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
225
John McCalle2b45e22012-05-01 05:23:51 +0000226 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000227 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
228 llvm::Value *NewPtr,
229 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000230 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000231 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000232 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
233 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000234};
Charles Davis3a811f12010-05-25 19:52:27 +0000235}
236
Charles Davis071cc7d2010-08-16 03:33:14 +0000237CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000238 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000239 // For IR-generation purposes, there's no significant difference
240 // between the ARM and iOS ABIs.
241 case TargetCXXABI::GenericARM:
242 case TargetCXXABI::iOS:
243 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000244
Tim Northoverc264e162013-01-31 12:13:10 +0000245 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
246 // include the other 32-bit ARM oddities: constructor/destructor return values
247 // and array cookies.
248 case TargetCXXABI::GenericAArch64:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000249 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
250 /* UseARMGuardVarABI = */ true);
Tim Northoverc264e162013-01-31 12:13:10 +0000251
John McCall96fcde02013-01-25 23:36:14 +0000252 case TargetCXXABI::GenericItanium:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000253 if (CGM.getContext().getTargetInfo().getTriple().getArch()
254 == llvm::Triple::le32) {
255 // For PNaCl, use ARM-style method pointers so that PNaCl code
256 // does not assume anything about the alignment of function
257 // pointers.
258 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
259 /* UseARMGuardVarABI = */ false);
260 }
John McCall96fcde02013-01-25 23:36:14 +0000261 return new ItaniumCXXABI(CGM);
262
263 case TargetCXXABI::Microsoft:
264 llvm_unreachable("Microsoft ABI is not Itanium-based");
265 }
266 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000267}
268
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000269llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000270ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
271 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000272 return CGM.PtrDiffTy;
273 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000274}
275
John McCallbabc9a92010-08-22 00:59:17 +0000276/// In the Itanium and ARM ABIs, method pointers have the form:
277/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
278///
279/// In the Itanium ABI:
280/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
281/// - the this-adjustment is (memptr.adj)
282/// - the virtual offset is (memptr.ptr - 1)
283///
284/// In the ARM ABI:
285/// - method pointers are virtual if (memptr.adj & 1) is nonzero
286/// - the this-adjustment is (memptr.adj >> 1)
287/// - the virtual offset is (memptr.ptr)
288/// ARM uses 'adj' for the virtual flag because Thumb functions
289/// may be only single-byte aligned.
290///
291/// If the member is virtual, the adjusted 'this' pointer points
292/// to a vtable pointer from which the virtual offset is applied.
293///
294/// If the member is non-virtual, memptr.ptr is the address of
295/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000296llvm::Value *
297ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
298 llvm::Value *&This,
299 llvm::Value *MemFnPtr,
300 const MemberPointerType *MPT) {
301 CGBuilderTy &Builder = CGF.Builder;
302
303 const FunctionProtoType *FPT =
304 MPT->getPointeeType()->getAs<FunctionProtoType>();
305 const CXXRecordDecl *RD =
306 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
307
Chris Lattner2acc6e32011-07-18 04:24:23 +0000308 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000309 CGM.getTypes().GetFunctionType(
310 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000311
Reid Kleckner92e44d92013-03-22 16:13:10 +0000312 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000313
John McCallbabc9a92010-08-22 00:59:17 +0000314 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
315 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
316 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
317
John McCalld608cdb2010-08-22 10:59:02 +0000318 // Extract memptr.adj, which is in the second field.
319 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000320
321 // Compute the true adjustment.
322 llvm::Value *Adj = RawAdj;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000323 if (UseARMMethodPtrABI)
John McCallbabc9a92010-08-22 00:59:17 +0000324 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000325
326 // Apply the adjustment and cast back to the original struct type
327 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000328 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
329 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
330 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000331
332 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000333 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000334
335 // If the LSB in the function pointer is 1, the function pointer points to
336 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000337 llvm::Value *IsVirtual;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000338 if (UseARMMethodPtrABI)
John McCallbabc9a92010-08-22 00:59:17 +0000339 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
340 else
341 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
342 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000343 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
344
345 // In the virtual path, the adjustment left 'This' pointing to the
346 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000347 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000348 CGF.EmitBlock(FnVirtual);
349
350 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000351 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000352 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000353 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000354
355 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000356 llvm::Value *VTableOffset = FnAsInt;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000357 if (!UseARMMethodPtrABI)
358 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCallbabc9a92010-08-22 00:59:17 +0000359 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000360
361 // Load the virtual function to call.
362 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000363 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000364 CGF.EmitBranch(FnEnd);
365
366 // In the non-virtual path, the function pointer is actually a
367 // function pointer.
368 CGF.EmitBlock(FnNonVirtual);
369 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000370 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000371
372 // We're done.
373 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000374 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000375 Callee->addIncoming(VirtualFn, FnVirtual);
376 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
377 return Callee;
378}
John McCall3023def2010-08-22 03:04:22 +0000379
John McCall6c2ab1d2010-08-31 21:07:20 +0000380/// Compute an l-value by applying the given pointer-to-member to a
381/// base object.
382llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
383 llvm::Value *Base,
384 llvm::Value *MemPtr,
385 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000386 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000387
388 CGBuilderTy &Builder = CGF.Builder;
389
Micah Villmow956a5a12012-10-25 15:39:14 +0000390 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000391
392 // Cast to char*.
393 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
394
395 // Apply the offset, which we assume is non-null.
396 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
397
398 // Cast the address to the appropriate pointer type, adopting the
399 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000400 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000401 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000402 return Builder.CreateBitCast(Addr, PType);
403}
404
John McCall4d4e5c12012-02-15 01:22:51 +0000405/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
406/// conversion.
407///
408/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000409///
410/// Obligatory offset/adjustment diagram:
411/// <-- offset --> <-- adjustment -->
412/// |--------------------------|----------------------|--------------------|
413/// ^Derived address point ^Base address point ^Member address point
414///
415/// So when converting a base member pointer to a derived member pointer,
416/// we add the offset to the adjustment because the address point has
417/// decreased; and conversely, when converting a derived MP to a base MP
418/// we subtract the offset from the adjustment because the address point
419/// has increased.
420///
421/// The standard forbids (at compile time) conversion to and from
422/// virtual bases, which is why we don't have to consider them here.
423///
424/// The standard forbids (at run time) casting a derived MP to a base
425/// MP when the derived MP does not point to a member of the base.
426/// This is why -1 is a reasonable choice for null data member
427/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000428llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000429ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
430 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000431 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000432 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000433 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
434 E->getCastKind() == CK_ReinterpretMemberPointer);
435
436 // Under Itanium, reinterprets don't require any additional processing.
437 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
438
439 // Use constant emission if we can.
440 if (isa<llvm::Constant>(src))
441 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
442
443 llvm::Constant *adj = getMemberPointerAdjustment(E);
444 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000445
446 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000447 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000448
John McCall4d4e5c12012-02-15 01:22:51 +0000449 const MemberPointerType *destTy =
450 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000451
John McCall0bab0cd2010-08-23 01:21:21 +0000452 // For member data pointers, this is just a matter of adding the
453 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000454 if (destTy->isMemberDataPointer()) {
455 llvm::Value *dst;
456 if (isDerivedToBase)
457 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000458 else
John McCall4d4e5c12012-02-15 01:22:51 +0000459 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000460
461 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000462 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
463 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
464 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000465 }
466
John McCalld608cdb2010-08-22 10:59:02 +0000467 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000468 if (UseARMMethodPtrABI) {
John McCall4d4e5c12012-02-15 01:22:51 +0000469 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
470 offset <<= 1;
471 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000472 }
473
John McCall4d4e5c12012-02-15 01:22:51 +0000474 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
475 llvm::Value *dstAdj;
476 if (isDerivedToBase)
477 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000478 else
John McCall4d4e5c12012-02-15 01:22:51 +0000479 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000480
John McCall4d4e5c12012-02-15 01:22:51 +0000481 return Builder.CreateInsertValue(src, dstAdj, 1);
482}
483
484llvm::Constant *
485ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
486 llvm::Constant *src) {
487 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
488 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
489 E->getCastKind() == CK_ReinterpretMemberPointer);
490
491 // Under Itanium, reinterprets don't require any additional processing.
492 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
493
494 // If the adjustment is trivial, we don't need to do anything.
495 llvm::Constant *adj = getMemberPointerAdjustment(E);
496 if (!adj) return src;
497
498 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
499
500 const MemberPointerType *destTy =
501 E->getType()->castAs<MemberPointerType>();
502
503 // For member data pointers, this is just a matter of adding the
504 // offset if the source is non-null.
505 if (destTy->isMemberDataPointer()) {
506 // null maps to null.
507 if (src->isAllOnesValue()) return src;
508
509 if (isDerivedToBase)
510 return llvm::ConstantExpr::getNSWSub(src, adj);
511 else
512 return llvm::ConstantExpr::getNSWAdd(src, adj);
513 }
514
515 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000516 if (UseARMMethodPtrABI) {
John McCall4d4e5c12012-02-15 01:22:51 +0000517 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
518 offset <<= 1;
519 adj = llvm::ConstantInt::get(adj->getType(), offset);
520 }
521
522 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
523 llvm::Constant *dstAdj;
524 if (isDerivedToBase)
525 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
526 else
527 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
528
529 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000530}
John McCallcf2c85e2010-08-22 04:16:24 +0000531
532llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000533ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000534 // Itanium C++ ABI 2.3:
535 // A NULL pointer is represented as -1.
536 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000537 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000538
Reid Kleckner92e44d92013-03-22 16:13:10 +0000539 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000540 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000541 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000542}
543
John McCall5808ce42011-02-03 08:15:49 +0000544llvm::Constant *
545ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
546 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000547 // Itanium C++ ABI 2.3:
548 // A pointer to data member is an offset from the base address of
549 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000550 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000551}
552
John McCall755d8492011-04-12 00:42:48 +0000553llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000554 return BuildMemberPointer(MD, CharUnits::Zero());
555}
556
557llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
558 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000559 assert(MD->isInstance() && "Member function must not be static!");
560 MD = MD->getCanonicalDecl();
561
562 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000563
564 // Get the function pointer (or index if this is a virtual function).
565 llvm::Constant *MemPtr[2];
566 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000567 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000568
Ken Dyck1246ba62011-04-09 01:30:02 +0000569 const ASTContext &Context = getContext();
570 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000571 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000572 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000573
Mark Seaborn21fe4502013-07-24 16:25:13 +0000574 if (UseARMMethodPtrABI) {
John McCalld608cdb2010-08-22 10:59:02 +0000575 // ARM C++ ABI 3.2.1:
576 // This ABI specifies that adj contains twice the this
577 // adjustment, plus 1 if the member function is virtual. The
578 // least significant bit of adj then makes exactly the same
579 // discrimination as the least significant bit of ptr does for
580 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000581 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
582 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000583 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000584 } else {
585 // Itanium C++ ABI 2.3:
586 // For a virtual function, [the pointer field] is 1 plus the
587 // virtual table offset (in bytes) of the function,
588 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000589 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
590 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000591 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000592 }
593 } else {
John McCall755d8492011-04-12 00:42:48 +0000594 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000595 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000596 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000597 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000598 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000599 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000600 } else {
John McCall755d8492011-04-12 00:42:48 +0000601 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
602 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000603 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000604 }
John McCall755d8492011-04-12 00:42:48 +0000605 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000606
Reid Kleckner92e44d92013-03-22 16:13:10 +0000607 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seaborn21fe4502013-07-24 16:25:13 +0000608 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
609 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000610 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000611 }
John McCall875ab102010-08-22 06:43:33 +0000612
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000613 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000614}
615
Richard Smith2d6a5672012-01-14 04:30:29 +0000616llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
617 QualType MPType) {
618 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
619 const ValueDecl *MPD = MP.getMemberPointerDecl();
620 if (!MPD)
621 return EmitNullMemberPointer(MPT);
622
Reid Klecknerf6327302013-05-09 21:01:17 +0000623 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000624
625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
626 return BuildMemberPointer(MD, ThisAdjustment);
627
628 CharUnits FieldOffset =
629 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
630 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
631}
632
John McCalle9fd7eb2010-08-22 08:30:07 +0000633/// The comparison algorithm is pretty easy: the member pointers are
634/// the same if they're either bitwise identical *or* both null.
635///
636/// ARM is different here only because null-ness is more complicated.
637llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000638ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
639 llvm::Value *L,
640 llvm::Value *R,
641 const MemberPointerType *MPT,
642 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000643 CGBuilderTy &Builder = CGF.Builder;
644
John McCalle9fd7eb2010-08-22 08:30:07 +0000645 llvm::ICmpInst::Predicate Eq;
646 llvm::Instruction::BinaryOps And, Or;
647 if (Inequality) {
648 Eq = llvm::ICmpInst::ICMP_NE;
649 And = llvm::Instruction::Or;
650 Or = llvm::Instruction::And;
651 } else {
652 Eq = llvm::ICmpInst::ICMP_EQ;
653 And = llvm::Instruction::And;
654 Or = llvm::Instruction::Or;
655 }
656
John McCall0bab0cd2010-08-23 01:21:21 +0000657 // Member data pointers are easy because there's a unique null
658 // value, so it just comes down to bitwise equality.
659 if (MPT->isMemberDataPointer())
660 return Builder.CreateICmp(Eq, L, R);
661
662 // For member function pointers, the tautologies are more complex.
663 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000664 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000665 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000666 // (L == R) <==> (L.ptr == R.ptr &&
667 // (L.adj == R.adj ||
668 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000669 // The inequality tautologies have exactly the same structure, except
670 // applying De Morgan's laws.
671
672 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
673 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
674
John McCalle9fd7eb2010-08-22 08:30:07 +0000675 // This condition tests whether L.ptr == R.ptr. This must always be
676 // true for equality to hold.
677 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
678
679 // This condition, together with the assumption that L.ptr == R.ptr,
680 // tests whether the pointers are both null. ARM imposes an extra
681 // condition.
682 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
683 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
684
685 // This condition tests whether L.adj == R.adj. If this isn't
686 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000687 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
688 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000689 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
690
691 // Null member function pointers on ARM clear the low bit of Adj,
692 // so the zero condition has to check that neither low bit is set.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000693 if (UseARMMethodPtrABI) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000694 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
695
696 // Compute (l.adj | r.adj) & 1 and test it against zero.
697 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
698 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
699 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
700 "cmp.or.adj");
701 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
702 }
703
704 // Tie together all our conditions.
705 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
706 Result = Builder.CreateBinOp(And, PtrEq, Result,
707 Inequality ? "memptr.ne" : "memptr.eq");
708 return Result;
709}
710
711llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000712ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
713 llvm::Value *MemPtr,
714 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000715 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000716
717 /// For member data pointers, this is just a check against -1.
718 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000719 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000720 llvm::Value *NegativeOne =
721 llvm::Constant::getAllOnesValue(MemPtr->getType());
722 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
723 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000724
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000725 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000726 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000727
728 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
729 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
730
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000731 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
732 // (the virtual bit) is set.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000733 if (UseARMMethodPtrABI) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000734 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000735 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000736 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000737 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
738 "memptr.isvirtual");
739 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000740 }
741
742 return Result;
743}
John McCall875ab102010-08-22 06:43:33 +0000744
John McCallf16aa102010-08-22 21:01:12 +0000745/// The Itanium ABI requires non-zero initialization only for data
746/// member pointers, for which '0' is a valid offset.
747bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
748 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000749}
John McCall4c40d982010-08-31 07:33:07 +0000750
John McCallecd03b42012-09-25 10:10:39 +0000751/// The Itanium ABI always places an offset to the complete object
752/// at entry -2 in the vtable.
753llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
754 llvm::Value *ptr,
755 QualType type) {
756 // Grab the vtable pointer as an intptr_t*.
757 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
758
759 // Track back to entry -2 and pull out the offset there.
760 llvm::Value *offsetPtr =
761 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
762 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
763 offset->setAlignment(CGF.PointerAlignInBytes);
764
765 // Apply the offset.
766 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
767 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
768}
769
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000770llvm::Value *
771ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
772 llvm::Value *This,
773 const CXXRecordDecl *ClassDecl,
774 const CXXRecordDecl *BaseClassDecl) {
775 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
776 CharUnits VBaseOffsetOffset =
777 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
778
779 llvm::Value *VBaseOffsetPtr =
780 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
781 "vbase.offset.ptr");
782 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
783 CGM.PtrDiffTy->getPointerTo());
784
785 llvm::Value *VBaseOffset =
786 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
787
788 return VBaseOffset;
789}
790
John McCall4c40d982010-08-31 07:33:07 +0000791/// The generic ABI passes 'this', plus a VTT if it's initializing a
792/// base subobject.
793void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
794 CXXCtorType Type,
795 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000796 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000797 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000798
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000799 // 'this' parameter is already there, as well as 'this' return if
800 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000801
802 // Check if we need to add a VTT parameter (which has type void **).
803 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
804 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
805}
806
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000807void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
808 // Just make sure we're in sync with TargetCXXABI.
809 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
810
811 // The constructor used for constructing this as a complete class;
812 // constucts the virtual bases, then calls the base constructor.
813 if (!D->getParent()->isAbstract()) {
814 // We don't need to emit the complete ctor if the class is abstract.
815 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
816 }
817
818 // The constructor used for constructing this as a base class;
819 // ignores virtual bases.
820 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
821}
822
John McCall4c40d982010-08-31 07:33:07 +0000823/// The generic ABI passes 'this', plus a VTT if it's destroying a
824/// base subobject.
825void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
826 CXXDtorType Type,
827 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000828 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000829 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000830
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000831 // 'this' parameter is already there, as well as 'this' return if
832 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000833
834 // Check if we need to add a VTT parameter (which has type void **).
835 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
836 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
837}
838
Reid Klecknera4130ba2013-07-22 13:51:44 +0000839void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
840 // The destructor in a virtual table is always a 'deleting'
841 // destructor, which calls the complete destructor and then uses the
842 // appropriate operator delete.
843 if (D->isVirtual())
844 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
845
846 // The destructor used for destructing this as a most-derived class;
847 // call the base destructor and then destructs any virtual bases.
848 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
849
850 // The destructor used for destructing this as a base class; ignores
851 // virtual bases.
852 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
853}
854
John McCall4c40d982010-08-31 07:33:07 +0000855void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
856 QualType &ResTy,
857 FunctionArgList &Params) {
858 /// Create the 'this' variable.
859 BuildThisParam(CGF, Params);
860
861 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
862 assert(MD->isInstance());
863
864 // Check if we need a VTT parameter as well.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000865 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000866 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000867
868 // FIXME: avoid the fake decl
869 QualType T = Context.getPointerType(Context.VoidPtrTy);
870 ImplicitParamDecl *VTTDecl
871 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
872 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000873 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000874 getVTTDecl(CGF) = VTTDecl;
875 }
876}
877
John McCall4c40d982010-08-31 07:33:07 +0000878void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
879 /// Initialize the 'this' slot.
880 EmitThisParam(CGF);
881
882 /// Initialize the 'vtt' slot if needed.
883 if (getVTTDecl(CGF)) {
884 getVTTValue(CGF)
885 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
886 "vtt");
887 }
John McCall4c40d982010-08-31 07:33:07 +0000888
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000889 /// If this is a function that the ABI specifies returns 'this', initialize
890 /// the return slot to 'this' at the start of the function.
891 ///
892 /// Unlike the setting of return types, this is done within the ABI
893 /// implementation instead of by clients of CGCXXABI because:
894 /// 1) getThisValue is currently protected
895 /// 2) in theory, an ABI could implement 'this' returns some other way;
896 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000897 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000898 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000899}
900
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000901void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000902 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000903 CXXCtorType Type,
904 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000905 llvm::Value *This,
906 CallExpr::const_arg_iterator ArgBeg,
907 CallExpr::const_arg_iterator ArgEnd) {
908 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
909 Delegating);
910 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
911 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
912
913 // FIXME: Provide a source location here.
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000914 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
915 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000916}
917
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000918void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
919 const CXXRecordDecl *RD) {
920 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
921 if (VTable->hasInitializer())
922 return;
923
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +0000924 ItaniumVTableContext &VTContext = CGM.getVTableContext();
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000925 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
926 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
927
928 // Create and set the initializer.
929 llvm::Constant *Init = CGVT.CreateVTableInitializer(
930 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
931 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
932 VTable->setInitializer(Init);
933
934 // Set the correct linkage.
935 VTable->setLinkage(Linkage);
936
937 // Set the right visibility.
938 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
939
940 // If this is the magic class __cxxabiv1::__fundamental_type_info,
941 // we will emit the typeinfo for the fundamental types. This is the
942 // same behaviour as GCC.
943 const DeclContext *DC = RD->getDeclContext();
944 if (RD->getIdentifier() &&
945 RD->getIdentifier()->isStr("__fundamental_type_info") &&
946 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
947 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
948 DC->getParent()->isTranslationUnit())
949 CGM.EmitFundamentalRTTIDescriptors();
950}
951
952llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
953 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
954 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
955 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
956 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
957
958 llvm::Value *VTableAddressPoint;
959 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
960 // Get the secondary vpointer index.
961 uint64_t VirtualPointerIndex =
962 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
963
964 /// Load the VTT.
965 llvm::Value *VTT = CGF.LoadCXXVTT();
966 if (VirtualPointerIndex)
967 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
968
969 // And load the address point from the VTT.
970 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
971 } else {
972 llvm::Constant *VTable =
973 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
974 uint64_t AddressPoint = CGM.getVTableContext().getVTableLayout(VTableClass)
975 .getAddressPoint(Base);
976 VTableAddressPoint =
977 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
978 }
979
980 return VTableAddressPoint;
981}
982
983llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
984 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
985 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
986
987 // Find the appropriate vtable within the vtable group.
988 uint64_t AddressPoint =
989 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
990 llvm::Value *Indices[] = {
991 llvm::ConstantInt::get(CGM.Int64Ty, 0),
992 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
993 };
994
995 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
996}
997
998llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
999 CharUnits VPtrOffset) {
1000 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1001
1002 llvm::GlobalVariable *&VTable = VTables[RD];
1003 if (VTable)
1004 return VTable;
1005
1006 // Queue up this v-table for possible deferred emission.
1007 CGM.addDeferredVTable(RD);
1008
1009 SmallString<256> OutName;
1010 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +00001011 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001012 Out.flush();
1013 StringRef Name = OutName.str();
1014
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001015 ItaniumVTableContext &VTContext = CGM.getVTableContext();
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001016 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1017 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1018
1019 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1020 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1021 VTable->setUnnamedAddr(true);
1022 return VTable;
1023}
1024
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001025llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1026 GlobalDecl GD,
1027 llvm::Value *This,
1028 llvm::Type *Ty) {
1029 GD = GD.getCanonicalDecl();
1030 Ty = Ty->getPointerTo()->getPointerTo();
1031 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1032
1033 uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(GD);
1034 llvm::Value *VFuncPtr =
1035 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1036 return CGF.Builder.CreateLoad(VFuncPtr);
1037}
1038
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001039void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1040 const CXXDestructorDecl *Dtor,
1041 CXXDtorType DtorType,
1042 SourceLocation CallLoc,
1043 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001044 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1045
1046 const CGFunctionInfo *FInfo
1047 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1048 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001049 llvm::Value *Callee =
1050 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001051
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001052 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1053 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001054}
1055
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001056void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner90633022013-06-19 15:20:38 +00001057 CodeGenVTables &VTables = CGM.getVTables();
1058 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001059 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner90633022013-06-19 15:20:38 +00001060}
1061
John McCall4c40d982010-08-31 07:33:07 +00001062void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1063 RValue RV, QualType ResultType) {
1064 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1065 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1066
1067 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001068 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +00001069 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1070 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1071 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1072}
John McCall1e7fe752010-09-02 09:58:18 +00001073
1074/************************** Array allocation cookies **************************/
1075
John McCalle2b45e22012-05-01 05:23:51 +00001076CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1077 // The array cookie is a size_t; pad that up to the element alignment.
1078 // The cookie is actually right-justified in that space.
1079 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1080 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +00001081}
1082
1083llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1084 llvm::Value *NewPtr,
1085 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +00001086 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +00001087 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +00001088 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +00001089
Micah Villmow956a5a12012-10-25 15:39:14 +00001090 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +00001091
John McCall9cb2cee2010-09-02 10:25:57 +00001092 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +00001093 QualType SizeTy = Ctx.getSizeType();
1094 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1095
1096 // The size of the cookie.
1097 CharUnits CookieSize =
1098 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +00001099 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +00001100
1101 // Compute an offset to the cookie.
1102 llvm::Value *CookiePtr = NewPtr;
1103 CharUnits CookieOffset = CookieSize - SizeSize;
1104 if (!CookieOffset.isZero())
1105 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1106 CookieOffset.getQuantity());
1107
1108 // Write the number of elements into the appropriate slot.
1109 llvm::Value *NumElementsPtr
1110 = CGF.Builder.CreateBitCast(CookiePtr,
1111 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1112 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1113
1114 // Finally, compute a pointer to the actual data buffer by skipping
1115 // over the cookie completely.
1116 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1117 CookieSize.getQuantity());
1118}
1119
John McCalle2b45e22012-05-01 05:23:51 +00001120llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1121 llvm::Value *allocPtr,
1122 CharUnits cookieSize) {
1123 // The element size is right-justified in the cookie.
1124 llvm::Value *numElementsPtr = allocPtr;
1125 CharUnits numElementsOffset =
1126 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1127 if (!numElementsOffset.isZero())
1128 numElementsPtr =
1129 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1130 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +00001131
Micah Villmow956a5a12012-10-25 15:39:14 +00001132 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001133 numElementsPtr =
1134 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1135 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001136}
1137
John McCalle2b45e22012-05-01 05:23:51 +00001138CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +00001139 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +00001140 // struct array_cookie {
1141 // std::size_t element_size; // element_size != 0
1142 // std::size_t element_count;
1143 // };
John McCallf3bbb152013-01-25 23:36:19 +00001144 // But the base ABI doesn't give anything an alignment greater than
1145 // 8, so we can dismiss this as typical ABI-author blindness to
1146 // actual language complexity and round up to the element alignment.
1147 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1148 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +00001149}
1150
1151llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +00001152 llvm::Value *newPtr,
1153 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +00001154 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +00001155 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +00001156 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +00001157
John McCallf3bbb152013-01-25 23:36:19 +00001158 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1159 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +00001160
1161 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +00001162 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +00001163
1164 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +00001165 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1166 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1167 getContext().getTypeSizeInChars(elementType).getQuantity());
1168 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +00001169
1170 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +00001171 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1172 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +00001173
1174 // Finally, compute a pointer to the actual data buffer by skipping
1175 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +00001176 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1177 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1178 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +00001179}
1180
John McCalle2b45e22012-05-01 05:23:51 +00001181llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1182 llvm::Value *allocPtr,
1183 CharUnits cookieSize) {
1184 // The number of elements is at offset sizeof(size_t) relative to
1185 // the allocated pointer.
1186 llvm::Value *numElementsPtr
1187 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +00001188
Micah Villmow956a5a12012-10-25 15:39:14 +00001189 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001190 numElementsPtr =
1191 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1192 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001193}
1194
John McCall5cd91b52010-09-08 01:44:27 +00001195/*********************** Static local initialization **************************/
1196
1197static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001198 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001199 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001200 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001201 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001202 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001203 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001204 llvm::AttributeSet::get(CGM.getLLVMContext(),
1205 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001206 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001207}
1208
1209static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001210 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001211 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001212 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001213 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001214 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001215 llvm::AttributeSet::get(CGM.getLLVMContext(),
1216 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001217 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001218}
1219
1220static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001221 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001222 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001223 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001224 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001225 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001226 llvm::AttributeSet::get(CGM.getLLVMContext(),
1227 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001228 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001229}
1230
1231namespace {
1232 struct CallGuardAbort : EHScopeStack::Cleanup {
1233 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001234 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001235
John McCallad346f42011-07-12 20:27:29 +00001236 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001237 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1238 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001239 }
1240 };
1241}
1242
1243/// The ARM code here follows the Itanium code closely enough that we
1244/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001245void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1246 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001247 llvm::GlobalVariable *var,
1248 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001249 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001250
Richard Smith04e51762013-04-14 23:01:42 +00001251 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001252 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001253 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1254 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001255
Anders Carlsson173d5122011-04-27 04:37:08 +00001256 // If we have a global variable with internal linkage and thread-safe statics
1257 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001258 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1259
1260 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001261 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001262 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001263 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001264 // Guard variables are 64 bits in the generic ABI and size width on ARM
1265 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seaborn21fe4502013-07-24 16:25:13 +00001266 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001267 }
John McCall355bba72012-03-30 21:00:39 +00001268 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001269
John McCall355bba72012-03-30 21:00:39 +00001270 // Create the guard variable if we don't already have it (as we
1271 // might if we're double-emitting this function body).
1272 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1273 if (!guard) {
1274 // Mangle the name for the guard.
1275 SmallString<256> guardName;
1276 {
1277 llvm::raw_svector_ostream out(guardName);
Reid Kleckner942f9fe2013-09-10 20:14:30 +00001278 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCall355bba72012-03-30 21:00:39 +00001279 out.flush();
1280 }
John McCall112c9672010-11-02 21:04:24 +00001281
John McCall355bba72012-03-30 21:00:39 +00001282 // Create the guard variable with a zero-initializer.
1283 // Just absorb linkage and visibility from the guarded variable.
1284 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1285 false, var->getLinkage(),
1286 llvm::ConstantInt::get(guardTy, 0),
1287 guardName.str());
1288 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001289 // If the variable is thread-local, so is its guard variable.
1290 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001291
1292 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1293 }
John McCall49d26d22012-03-30 07:09:50 +00001294
John McCall5cd91b52010-09-08 01:44:27 +00001295 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001296 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001297
1298 // ARM C++ ABI 3.2.3.1:
1299 // To support the potential use of initialization guard variables
1300 // as semaphores that are the target of ARM SWP and LDREX/STREX
1301 // synchronizing instructions we define a static initialization
1302 // guard variable to be a 4-byte aligned, 4- byte word with the
1303 // following inline access protocol.
1304 // #define INITIALIZED 1
1305 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1306 // if (__cxa_guard_acquire(&obj_guard))
1307 // ...
1308 // }
Mark Seaborn21fe4502013-07-24 16:25:13 +00001309 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001310 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001311 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1312 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001313 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001314
1315 // Itanium C++ ABI 3.3.2:
1316 // The following is pseudo-code showing how these functions can be used:
1317 // if (obj_guard.first_byte == 0) {
1318 // if ( __cxa_guard_acquire (&obj_guard) ) {
1319 // try {
1320 // ... initialize the object ...;
1321 // } catch (...) {
1322 // __cxa_guard_abort (&obj_guard);
1323 // throw;
1324 // }
1325 // ... queue object destructor with __cxa_atexit() ...;
1326 // __cxa_guard_release (&obj_guard);
1327 // }
1328 // }
1329 } else {
1330 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001331 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001332 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001333 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001334
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001335 // Itanium ABI:
1336 // An implementation supporting thread-safety on multiprocessor
1337 // systems must also guarantee that references to the initialized
1338 // object do not occur before the load of the initialization flag.
1339 //
1340 // In LLVM, we do this by marking the load Acquire.
1341 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001342 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001343
John McCall355bba72012-03-30 21:00:39 +00001344 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001345 }
1346
1347 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1348 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1349
1350 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001351 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001352
1353 CGF.EmitBlock(InitCheckBlock);
1354
1355 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001356 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001357 // Call __cxa_guard_acquire.
1358 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001359 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001360
1361 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1362
1363 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1364 InitBlock, EndBlock);
1365
1366 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001367 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001368
1369 CGF.EmitBlock(InitBlock);
1370 }
1371
1372 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001373 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001374
John McCall0502a222011-06-17 07:33:57 +00001375 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001376 // Pop the guard-abort cleanup if we pushed one.
1377 CGF.PopCleanupBlock();
1378
1379 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001380 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001381 } else {
John McCall355bba72012-03-30 21:00:39 +00001382 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001383 }
1384
1385 CGF.EmitBlock(EndBlock);
1386}
John McCall20bb1752012-05-01 06:13:13 +00001387
1388/// Register a global destructor using __cxa_atexit.
1389static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1390 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001391 llvm::Constant *addr,
1392 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001393 const char *Name = "__cxa_atexit";
1394 if (TLS) {
1395 const llvm::Triple &T = CGF.getTarget().getTriple();
1396 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1397 }
Richard Smith04e51762013-04-14 23:01:42 +00001398
John McCall20bb1752012-05-01 06:13:13 +00001399 // We're assuming that the destructor function is something we can
1400 // reasonably call with the default CC. Go ahead and cast it to the
1401 // right prototype.
1402 llvm::Type *dtorTy =
1403 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1404
1405 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1406 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1407 llvm::FunctionType *atexitTy =
1408 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1409
1410 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001411 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001412 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1413 fn->setDoesNotThrow();
1414
1415 // Create a variable that binds the atexit to this shared object.
1416 llvm::Constant *handle =
1417 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1418
1419 llvm::Value *args[] = {
1420 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1421 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1422 handle
1423 };
John McCallbd7370a2013-02-28 19:01:20 +00001424 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001425}
1426
1427/// Register a global destructor as best as we know how.
1428void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001429 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001430 llvm::Constant *dtor,
1431 llvm::Constant *addr) {
1432 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001433 if (CGM.getCodeGenOpts().CXAAtExit)
1434 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1435
1436 if (D.getTLSKind())
1437 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001438
1439 // In Apple kexts, we want to add a global destructor entry.
1440 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001441 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001442 // Generate a global destructor entry.
1443 return CGM.AddCXXDtorEntry(dtor, addr);
1444 }
1445
David Blaikiec7971a92013-08-27 23:57:18 +00001446 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCall20bb1752012-05-01 06:13:13 +00001447}
Richard Smithb80a16e2013-04-19 16:42:07 +00001448
1449/// Get the appropriate linkage for the wrapper function. This is essentially
1450/// the weak form of the variable's linkage; every translation unit which wneeds
1451/// the wrapper emits a copy, and we want the linker to merge them.
1452static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1453 llvm::GlobalValue::LinkageTypes VarLinkage) {
1454 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1455 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1456 // For internal linkage variables, we don't need an external or weak wrapper.
1457 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1458 return VarLinkage;
1459 return llvm::GlobalValue::WeakODRLinkage;
1460}
1461
1462llvm::Function *
1463ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1464 llvm::GlobalVariable *Var) {
1465 // Mangle the name for the thread_local wrapper function.
1466 SmallString<256> WrapperName;
1467 {
1468 llvm::raw_svector_ostream Out(WrapperName);
1469 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1470 Out.flush();
1471 }
1472
1473 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1474 return cast<llvm::Function>(V);
1475
1476 llvm::Type *RetTy = Var->getType();
1477 if (VD->getType()->isReferenceType())
1478 RetTy = RetTy->getPointerElementType();
1479
1480 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1481 llvm::Function *Wrapper = llvm::Function::Create(
1482 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1483 &CGM.getModule());
1484 // Always resolve references to the wrapper at link time.
1485 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1486 return Wrapper;
1487}
1488
1489void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1490 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1491 llvm::Function *InitFunc) {
1492 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1493 const VarDecl *VD = Decls[I].first;
1494 llvm::GlobalVariable *Var = Decls[I].second;
1495
1496 // Mangle the name for the thread_local initialization function.
1497 SmallString<256> InitFnName;
1498 {
1499 llvm::raw_svector_ostream Out(InitFnName);
1500 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1501 Out.flush();
1502 }
1503
1504 // If we have a definition for the variable, emit the initialization
1505 // function as an alias to the global Init function (if any). Otherwise,
1506 // produce a declaration of the initialization function.
1507 llvm::GlobalValue *Init = 0;
1508 bool InitIsInitFunc = false;
1509 if (VD->hasDefinition()) {
1510 InitIsInitFunc = true;
1511 if (InitFunc)
1512 Init =
1513 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1514 InitFnName.str(), InitFunc, &CGM.getModule());
1515 } else {
1516 // Emit a weak global function referring to the initialization function.
1517 // This function will not exist if the TU defining the thread_local
1518 // variable in question does not need any dynamic initialization for
1519 // its thread_local variables.
1520 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1521 Init = llvm::Function::Create(
1522 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1523 &CGM.getModule());
1524 }
1525
1526 if (Init)
1527 Init->setVisibility(Var->getVisibility());
1528
1529 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1530 llvm::LLVMContext &Context = CGM.getModule().getContext();
1531 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1532 CGBuilderTy Builder(Entry);
1533 if (InitIsInitFunc) {
1534 if (Init)
1535 Builder.CreateCall(Init);
1536 } else {
1537 // Don't know whether we have an init function. Call it if it exists.
1538 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1539 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1540 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1541 Builder.CreateCondBr(Have, InitBB, ExitBB);
1542
1543 Builder.SetInsertPoint(InitBB);
1544 Builder.CreateCall(Init);
1545 Builder.CreateBr(ExitBB);
1546
1547 Builder.SetInsertPoint(ExitBB);
1548 }
1549
1550 // For a reference, the result of the wrapper function is a pointer to
1551 // the referenced object.
1552 llvm::Value *Val = Var;
1553 if (VD->getType()->isReferenceType()) {
1554 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1555 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1556 Val = LI;
1557 }
1558
1559 Builder.CreateRet(Val);
1560 }
1561}
1562
1563LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1564 const DeclRefExpr *DRE) {
1565 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1566 QualType T = VD->getType();
1567 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1568 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1569 llvm::Function *Wrapper =
1570 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1571
1572 Val = CGF.Builder.CreateCall(Wrapper);
1573
1574 LValue LV;
1575 if (VD->getType()->isReferenceType())
1576 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1577 else
1578 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1579 CGF.getContext().getDeclAlign(VD));
1580 // FIXME: need setObjCGCLValueClass?
1581 return LV;
1582}
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001583
1584/// Return whether the given global decl needs a VTT parameter, which it does
1585/// if it's a base constructor or destructor with virtual bases.
1586bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1587 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1588
1589 // We don't have any virtual bases, just return early.
1590 if (!MD->getParent()->getNumVBases())
1591 return false;
1592
1593 // Check if we have a base constructor.
1594 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1595 return true;
1596
1597 // Check if we have a base destructor.
1598 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1599 return true;
1600
1601 return false;
1602}