blob: ecf5d577981a7ea61a450ed28c810f6918c62c0f [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall7a9aac22010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000031
32using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000034
35namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000037 /// VTables - All the vtables which have been defined.
38 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
39
John McCall475999d2010-08-22 00:05:51 +000040protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000041 bool UseARMMethodPtrABI;
42 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000043
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000044 ItaniumMangleContext &getMangleContext() {
45 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
46 }
47
Charles Davis4e786dd2010-05-25 19:52:27 +000048public:
Mark Seabornedf0d382013-07-24 16:25:13 +000049 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
50 bool UseARMMethodPtrABI = false,
51 bool UseARMGuardVarABI = false) :
52 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
53 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000054
Timur Iskhodzhanov8fe501d2013-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 McCall614dbdc2010-08-22 21:01:12 +000069 bool isZeroInitializable(const MemberPointerType *MPT);
John McCall84fa5102010-08-22 04:16:24 +000070
Chris Lattnera5f58b02011-07-09 17:41:47 +000071 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall7a9aac22010-08-23 01:21:21 +000072
John McCall475999d2010-08-22 00:05:51 +000073 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74 llvm::Value *&This,
75 llvm::Value *MemFnPtr,
76 const MemberPointerType *MPT);
John McCalla8bbb822010-08-22 03:04:22 +000077
John McCallc134eb52010-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 McCall7a9aac22010-08-23 01:21:21 +000083 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
84 const CastExpr *E,
85 llvm::Value *Src);
John McCallc62bb392012-02-15 01:22:51 +000086 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
87 llvm::Constant *Src);
John McCall84fa5102010-08-22 04:16:24 +000088
John McCall7a9aac22010-08-23 01:21:21 +000089 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCall84fa5102010-08-22 04:16:24 +000090
John McCall2979fe02011-04-12 00:42:48 +000091 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCallf3a88602011-02-03 08:15:49 +000092 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
93 CharUnits offset);
Richard Smithdafff942012-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 McCall1c456c82010-08-22 06:43:33 +000097
John McCall7a9aac22010-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 McCall131d97d2010-08-22 08:30:07 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
105 llvm::Value *Addr,
106 const MemberPointerType *MPT);
John McCall5d865c322010-08-31 07:33:07 +0000107
John McCall82fb8922012-09-25 10:10:39 +0000108 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
109 llvm::Value *ptr,
110 QualType type);
111
Reid Klecknerd8cbeec2013-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 McCall5d865c322010-08-31 07:33:07 +0000117 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
118 CXXCtorType T,
119 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000120 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000121
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000122 void EmitCXXConstructors(const CXXConstructorDecl *D);
123
John McCall5d865c322010-08-31 07:33:07 +0000124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
125 CXXDtorType T,
126 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000128
Reid Klecknere7de47e2013-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 McCall5d865c322010-08-31 07:33:07 +0000139 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
140 QualType &ResTy,
141 FunctionArgList &Params);
142
143 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall8ed55a52010-09-02 09:58:18 +0000144
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000145 void EmitConstructorCall(CodeGenFunction &CGF,
146 const CXXConstructorDecl *D, CXXCtorType Type,
147 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000148 llvm::Value *This,
149 CallExpr::const_arg_iterator ArgBeg,
150 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000151
Timur Iskhodzhanov8b5987e2013-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 Iskhodzhanov88fd4392013-08-21 06:25:03 +0000166 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
167 llvm::Value *This, llvm::Type *Ty);
168
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000169 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
170 const CXXDestructorDecl *Dtor,
171 CXXDtorType DtorType, SourceLocation CallLoc,
172 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000173
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000174 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000175
Joao Matos2ce88ef2012-07-17 17:10:11 +0000176 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikieeb7d5982012-10-16 22:56:05 +0000177 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000178
John McCallb91cd662012-05-01 05:23:51 +0000179 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall8ed55a52010-09-02 09:58:18 +0000180 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
181 llvm::Value *NewPtr,
182 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000183 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +0000184 QualType ElementType);
John McCallb91cd662012-05-01 05:23:51 +0000185 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
186 llvm::Value *allocPtr,
187 CharUnits cookieSize);
John McCall68ff0372010-09-08 01:44:27 +0000188
John McCallcdf7ef52010-11-06 09:44:32 +0000189 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000190 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smithdbf74ba2013-04-14 23:01:42 +0000191 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
192 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000193
194 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
195 llvm::GlobalVariable *Var);
196 void EmitThreadLocalInitFuncs(
197 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
198 llvm::Function *InitFunc);
199 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
200 const DeclRefExpr *DRE);
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000201
202 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis4e786dd2010-05-25 19:52:27 +0000203};
John McCall86353412010-08-21 22:46:04 +0000204
205class ARMCXXABI : public ItaniumCXXABI {
206public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000207 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
208 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
209 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000210
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000211 bool HasThisReturn(GlobalDecl GD) const {
212 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
213 isa<CXXDestructorDecl>(GD.getDecl()) &&
214 GD.getDtorType() != Dtor_Deleting));
215 }
John McCall5d865c322010-08-31 07:33:07 +0000216
217 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
218
John McCallb91cd662012-05-01 05:23:51 +0000219 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall8ed55a52010-09-02 09:58:18 +0000220 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
221 llvm::Value *NewPtr,
222 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000223 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +0000224 QualType ElementType);
John McCallb91cd662012-05-01 05:23:51 +0000225 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
226 CharUnits cookieSize);
John McCall86353412010-08-21 22:46:04 +0000227};
Charles Davis4e786dd2010-05-25 19:52:27 +0000228}
229
Charles Davis53c59df2010-08-16 03:33:14 +0000230CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000231 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000232 // For IR-generation purposes, there's no significant difference
233 // between the ARM and iOS ABIs.
234 case TargetCXXABI::GenericARM:
235 case TargetCXXABI::iOS:
236 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000237
Tim Northover9bb857a2013-01-31 12:13:10 +0000238 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
239 // include the other 32-bit ARM oddities: constructor/destructor return values
240 // and array cookies.
241 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000242 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
243 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000244
John McCall57625922013-01-25 23:36:14 +0000245 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000246 if (CGM.getContext().getTargetInfo().getTriple().getArch()
247 == llvm::Triple::le32) {
248 // For PNaCl, use ARM-style method pointers so that PNaCl code
249 // does not assume anything about the alignment of function
250 // pointers.
251 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
252 /* UseARMGuardVarABI = */ false);
253 }
John McCall57625922013-01-25 23:36:14 +0000254 return new ItaniumCXXABI(CGM);
255
256 case TargetCXXABI::Microsoft:
257 llvm_unreachable("Microsoft ABI is not Itanium-based");
258 }
259 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000260}
261
Chris Lattnera5f58b02011-07-09 17:41:47 +0000262llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000263ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
264 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000265 return CGM.PtrDiffTy;
266 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000267}
268
John McCalld9c6c0b2010-08-22 00:59:17 +0000269/// In the Itanium and ARM ABIs, method pointers have the form:
270/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
271///
272/// In the Itanium ABI:
273/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
274/// - the this-adjustment is (memptr.adj)
275/// - the virtual offset is (memptr.ptr - 1)
276///
277/// In the ARM ABI:
278/// - method pointers are virtual if (memptr.adj & 1) is nonzero
279/// - the this-adjustment is (memptr.adj >> 1)
280/// - the virtual offset is (memptr.ptr)
281/// ARM uses 'adj' for the virtual flag because Thumb functions
282/// may be only single-byte aligned.
283///
284/// If the member is virtual, the adjusted 'this' pointer points
285/// to a vtable pointer from which the virtual offset is applied.
286///
287/// If the member is non-virtual, memptr.ptr is the address of
288/// the function to call.
John McCall475999d2010-08-22 00:05:51 +0000289llvm::Value *
290ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
291 llvm::Value *&This,
292 llvm::Value *MemFnPtr,
293 const MemberPointerType *MPT) {
294 CGBuilderTy &Builder = CGF.Builder;
295
296 const FunctionProtoType *FPT =
297 MPT->getPointeeType()->getAs<FunctionProtoType>();
298 const CXXRecordDecl *RD =
299 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
300
Chris Lattner2192fe52011-07-18 04:24:23 +0000301 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000302 CGM.getTypes().GetFunctionType(
303 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000304
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000305 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000306
John McCalld9c6c0b2010-08-22 00:59:17 +0000307 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
308 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
309 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
310
John McCalla1dee5302010-08-22 10:59:02 +0000311 // Extract memptr.adj, which is in the second field.
312 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000313
314 // Compute the true adjustment.
315 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000316 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000317 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000318
319 // Apply the adjustment and cast back to the original struct type
320 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000321 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
322 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
323 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000324
325 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000326 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000327
328 // If the LSB in the function pointer is 1, the function pointer points to
329 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000330 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000331 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000332 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
333 else
334 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
335 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000336 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
337
338 // In the virtual path, the adjustment left 'This' pointing to the
339 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000340 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000341 CGF.EmitBlock(FnVirtual);
342
343 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000344 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall475999d2010-08-22 00:05:51 +0000345 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000346 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall475999d2010-08-22 00:05:51 +0000347
348 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000349 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000350 if (!UseARMMethodPtrABI)
351 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000352 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000353
354 // Load the virtual function to call.
355 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000356 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000357 CGF.EmitBranch(FnEnd);
358
359 // In the non-virtual path, the function pointer is actually a
360 // function pointer.
361 CGF.EmitBlock(FnNonVirtual);
362 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000363 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000364
365 // We're done.
366 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000367 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000368 Callee->addIncoming(VirtualFn, FnVirtual);
369 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
370 return Callee;
371}
John McCalla8bbb822010-08-22 03:04:22 +0000372
John McCallc134eb52010-08-31 21:07:20 +0000373/// Compute an l-value by applying the given pointer-to-member to a
374/// base object.
375llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
376 llvm::Value *Base,
377 llvm::Value *MemPtr,
378 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000379 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000380
381 CGBuilderTy &Builder = CGF.Builder;
382
Micah Villmowea2fea22012-10-25 15:39:14 +0000383 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000384
385 // Cast to char*.
386 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
387
388 // Apply the offset, which we assume is non-null.
389 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
390
391 // Cast the address to the appropriate pointer type, adopting the
392 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000393 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000394 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000395 return Builder.CreateBitCast(Addr, PType);
396}
397
John McCallc62bb392012-02-15 01:22:51 +0000398/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
399/// conversion.
400///
401/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000402///
403/// Obligatory offset/adjustment diagram:
404/// <-- offset --> <-- adjustment -->
405/// |--------------------------|----------------------|--------------------|
406/// ^Derived address point ^Base address point ^Member address point
407///
408/// So when converting a base member pointer to a derived member pointer,
409/// we add the offset to the adjustment because the address point has
410/// decreased; and conversely, when converting a derived MP to a base MP
411/// we subtract the offset from the adjustment because the address point
412/// has increased.
413///
414/// The standard forbids (at compile time) conversion to and from
415/// virtual bases, which is why we don't have to consider them here.
416///
417/// The standard forbids (at run time) casting a derived MP to a base
418/// MP when the derived MP does not point to a member of the base.
419/// This is why -1 is a reasonable choice for null data member
420/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000421llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000422ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
423 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000424 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000425 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000426 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
427 E->getCastKind() == CK_ReinterpretMemberPointer);
428
429 // Under Itanium, reinterprets don't require any additional processing.
430 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
431
432 // Use constant emission if we can.
433 if (isa<llvm::Constant>(src))
434 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
435
436 llvm::Constant *adj = getMemberPointerAdjustment(E);
437 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000438
439 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000440 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000441
John McCallc62bb392012-02-15 01:22:51 +0000442 const MemberPointerType *destTy =
443 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000444
John McCall7a9aac22010-08-23 01:21:21 +0000445 // For member data pointers, this is just a matter of adding the
446 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000447 if (destTy->isMemberDataPointer()) {
448 llvm::Value *dst;
449 if (isDerivedToBase)
450 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000451 else
John McCallc62bb392012-02-15 01:22:51 +0000452 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000453
454 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000455 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
456 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
457 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000458 }
459
John McCalla1dee5302010-08-22 10:59:02 +0000460 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000461 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000462 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
463 offset <<= 1;
464 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000465 }
466
John McCallc62bb392012-02-15 01:22:51 +0000467 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
468 llvm::Value *dstAdj;
469 if (isDerivedToBase)
470 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000471 else
John McCallc62bb392012-02-15 01:22:51 +0000472 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000473
John McCallc62bb392012-02-15 01:22:51 +0000474 return Builder.CreateInsertValue(src, dstAdj, 1);
475}
476
477llvm::Constant *
478ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
479 llvm::Constant *src) {
480 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
481 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
482 E->getCastKind() == CK_ReinterpretMemberPointer);
483
484 // Under Itanium, reinterprets don't require any additional processing.
485 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
486
487 // If the adjustment is trivial, we don't need to do anything.
488 llvm::Constant *adj = getMemberPointerAdjustment(E);
489 if (!adj) return src;
490
491 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
492
493 const MemberPointerType *destTy =
494 E->getType()->castAs<MemberPointerType>();
495
496 // For member data pointers, this is just a matter of adding the
497 // offset if the source is non-null.
498 if (destTy->isMemberDataPointer()) {
499 // null maps to null.
500 if (src->isAllOnesValue()) return src;
501
502 if (isDerivedToBase)
503 return llvm::ConstantExpr::getNSWSub(src, adj);
504 else
505 return llvm::ConstantExpr::getNSWAdd(src, adj);
506 }
507
508 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000509 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000510 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
511 offset <<= 1;
512 adj = llvm::ConstantInt::get(adj->getType(), offset);
513 }
514
515 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
516 llvm::Constant *dstAdj;
517 if (isDerivedToBase)
518 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
519 else
520 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
521
522 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000523}
John McCall84fa5102010-08-22 04:16:24 +0000524
525llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000526ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000527 // Itanium C++ ABI 2.3:
528 // A NULL pointer is represented as -1.
529 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000530 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000531
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000532 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000533 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000534 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000535}
536
John McCallf3a88602011-02-03 08:15:49 +0000537llvm::Constant *
538ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
539 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000540 // Itanium C++ ABI 2.3:
541 // A pointer to data member is an offset from the base address of
542 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000543 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000544}
545
John McCall2979fe02011-04-12 00:42:48 +0000546llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000547 return BuildMemberPointer(MD, CharUnits::Zero());
548}
549
550llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
551 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000552 assert(MD->isInstance() && "Member function must not be static!");
553 MD = MD->getCanonicalDecl();
554
555 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000556
557 // Get the function pointer (or index if this is a virtual function).
558 llvm::Constant *MemPtr[2];
559 if (MD->isVirtual()) {
Peter Collingbournea8341662011-09-26 01:56:30 +0000560 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000561
Ken Dyckdf016282011-04-09 01:30:02 +0000562 const ASTContext &Context = getContext();
563 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000564 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000565 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000566
Mark Seabornedf0d382013-07-24 16:25:13 +0000567 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000568 // ARM C++ ABI 3.2.1:
569 // This ABI specifies that adj contains twice the this
570 // adjustment, plus 1 if the member function is virtual. The
571 // least significant bit of adj then makes exactly the same
572 // discrimination as the least significant bit of ptr does for
573 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000574 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
575 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000576 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000577 } else {
578 // Itanium C++ ABI 2.3:
579 // For a virtual function, [the pointer field] is 1 plus the
580 // virtual table offset (in bytes) of the function,
581 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000582 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
583 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000584 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000585 }
586 } else {
John McCall2979fe02011-04-12 00:42:48 +0000587 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000588 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000589 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000590 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000591 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000592 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000593 } else {
John McCall2979fe02011-04-12 00:42:48 +0000594 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
595 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000596 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000597 }
John McCall2979fe02011-04-12 00:42:48 +0000598 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000599
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000600 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000601 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
602 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000603 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000604 }
John McCall1c456c82010-08-22 06:43:33 +0000605
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000606 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000607}
608
Richard Smithdafff942012-01-14 04:30:29 +0000609llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
610 QualType MPType) {
611 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
612 const ValueDecl *MPD = MP.getMemberPointerDecl();
613 if (!MPD)
614 return EmitNullMemberPointer(MPT);
615
Reid Kleckner452abac2013-05-09 21:01:17 +0000616 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000617
618 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
619 return BuildMemberPointer(MD, ThisAdjustment);
620
621 CharUnits FieldOffset =
622 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
623 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
624}
625
John McCall131d97d2010-08-22 08:30:07 +0000626/// The comparison algorithm is pretty easy: the member pointers are
627/// the same if they're either bitwise identical *or* both null.
628///
629/// ARM is different here only because null-ness is more complicated.
630llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000631ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
632 llvm::Value *L,
633 llvm::Value *R,
634 const MemberPointerType *MPT,
635 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000636 CGBuilderTy &Builder = CGF.Builder;
637
John McCall131d97d2010-08-22 08:30:07 +0000638 llvm::ICmpInst::Predicate Eq;
639 llvm::Instruction::BinaryOps And, Or;
640 if (Inequality) {
641 Eq = llvm::ICmpInst::ICMP_NE;
642 And = llvm::Instruction::Or;
643 Or = llvm::Instruction::And;
644 } else {
645 Eq = llvm::ICmpInst::ICMP_EQ;
646 And = llvm::Instruction::And;
647 Or = llvm::Instruction::Or;
648 }
649
John McCall7a9aac22010-08-23 01:21:21 +0000650 // Member data pointers are easy because there's a unique null
651 // value, so it just comes down to bitwise equality.
652 if (MPT->isMemberDataPointer())
653 return Builder.CreateICmp(Eq, L, R);
654
655 // For member function pointers, the tautologies are more complex.
656 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000657 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000658 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000659 // (L == R) <==> (L.ptr == R.ptr &&
660 // (L.adj == R.adj ||
661 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000662 // The inequality tautologies have exactly the same structure, except
663 // applying De Morgan's laws.
664
665 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
666 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
667
John McCall131d97d2010-08-22 08:30:07 +0000668 // This condition tests whether L.ptr == R.ptr. This must always be
669 // true for equality to hold.
670 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
671
672 // This condition, together with the assumption that L.ptr == R.ptr,
673 // tests whether the pointers are both null. ARM imposes an extra
674 // condition.
675 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
676 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
677
678 // This condition tests whether L.adj == R.adj. If this isn't
679 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000680 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
681 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000682 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
683
684 // Null member function pointers on ARM clear the low bit of Adj,
685 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000686 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000687 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
688
689 // Compute (l.adj | r.adj) & 1 and test it against zero.
690 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
691 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
692 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
693 "cmp.or.adj");
694 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
695 }
696
697 // Tie together all our conditions.
698 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
699 Result = Builder.CreateBinOp(And, PtrEq, Result,
700 Inequality ? "memptr.ne" : "memptr.eq");
701 return Result;
702}
703
704llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000705ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
706 llvm::Value *MemPtr,
707 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000708 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000709
710 /// For member data pointers, this is just a check against -1.
711 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000712 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000713 llvm::Value *NegativeOne =
714 llvm::Constant::getAllOnesValue(MemPtr->getType());
715 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
716 }
John McCall131d97d2010-08-22 08:30:07 +0000717
Daniel Dunbar914bc412011-04-19 23:10:47 +0000718 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000719 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000720
721 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
722 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
723
Daniel Dunbar914bc412011-04-19 23:10:47 +0000724 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
725 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000726 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000727 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000728 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000729 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000730 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
731 "memptr.isvirtual");
732 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000733 }
734
735 return Result;
736}
John McCall1c456c82010-08-22 06:43:33 +0000737
John McCall614dbdc2010-08-22 21:01:12 +0000738/// The Itanium ABI requires non-zero initialization only for data
739/// member pointers, for which '0' is a valid offset.
740bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
741 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000742}
John McCall5d865c322010-08-31 07:33:07 +0000743
John McCall82fb8922012-09-25 10:10:39 +0000744/// The Itanium ABI always places an offset to the complete object
745/// at entry -2 in the vtable.
746llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
747 llvm::Value *ptr,
748 QualType type) {
749 // Grab the vtable pointer as an intptr_t*.
750 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
751
752 // Track back to entry -2 and pull out the offset there.
753 llvm::Value *offsetPtr =
754 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
755 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
756 offset->setAlignment(CGF.PointerAlignInBytes);
757
758 // Apply the offset.
759 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
760 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
761}
762
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000763llvm::Value *
764ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
765 llvm::Value *This,
766 const CXXRecordDecl *ClassDecl,
767 const CXXRecordDecl *BaseClassDecl) {
768 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
769 CharUnits VBaseOffsetOffset =
770 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
771
772 llvm::Value *VBaseOffsetPtr =
773 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
774 "vbase.offset.ptr");
775 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
776 CGM.PtrDiffTy->getPointerTo());
777
778 llvm::Value *VBaseOffset =
779 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
780
781 return VBaseOffset;
782}
783
John McCall5d865c322010-08-31 07:33:07 +0000784/// The generic ABI passes 'this', plus a VTT if it's initializing a
785/// base subobject.
786void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
787 CXXCtorType Type,
788 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000789 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000790 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000791
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000792 // 'this' parameter is already there, as well as 'this' return if
793 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000794
795 // Check if we need to add a VTT parameter (which has type void **).
796 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
797 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
798}
799
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000800void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
801 // Just make sure we're in sync with TargetCXXABI.
802 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
803
804 // The constructor used for constructing this as a complete class;
805 // constucts the virtual bases, then calls the base constructor.
806 if (!D->getParent()->isAbstract()) {
807 // We don't need to emit the complete ctor if the class is abstract.
808 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
809 }
810
811 // The constructor used for constructing this as a base class;
812 // ignores virtual bases.
813 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
814}
815
John McCall5d865c322010-08-31 07:33:07 +0000816/// The generic ABI passes 'this', plus a VTT if it's destroying a
817/// base subobject.
818void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
819 CXXDtorType Type,
820 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000821 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000822 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000823
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000824 // 'this' parameter is already there, as well as 'this' return if
825 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000826
827 // Check if we need to add a VTT parameter (which has type void **).
828 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
829 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
830}
831
Reid Klecknere7de47e2013-07-22 13:51:44 +0000832void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
833 // The destructor in a virtual table is always a 'deleting'
834 // destructor, which calls the complete destructor and then uses the
835 // appropriate operator delete.
836 if (D->isVirtual())
837 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
838
839 // The destructor used for destructing this as a most-derived class;
840 // call the base destructor and then destructs any virtual bases.
841 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
842
843 // The destructor used for destructing this as a base class; ignores
844 // virtual bases.
845 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
846}
847
John McCall5d865c322010-08-31 07:33:07 +0000848void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
849 QualType &ResTy,
850 FunctionArgList &Params) {
851 /// Create the 'this' variable.
852 BuildThisParam(CGF, Params);
853
854 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
855 assert(MD->isInstance());
856
857 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000858 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000859 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000860
861 // FIXME: avoid the fake decl
862 QualType T = Context.getPointerType(Context.VoidPtrTy);
863 ImplicitParamDecl *VTTDecl
864 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
865 &Context.Idents.get("vtt"), T);
John McCalla738c252011-03-09 04:27:21 +0000866 Params.push_back(VTTDecl);
John McCall5d865c322010-08-31 07:33:07 +0000867 getVTTDecl(CGF) = VTTDecl;
868 }
869}
870
John McCall5d865c322010-08-31 07:33:07 +0000871void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
872 /// Initialize the 'this' slot.
873 EmitThisParam(CGF);
874
875 /// Initialize the 'vtt' slot if needed.
876 if (getVTTDecl(CGF)) {
877 getVTTValue(CGF)
878 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
879 "vtt");
880 }
John McCall5d865c322010-08-31 07:33:07 +0000881
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000882 /// If this is a function that the ABI specifies returns 'this', initialize
883 /// the return slot to 'this' at the start of the function.
884 ///
885 /// Unlike the setting of return types, this is done within the ABI
886 /// implementation instead of by clients of CGCXXABI because:
887 /// 1) getThisValue is currently protected
888 /// 2) in theory, an ABI could implement 'this' returns some other way;
889 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000890 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000891 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000892}
893
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000894void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000895 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000896 CXXCtorType Type,
897 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000898 llvm::Value *This,
899 CallExpr::const_arg_iterator ArgBeg,
900 CallExpr::const_arg_iterator ArgEnd) {
901 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
902 Delegating);
903 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
904 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
905
906 // FIXME: Provide a source location here.
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000907 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
908 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000909}
910
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000911void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
912 const CXXRecordDecl *RD) {
913 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
914 if (VTable->hasInitializer())
915 return;
916
917 VTableContext &VTContext = CGM.getVTableContext();
918 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
919 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
920
921 // Create and set the initializer.
922 llvm::Constant *Init = CGVT.CreateVTableInitializer(
923 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
924 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
925 VTable->setInitializer(Init);
926
927 // Set the correct linkage.
928 VTable->setLinkage(Linkage);
929
930 // Set the right visibility.
931 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
932
933 // If this is the magic class __cxxabiv1::__fundamental_type_info,
934 // we will emit the typeinfo for the fundamental types. This is the
935 // same behaviour as GCC.
936 const DeclContext *DC = RD->getDeclContext();
937 if (RD->getIdentifier() &&
938 RD->getIdentifier()->isStr("__fundamental_type_info") &&
939 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
940 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
941 DC->getParent()->isTranslationUnit())
942 CGM.EmitFundamentalRTTIDescriptors();
943}
944
945llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
946 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
947 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
948 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
949 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
950
951 llvm::Value *VTableAddressPoint;
952 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
953 // Get the secondary vpointer index.
954 uint64_t VirtualPointerIndex =
955 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
956
957 /// Load the VTT.
958 llvm::Value *VTT = CGF.LoadCXXVTT();
959 if (VirtualPointerIndex)
960 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
961
962 // And load the address point from the VTT.
963 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
964 } else {
965 llvm::Constant *VTable =
966 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
967 uint64_t AddressPoint = CGM.getVTableContext().getVTableLayout(VTableClass)
968 .getAddressPoint(Base);
969 VTableAddressPoint =
970 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
971 }
972
973 return VTableAddressPoint;
974}
975
976llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
977 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
978 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
979
980 // Find the appropriate vtable within the vtable group.
981 uint64_t AddressPoint =
982 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
983 llvm::Value *Indices[] = {
984 llvm::ConstantInt::get(CGM.Int64Ty, 0),
985 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
986 };
987
988 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
989}
990
991llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
992 CharUnits VPtrOffset) {
993 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
994
995 llvm::GlobalVariable *&VTable = VTables[RD];
996 if (VTable)
997 return VTable;
998
999 // Queue up this v-table for possible deferred emission.
1000 CGM.addDeferredVTable(RD);
1001
1002 SmallString<256> OutName;
1003 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001004 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001005 Out.flush();
1006 StringRef Name = OutName.str();
1007
1008 VTableContext &VTContext = CGM.getVTableContext();
1009 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1010 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1011
1012 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1013 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1014 VTable->setUnnamedAddr(true);
1015 return VTable;
1016}
1017
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001018llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1019 GlobalDecl GD,
1020 llvm::Value *This,
1021 llvm::Type *Ty) {
1022 GD = GD.getCanonicalDecl();
1023 Ty = Ty->getPointerTo()->getPointerTo();
1024 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1025
1026 uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(GD);
1027 llvm::Value *VFuncPtr =
1028 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1029 return CGF.Builder.CreateLoad(VFuncPtr);
1030}
1031
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001032void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1033 const CXXDestructorDecl *Dtor,
1034 CXXDtorType DtorType,
1035 SourceLocation CallLoc,
1036 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001037 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1038
1039 const CGFunctionInfo *FInfo
1040 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1041 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001042 llvm::Value *Callee =
1043 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001044
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001045 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1046 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001047}
1048
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001049void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001050 CodeGenVTables &VTables = CGM.getVTables();
1051 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001052 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001053}
1054
John McCall5d865c322010-08-31 07:33:07 +00001055void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1056 RValue RV, QualType ResultType) {
1057 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1058 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1059
1060 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001061 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001062 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1063 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1064 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1065}
John McCall8ed55a52010-09-02 09:58:18 +00001066
1067/************************** Array allocation cookies **************************/
1068
John McCallb91cd662012-05-01 05:23:51 +00001069CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1070 // The array cookie is a size_t; pad that up to the element alignment.
1071 // The cookie is actually right-justified in that space.
1072 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1073 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001074}
1075
1076llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1077 llvm::Value *NewPtr,
1078 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001079 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001080 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001081 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001082
Micah Villmowea2fea22012-10-25 15:39:14 +00001083 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001084
John McCall9bca9232010-09-02 10:25:57 +00001085 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001086 QualType SizeTy = Ctx.getSizeType();
1087 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1088
1089 // The size of the cookie.
1090 CharUnits CookieSize =
1091 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001092 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001093
1094 // Compute an offset to the cookie.
1095 llvm::Value *CookiePtr = NewPtr;
1096 CharUnits CookieOffset = CookieSize - SizeSize;
1097 if (!CookieOffset.isZero())
1098 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1099 CookieOffset.getQuantity());
1100
1101 // Write the number of elements into the appropriate slot.
1102 llvm::Value *NumElementsPtr
1103 = CGF.Builder.CreateBitCast(CookiePtr,
1104 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1105 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1106
1107 // Finally, compute a pointer to the actual data buffer by skipping
1108 // over the cookie completely.
1109 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1110 CookieSize.getQuantity());
1111}
1112
John McCallb91cd662012-05-01 05:23:51 +00001113llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1114 llvm::Value *allocPtr,
1115 CharUnits cookieSize) {
1116 // The element size is right-justified in the cookie.
1117 llvm::Value *numElementsPtr = allocPtr;
1118 CharUnits numElementsOffset =
1119 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1120 if (!numElementsOffset.isZero())
1121 numElementsPtr =
1122 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1123 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001124
Micah Villmowea2fea22012-10-25 15:39:14 +00001125 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001126 numElementsPtr =
1127 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1128 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001129}
1130
John McCallb91cd662012-05-01 05:23:51 +00001131CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001132 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001133 // struct array_cookie {
1134 // std::size_t element_size; // element_size != 0
1135 // std::size_t element_count;
1136 // };
John McCallc19c7062013-01-25 23:36:19 +00001137 // But the base ABI doesn't give anything an alignment greater than
1138 // 8, so we can dismiss this as typical ABI-author blindness to
1139 // actual language complexity and round up to the element alignment.
1140 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1141 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001142}
1143
1144llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001145 llvm::Value *newPtr,
1146 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001147 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001148 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001149 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001150
John McCallc19c7062013-01-25 23:36:19 +00001151 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1152 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001153
1154 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001155 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001156
1157 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001158 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1159 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1160 getContext().getTypeSizeInChars(elementType).getQuantity());
1161 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001162
1163 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001164 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1165 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001166
1167 // Finally, compute a pointer to the actual data buffer by skipping
1168 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001169 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1170 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1171 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001172}
1173
John McCallb91cd662012-05-01 05:23:51 +00001174llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1175 llvm::Value *allocPtr,
1176 CharUnits cookieSize) {
1177 // The number of elements is at offset sizeof(size_t) relative to
1178 // the allocated pointer.
1179 llvm::Value *numElementsPtr
1180 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001181
Micah Villmowea2fea22012-10-25 15:39:14 +00001182 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001183 numElementsPtr =
1184 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1185 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001186}
1187
John McCall68ff0372010-09-08 01:44:27 +00001188/*********************** Static local initialization **************************/
1189
1190static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001191 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001192 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001193 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001194 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001195 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001196 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001197 llvm::AttributeSet::get(CGM.getLLVMContext(),
1198 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001199 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001200}
1201
1202static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001203 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001204 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001205 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001206 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001207 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001208 llvm::AttributeSet::get(CGM.getLLVMContext(),
1209 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001210 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001211}
1212
1213static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001214 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001215 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001216 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001217 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001218 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001219 llvm::AttributeSet::get(CGM.getLLVMContext(),
1220 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001221 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001222}
1223
1224namespace {
1225 struct CallGuardAbort : EHScopeStack::Cleanup {
1226 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001227 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001228
John McCall30317fd2011-07-12 20:27:29 +00001229 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall882987f2013-02-28 19:01:20 +00001230 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1231 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001232 }
1233 };
1234}
1235
1236/// The ARM code here follows the Itanium code closely enough that we
1237/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001238void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1239 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001240 llvm::GlobalVariable *var,
1241 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001242 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001243
Richard Smithdbf74ba2013-04-14 23:01:42 +00001244 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001245 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001246 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1247 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001248
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001249 // If we have a global variable with internal linkage and thread-safe statics
1250 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001251 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1252
1253 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001254 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001255 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001256 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001257 // Guard variables are 64 bits in the generic ABI and size width on ARM
1258 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001259 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001260 }
John McCallb88a5662012-03-30 21:00:39 +00001261 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001262
John McCallb88a5662012-03-30 21:00:39 +00001263 // Create the guard variable if we don't already have it (as we
1264 // might if we're double-emitting this function body).
1265 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1266 if (!guard) {
1267 // Mangle the name for the guard.
1268 SmallString<256> guardName;
1269 {
1270 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001271 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001272 out.flush();
1273 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001274
John McCallb88a5662012-03-30 21:00:39 +00001275 // Create the guard variable with a zero-initializer.
1276 // Just absorb linkage and visibility from the guarded variable.
1277 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1278 false, var->getLinkage(),
1279 llvm::ConstantInt::get(guardTy, 0),
1280 guardName.str());
1281 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001282 // If the variable is thread-local, so is its guard variable.
1283 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001284
1285 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1286 }
John McCall87590e62012-03-30 07:09:50 +00001287
John McCall68ff0372010-09-08 01:44:27 +00001288 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001289 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001290
1291 // ARM C++ ABI 3.2.3.1:
1292 // To support the potential use of initialization guard variables
1293 // as semaphores that are the target of ARM SWP and LDREX/STREX
1294 // synchronizing instructions we define a static initialization
1295 // guard variable to be a 4-byte aligned, 4- byte word with the
1296 // following inline access protocol.
1297 // #define INITIALIZED 1
1298 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1299 // if (__cxa_guard_acquire(&obj_guard))
1300 // ...
1301 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001302 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001303 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001304 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1305 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001306 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001307
1308 // Itanium C++ ABI 3.3.2:
1309 // The following is pseudo-code showing how these functions can be used:
1310 // if (obj_guard.first_byte == 0) {
1311 // if ( __cxa_guard_acquire (&obj_guard) ) {
1312 // try {
1313 // ... initialize the object ...;
1314 // } catch (...) {
1315 // __cxa_guard_abort (&obj_guard);
1316 // throw;
1317 // }
1318 // ... queue object destructor with __cxa_atexit() ...;
1319 // __cxa_guard_release (&obj_guard);
1320 // }
1321 // }
1322 } else {
1323 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001324 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001325 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001326 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001327
Eli Friedman84d28122011-09-13 22:21:56 +00001328 // Itanium ABI:
1329 // An implementation supporting thread-safety on multiprocessor
1330 // systems must also guarantee that references to the initialized
1331 // object do not occur before the load of the initialization flag.
1332 //
1333 // In LLVM, we do this by marking the load Acquire.
1334 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001335 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001336
John McCallb88a5662012-03-30 21:00:39 +00001337 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001338 }
1339
1340 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1341 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1342
1343 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001344 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001345
1346 CGF.EmitBlock(InitCheckBlock);
1347
1348 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001349 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001350 // Call __cxa_guard_acquire.
1351 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001352 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001353
1354 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1355
1356 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1357 InitBlock, EndBlock);
1358
1359 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001360 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001361
1362 CGF.EmitBlock(InitBlock);
1363 }
1364
1365 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001366 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001367
John McCall5aa52592011-06-17 07:33:57 +00001368 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001369 // Pop the guard-abort cleanup if we pushed one.
1370 CGF.PopCleanupBlock();
1371
1372 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001373 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001374 } else {
John McCallb88a5662012-03-30 21:00:39 +00001375 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001376 }
1377
1378 CGF.EmitBlock(EndBlock);
1379}
John McCallc84ed6a2012-05-01 06:13:13 +00001380
1381/// Register a global destructor using __cxa_atexit.
1382static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1383 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001384 llvm::Constant *addr,
1385 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001386 const char *Name = "__cxa_atexit";
1387 if (TLS) {
1388 const llvm::Triple &T = CGF.getTarget().getTriple();
1389 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1390 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001391
John McCallc84ed6a2012-05-01 06:13:13 +00001392 // We're assuming that the destructor function is something we can
1393 // reasonably call with the default CC. Go ahead and cast it to the
1394 // right prototype.
1395 llvm::Type *dtorTy =
1396 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1397
1398 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1399 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1400 llvm::FunctionType *atexitTy =
1401 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1402
1403 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001404 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001405 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1406 fn->setDoesNotThrow();
1407
1408 // Create a variable that binds the atexit to this shared object.
1409 llvm::Constant *handle =
1410 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1411
1412 llvm::Value *args[] = {
1413 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1414 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1415 handle
1416 };
John McCall882987f2013-02-28 19:01:20 +00001417 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001418}
1419
1420/// Register a global destructor as best as we know how.
1421void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001422 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001423 llvm::Constant *dtor,
1424 llvm::Constant *addr) {
1425 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001426 if (CGM.getCodeGenOpts().CXAAtExit)
1427 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1428
1429 if (D.getTLSKind())
1430 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001431
1432 // In Apple kexts, we want to add a global destructor entry.
1433 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001434 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001435 // Generate a global destructor entry.
1436 return CGM.AddCXXDtorEntry(dtor, addr);
1437 }
1438
David Blaikieebe87e12013-08-27 23:57:18 +00001439 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001440}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001441
1442/// Get the appropriate linkage for the wrapper function. This is essentially
1443/// the weak form of the variable's linkage; every translation unit which wneeds
1444/// the wrapper emits a copy, and we want the linker to merge them.
1445static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1446 llvm::GlobalValue::LinkageTypes VarLinkage) {
1447 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1448 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1449 // For internal linkage variables, we don't need an external or weak wrapper.
1450 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1451 return VarLinkage;
1452 return llvm::GlobalValue::WeakODRLinkage;
1453}
1454
1455llvm::Function *
1456ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1457 llvm::GlobalVariable *Var) {
1458 // Mangle the name for the thread_local wrapper function.
1459 SmallString<256> WrapperName;
1460 {
1461 llvm::raw_svector_ostream Out(WrapperName);
1462 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1463 Out.flush();
1464 }
1465
1466 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1467 return cast<llvm::Function>(V);
1468
1469 llvm::Type *RetTy = Var->getType();
1470 if (VD->getType()->isReferenceType())
1471 RetTy = RetTy->getPointerElementType();
1472
1473 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1474 llvm::Function *Wrapper = llvm::Function::Create(
1475 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1476 &CGM.getModule());
1477 // Always resolve references to the wrapper at link time.
1478 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1479 return Wrapper;
1480}
1481
1482void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1483 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1484 llvm::Function *InitFunc) {
1485 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1486 const VarDecl *VD = Decls[I].first;
1487 llvm::GlobalVariable *Var = Decls[I].second;
1488
1489 // Mangle the name for the thread_local initialization function.
1490 SmallString<256> InitFnName;
1491 {
1492 llvm::raw_svector_ostream Out(InitFnName);
1493 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1494 Out.flush();
1495 }
1496
1497 // If we have a definition for the variable, emit the initialization
1498 // function as an alias to the global Init function (if any). Otherwise,
1499 // produce a declaration of the initialization function.
1500 llvm::GlobalValue *Init = 0;
1501 bool InitIsInitFunc = false;
1502 if (VD->hasDefinition()) {
1503 InitIsInitFunc = true;
1504 if (InitFunc)
1505 Init =
1506 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1507 InitFnName.str(), InitFunc, &CGM.getModule());
1508 } else {
1509 // Emit a weak global function referring to the initialization function.
1510 // This function will not exist if the TU defining the thread_local
1511 // variable in question does not need any dynamic initialization for
1512 // its thread_local variables.
1513 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1514 Init = llvm::Function::Create(
1515 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1516 &CGM.getModule());
1517 }
1518
1519 if (Init)
1520 Init->setVisibility(Var->getVisibility());
1521
1522 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1523 llvm::LLVMContext &Context = CGM.getModule().getContext();
1524 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1525 CGBuilderTy Builder(Entry);
1526 if (InitIsInitFunc) {
1527 if (Init)
1528 Builder.CreateCall(Init);
1529 } else {
1530 // Don't know whether we have an init function. Call it if it exists.
1531 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1532 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1533 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1534 Builder.CreateCondBr(Have, InitBB, ExitBB);
1535
1536 Builder.SetInsertPoint(InitBB);
1537 Builder.CreateCall(Init);
1538 Builder.CreateBr(ExitBB);
1539
1540 Builder.SetInsertPoint(ExitBB);
1541 }
1542
1543 // For a reference, the result of the wrapper function is a pointer to
1544 // the referenced object.
1545 llvm::Value *Val = Var;
1546 if (VD->getType()->isReferenceType()) {
1547 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1548 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1549 Val = LI;
1550 }
1551
1552 Builder.CreateRet(Val);
1553 }
1554}
1555
1556LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1557 const DeclRefExpr *DRE) {
1558 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1559 QualType T = VD->getType();
1560 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1561 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1562 llvm::Function *Wrapper =
1563 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1564
1565 Val = CGF.Builder.CreateCall(Wrapper);
1566
1567 LValue LV;
1568 if (VD->getType()->isReferenceType())
1569 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1570 else
1571 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1572 CGF.getContext().getDeclAlign(VD));
1573 // FIXME: need setObjCGCLValueClass?
1574 return LV;
1575}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001576
1577/// Return whether the given global decl needs a VTT parameter, which it does
1578/// if it's a base constructor or destructor with virtual bases.
1579bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1580 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1581
1582 // We don't have any virtual bases, just return early.
1583 if (!MD->getParent()->getNumVBases())
1584 return false;
1585
1586 // Check if we have a base constructor.
1587 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1588 return true;
1589
1590 // Check if we have a base destructor.
1591 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1592 return true;
1593
1594 return false;
1595}