blob: 03fea467364875eeec8e5ed476a17fcf8f871bdd [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
Timur Iskhodzhanovad9d3b82013-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
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000183 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
184 const ThisAdjustment &TA);
185
186 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
187 const ReturnAdjustment &RA);
188
Joao Matos2ce88ef2012-07-17 17:10:11 +0000189 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikieeb7d5982012-10-16 22:56:05 +0000190 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000191
John McCallb91cd662012-05-01 05:23:51 +0000192 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall8ed55a52010-09-02 09:58:18 +0000193 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
194 llvm::Value *NewPtr,
195 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000196 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +0000197 QualType ElementType);
John McCallb91cd662012-05-01 05:23:51 +0000198 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
199 llvm::Value *allocPtr,
200 CharUnits cookieSize);
John McCall68ff0372010-09-08 01:44:27 +0000201
John McCallcdf7ef52010-11-06 09:44:32 +0000202 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000203 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smithdbf74ba2013-04-14 23:01:42 +0000204 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
205 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000206
207 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
208 llvm::GlobalVariable *Var);
209 void EmitThreadLocalInitFuncs(
210 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
211 llvm::Function *InitFunc);
212 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
213 const DeclRefExpr *DRE);
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000214
215 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis4e786dd2010-05-25 19:52:27 +0000216};
John McCall86353412010-08-21 22:46:04 +0000217
218class ARMCXXABI : public ItaniumCXXABI {
219public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000220 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
221 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
222 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000223
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000224 bool HasThisReturn(GlobalDecl GD) const {
225 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
226 isa<CXXDestructorDecl>(GD.getDecl()) &&
227 GD.getDtorType() != Dtor_Deleting));
228 }
John McCall5d865c322010-08-31 07:33:07 +0000229
230 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
231
John McCallb91cd662012-05-01 05:23:51 +0000232 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall8ed55a52010-09-02 09:58:18 +0000233 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
234 llvm::Value *NewPtr,
235 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000236 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +0000237 QualType ElementType);
John McCallb91cd662012-05-01 05:23:51 +0000238 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
239 CharUnits cookieSize);
John McCall86353412010-08-21 22:46:04 +0000240};
Charles Davis4e786dd2010-05-25 19:52:27 +0000241}
242
Charles Davis53c59df2010-08-16 03:33:14 +0000243CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000244 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000245 // For IR-generation purposes, there's no significant difference
246 // between the ARM and iOS ABIs.
247 case TargetCXXABI::GenericARM:
248 case TargetCXXABI::iOS:
249 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000250
Tim Northover9bb857a2013-01-31 12:13:10 +0000251 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
252 // include the other 32-bit ARM oddities: constructor/destructor return values
253 // and array cookies.
254 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000255 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
256 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000257
John McCall57625922013-01-25 23:36:14 +0000258 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000259 if (CGM.getContext().getTargetInfo().getTriple().getArch()
260 == llvm::Triple::le32) {
261 // For PNaCl, use ARM-style method pointers so that PNaCl code
262 // does not assume anything about the alignment of function
263 // pointers.
264 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
265 /* UseARMGuardVarABI = */ false);
266 }
John McCall57625922013-01-25 23:36:14 +0000267 return new ItaniumCXXABI(CGM);
268
269 case TargetCXXABI::Microsoft:
270 llvm_unreachable("Microsoft ABI is not Itanium-based");
271 }
272 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000273}
274
Chris Lattnera5f58b02011-07-09 17:41:47 +0000275llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000276ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
277 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000278 return CGM.PtrDiffTy;
279 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000280}
281
John McCalld9c6c0b2010-08-22 00:59:17 +0000282/// In the Itanium and ARM ABIs, method pointers have the form:
283/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
284///
285/// In the Itanium ABI:
286/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
287/// - the this-adjustment is (memptr.adj)
288/// - the virtual offset is (memptr.ptr - 1)
289///
290/// In the ARM ABI:
291/// - method pointers are virtual if (memptr.adj & 1) is nonzero
292/// - the this-adjustment is (memptr.adj >> 1)
293/// - the virtual offset is (memptr.ptr)
294/// ARM uses 'adj' for the virtual flag because Thumb functions
295/// may be only single-byte aligned.
296///
297/// If the member is virtual, the adjusted 'this' pointer points
298/// to a vtable pointer from which the virtual offset is applied.
299///
300/// If the member is non-virtual, memptr.ptr is the address of
301/// the function to call.
John McCall475999d2010-08-22 00:05:51 +0000302llvm::Value *
303ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
304 llvm::Value *&This,
305 llvm::Value *MemFnPtr,
306 const MemberPointerType *MPT) {
307 CGBuilderTy &Builder = CGF.Builder;
308
309 const FunctionProtoType *FPT =
310 MPT->getPointeeType()->getAs<FunctionProtoType>();
311 const CXXRecordDecl *RD =
312 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
313
Chris Lattner2192fe52011-07-18 04:24:23 +0000314 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000315 CGM.getTypes().GetFunctionType(
316 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000317
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000318 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000319
John McCalld9c6c0b2010-08-22 00:59:17 +0000320 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
321 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
322 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
323
John McCalla1dee5302010-08-22 10:59:02 +0000324 // Extract memptr.adj, which is in the second field.
325 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000326
327 // Compute the true adjustment.
328 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000329 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000330 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000331
332 // Apply the adjustment and cast back to the original struct type
333 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000334 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
335 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
336 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000337
338 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000339 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000340
341 // If the LSB in the function pointer is 1, the function pointer points to
342 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000343 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000344 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000345 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
346 else
347 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
348 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000349 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
350
351 // In the virtual path, the adjustment left 'This' pointing to the
352 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000353 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000354 CGF.EmitBlock(FnVirtual);
355
356 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000357 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall475999d2010-08-22 00:05:51 +0000358 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000359 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall475999d2010-08-22 00:05:51 +0000360
361 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000362 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000363 if (!UseARMMethodPtrABI)
364 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000365 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000366
367 // Load the virtual function to call.
368 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000369 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000370 CGF.EmitBranch(FnEnd);
371
372 // In the non-virtual path, the function pointer is actually a
373 // function pointer.
374 CGF.EmitBlock(FnNonVirtual);
375 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000376 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000377
378 // We're done.
379 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000380 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000381 Callee->addIncoming(VirtualFn, FnVirtual);
382 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
383 return Callee;
384}
John McCalla8bbb822010-08-22 03:04:22 +0000385
John McCallc134eb52010-08-31 21:07:20 +0000386/// Compute an l-value by applying the given pointer-to-member to a
387/// base object.
388llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
389 llvm::Value *Base,
390 llvm::Value *MemPtr,
391 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000392 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000393
394 CGBuilderTy &Builder = CGF.Builder;
395
Micah Villmowea2fea22012-10-25 15:39:14 +0000396 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000397
398 // Cast to char*.
399 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
400
401 // Apply the offset, which we assume is non-null.
402 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
403
404 // Cast the address to the appropriate pointer type, adopting the
405 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000406 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000407 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000408 return Builder.CreateBitCast(Addr, PType);
409}
410
John McCallc62bb392012-02-15 01:22:51 +0000411/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
412/// conversion.
413///
414/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000415///
416/// Obligatory offset/adjustment diagram:
417/// <-- offset --> <-- adjustment -->
418/// |--------------------------|----------------------|--------------------|
419/// ^Derived address point ^Base address point ^Member address point
420///
421/// So when converting a base member pointer to a derived member pointer,
422/// we add the offset to the adjustment because the address point has
423/// decreased; and conversely, when converting a derived MP to a base MP
424/// we subtract the offset from the adjustment because the address point
425/// has increased.
426///
427/// The standard forbids (at compile time) conversion to and from
428/// virtual bases, which is why we don't have to consider them here.
429///
430/// The standard forbids (at run time) casting a derived MP to a base
431/// MP when the derived MP does not point to a member of the base.
432/// This is why -1 is a reasonable choice for null data member
433/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000434llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000435ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
436 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000437 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000438 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000439 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
440 E->getCastKind() == CK_ReinterpretMemberPointer);
441
442 // Under Itanium, reinterprets don't require any additional processing.
443 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
444
445 // Use constant emission if we can.
446 if (isa<llvm::Constant>(src))
447 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
448
449 llvm::Constant *adj = getMemberPointerAdjustment(E);
450 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000451
452 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000453 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000454
John McCallc62bb392012-02-15 01:22:51 +0000455 const MemberPointerType *destTy =
456 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000457
John McCall7a9aac22010-08-23 01:21:21 +0000458 // For member data pointers, this is just a matter of adding the
459 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000460 if (destTy->isMemberDataPointer()) {
461 llvm::Value *dst;
462 if (isDerivedToBase)
463 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000464 else
John McCallc62bb392012-02-15 01:22:51 +0000465 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000466
467 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000468 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
469 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
470 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000471 }
472
John McCalla1dee5302010-08-22 10:59:02 +0000473 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000474 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000475 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
476 offset <<= 1;
477 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000478 }
479
John McCallc62bb392012-02-15 01:22:51 +0000480 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
481 llvm::Value *dstAdj;
482 if (isDerivedToBase)
483 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000484 else
John McCallc62bb392012-02-15 01:22:51 +0000485 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000486
John McCallc62bb392012-02-15 01:22:51 +0000487 return Builder.CreateInsertValue(src, dstAdj, 1);
488}
489
490llvm::Constant *
491ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
492 llvm::Constant *src) {
493 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
494 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
495 E->getCastKind() == CK_ReinterpretMemberPointer);
496
497 // Under Itanium, reinterprets don't require any additional processing.
498 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
499
500 // If the adjustment is trivial, we don't need to do anything.
501 llvm::Constant *adj = getMemberPointerAdjustment(E);
502 if (!adj) return src;
503
504 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
505
506 const MemberPointerType *destTy =
507 E->getType()->castAs<MemberPointerType>();
508
509 // For member data pointers, this is just a matter of adding the
510 // offset if the source is non-null.
511 if (destTy->isMemberDataPointer()) {
512 // null maps to null.
513 if (src->isAllOnesValue()) return src;
514
515 if (isDerivedToBase)
516 return llvm::ConstantExpr::getNSWSub(src, adj);
517 else
518 return llvm::ConstantExpr::getNSWAdd(src, adj);
519 }
520
521 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000522 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000523 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
524 offset <<= 1;
525 adj = llvm::ConstantInt::get(adj->getType(), offset);
526 }
527
528 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
529 llvm::Constant *dstAdj;
530 if (isDerivedToBase)
531 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
532 else
533 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
534
535 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000536}
John McCall84fa5102010-08-22 04:16:24 +0000537
538llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000539ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000540 // Itanium C++ ABI 2.3:
541 // A NULL pointer is represented as -1.
542 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000543 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000544
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000545 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000546 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000547 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000548}
549
John McCallf3a88602011-02-03 08:15:49 +0000550llvm::Constant *
551ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
552 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000553 // Itanium C++ ABI 2.3:
554 // A pointer to data member is an offset from the base address of
555 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000556 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000557}
558
John McCall2979fe02011-04-12 00:42:48 +0000559llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000560 return BuildMemberPointer(MD, CharUnits::Zero());
561}
562
563llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
564 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000565 assert(MD->isInstance() && "Member function must not be static!");
566 MD = MD->getCanonicalDecl();
567
568 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000569
570 // Get the function pointer (or index if this is a virtual function).
571 llvm::Constant *MemPtr[2];
572 if (MD->isVirtual()) {
Peter Collingbournea8341662011-09-26 01:56:30 +0000573 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000574
Ken Dyckdf016282011-04-09 01:30:02 +0000575 const ASTContext &Context = getContext();
576 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000577 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000578 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000579
Mark Seabornedf0d382013-07-24 16:25:13 +0000580 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000581 // ARM C++ ABI 3.2.1:
582 // This ABI specifies that adj contains twice the this
583 // adjustment, plus 1 if the member function is virtual. The
584 // least significant bit of adj then makes exactly the same
585 // discrimination as the least significant bit of ptr does for
586 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000587 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
588 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000589 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000590 } else {
591 // Itanium C++ ABI 2.3:
592 // For a virtual function, [the pointer field] is 1 plus the
593 // virtual table offset (in bytes) of the function,
594 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000595 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
596 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000597 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000598 }
599 } else {
John McCall2979fe02011-04-12 00:42:48 +0000600 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000601 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000602 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000603 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000604 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000605 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000606 } else {
John McCall2979fe02011-04-12 00:42:48 +0000607 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
608 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000609 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000610 }
John McCall2979fe02011-04-12 00:42:48 +0000611 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000612
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000613 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000614 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
615 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000616 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000617 }
John McCall1c456c82010-08-22 06:43:33 +0000618
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000619 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000620}
621
Richard Smithdafff942012-01-14 04:30:29 +0000622llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
623 QualType MPType) {
624 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
625 const ValueDecl *MPD = MP.getMemberPointerDecl();
626 if (!MPD)
627 return EmitNullMemberPointer(MPT);
628
Reid Kleckner452abac2013-05-09 21:01:17 +0000629 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000630
631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
632 return BuildMemberPointer(MD, ThisAdjustment);
633
634 CharUnits FieldOffset =
635 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
636 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
637}
638
John McCall131d97d2010-08-22 08:30:07 +0000639/// The comparison algorithm is pretty easy: the member pointers are
640/// the same if they're either bitwise identical *or* both null.
641///
642/// ARM is different here only because null-ness is more complicated.
643llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000644ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
645 llvm::Value *L,
646 llvm::Value *R,
647 const MemberPointerType *MPT,
648 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000649 CGBuilderTy &Builder = CGF.Builder;
650
John McCall131d97d2010-08-22 08:30:07 +0000651 llvm::ICmpInst::Predicate Eq;
652 llvm::Instruction::BinaryOps And, Or;
653 if (Inequality) {
654 Eq = llvm::ICmpInst::ICMP_NE;
655 And = llvm::Instruction::Or;
656 Or = llvm::Instruction::And;
657 } else {
658 Eq = llvm::ICmpInst::ICMP_EQ;
659 And = llvm::Instruction::And;
660 Or = llvm::Instruction::Or;
661 }
662
John McCall7a9aac22010-08-23 01:21:21 +0000663 // Member data pointers are easy because there's a unique null
664 // value, so it just comes down to bitwise equality.
665 if (MPT->isMemberDataPointer())
666 return Builder.CreateICmp(Eq, L, R);
667
668 // For member function pointers, the tautologies are more complex.
669 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000670 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000671 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000672 // (L == R) <==> (L.ptr == R.ptr &&
673 // (L.adj == R.adj ||
674 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000675 // The inequality tautologies have exactly the same structure, except
676 // applying De Morgan's laws.
677
678 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
679 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
680
John McCall131d97d2010-08-22 08:30:07 +0000681 // This condition tests whether L.ptr == R.ptr. This must always be
682 // true for equality to hold.
683 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
684
685 // This condition, together with the assumption that L.ptr == R.ptr,
686 // tests whether the pointers are both null. ARM imposes an extra
687 // condition.
688 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
689 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
690
691 // This condition tests whether L.adj == R.adj. If this isn't
692 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000693 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
694 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000695 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
696
697 // Null member function pointers on ARM clear the low bit of Adj,
698 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000699 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000700 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
701
702 // Compute (l.adj | r.adj) & 1 and test it against zero.
703 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
704 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
705 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
706 "cmp.or.adj");
707 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
708 }
709
710 // Tie together all our conditions.
711 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
712 Result = Builder.CreateBinOp(And, PtrEq, Result,
713 Inequality ? "memptr.ne" : "memptr.eq");
714 return Result;
715}
716
717llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000718ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
719 llvm::Value *MemPtr,
720 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000721 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000722
723 /// For member data pointers, this is just a check against -1.
724 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000725 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000726 llvm::Value *NegativeOne =
727 llvm::Constant::getAllOnesValue(MemPtr->getType());
728 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
729 }
John McCall131d97d2010-08-22 08:30:07 +0000730
Daniel Dunbar914bc412011-04-19 23:10:47 +0000731 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000732 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000733
734 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
735 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
736
Daniel Dunbar914bc412011-04-19 23:10:47 +0000737 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
738 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000739 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000740 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000741 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000742 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000743 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
744 "memptr.isvirtual");
745 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000746 }
747
748 return Result;
749}
John McCall1c456c82010-08-22 06:43:33 +0000750
John McCall614dbdc2010-08-22 21:01:12 +0000751/// The Itanium ABI requires non-zero initialization only for data
752/// member pointers, for which '0' is a valid offset.
753bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
754 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000755}
John McCall5d865c322010-08-31 07:33:07 +0000756
John McCall82fb8922012-09-25 10:10:39 +0000757/// The Itanium ABI always places an offset to the complete object
758/// at entry -2 in the vtable.
759llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
760 llvm::Value *ptr,
761 QualType type) {
762 // Grab the vtable pointer as an intptr_t*.
763 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
764
765 // Track back to entry -2 and pull out the offset there.
766 llvm::Value *offsetPtr =
767 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
768 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
769 offset->setAlignment(CGF.PointerAlignInBytes);
770
771 // Apply the offset.
772 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
773 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
774}
775
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000776llvm::Value *
777ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
778 llvm::Value *This,
779 const CXXRecordDecl *ClassDecl,
780 const CXXRecordDecl *BaseClassDecl) {
781 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
782 CharUnits VBaseOffsetOffset =
783 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
784
785 llvm::Value *VBaseOffsetPtr =
786 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
787 "vbase.offset.ptr");
788 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
789 CGM.PtrDiffTy->getPointerTo());
790
791 llvm::Value *VBaseOffset =
792 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
793
794 return VBaseOffset;
795}
796
John McCall5d865c322010-08-31 07:33:07 +0000797/// The generic ABI passes 'this', plus a VTT if it's initializing a
798/// base subobject.
799void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
800 CXXCtorType Type,
801 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000802 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000803 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000804
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000805 // 'this' parameter is already there, as well as 'this' return if
806 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000807
808 // Check if we need to add a VTT parameter (which has type void **).
809 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
810 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
811}
812
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000813void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
814 // Just make sure we're in sync with TargetCXXABI.
815 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
816
817 // The constructor used for constructing this as a complete class;
818 // constucts the virtual bases, then calls the base constructor.
819 if (!D->getParent()->isAbstract()) {
820 // We don't need to emit the complete ctor if the class is abstract.
821 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
822 }
823
824 // The constructor used for constructing this as a base class;
825 // ignores virtual bases.
826 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
827}
828
John McCall5d865c322010-08-31 07:33:07 +0000829/// The generic ABI passes 'this', plus a VTT if it's destroying a
830/// base subobject.
831void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
832 CXXDtorType Type,
833 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000834 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000835 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000836
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000837 // 'this' parameter is already there, as well as 'this' return if
838 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000839
840 // Check if we need to add a VTT parameter (which has type void **).
841 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
842 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
843}
844
Reid Klecknere7de47e2013-07-22 13:51:44 +0000845void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
846 // The destructor in a virtual table is always a 'deleting'
847 // destructor, which calls the complete destructor and then uses the
848 // appropriate operator delete.
849 if (D->isVirtual())
850 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
851
852 // The destructor used for destructing this as a most-derived class;
853 // call the base destructor and then destructs any virtual bases.
854 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
855
856 // The destructor used for destructing this as a base class; ignores
857 // virtual bases.
858 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
859}
860
John McCall5d865c322010-08-31 07:33:07 +0000861void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
862 QualType &ResTy,
863 FunctionArgList &Params) {
864 /// Create the 'this' variable.
865 BuildThisParam(CGF, Params);
866
867 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
868 assert(MD->isInstance());
869
870 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000871 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000872 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000873
874 // FIXME: avoid the fake decl
875 QualType T = Context.getPointerType(Context.VoidPtrTy);
876 ImplicitParamDecl *VTTDecl
877 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
878 &Context.Idents.get("vtt"), T);
John McCalla738c252011-03-09 04:27:21 +0000879 Params.push_back(VTTDecl);
John McCall5d865c322010-08-31 07:33:07 +0000880 getVTTDecl(CGF) = VTTDecl;
881 }
882}
883
John McCall5d865c322010-08-31 07:33:07 +0000884void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
885 /// Initialize the 'this' slot.
886 EmitThisParam(CGF);
887
888 /// Initialize the 'vtt' slot if needed.
889 if (getVTTDecl(CGF)) {
890 getVTTValue(CGF)
891 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
892 "vtt");
893 }
John McCall5d865c322010-08-31 07:33:07 +0000894
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000895 /// If this is a function that the ABI specifies returns 'this', initialize
896 /// the return slot to 'this' at the start of the function.
897 ///
898 /// Unlike the setting of return types, this is done within the ABI
899 /// implementation instead of by clients of CGCXXABI because:
900 /// 1) getThisValue is currently protected
901 /// 2) in theory, an ABI could implement 'this' returns some other way;
902 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000903 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000904 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000905}
906
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000907void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000908 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000909 CXXCtorType Type,
910 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000911 llvm::Value *This,
912 CallExpr::const_arg_iterator ArgBeg,
913 CallExpr::const_arg_iterator ArgEnd) {
914 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
915 Delegating);
916 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
917 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
918
919 // FIXME: Provide a source location here.
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000920 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
921 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000922}
923
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000924void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
925 const CXXRecordDecl *RD) {
926 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
927 if (VTable->hasInitializer())
928 return;
929
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000930 ItaniumVTableContext &VTContext = CGM.getVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000931 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
932 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
933
934 // Create and set the initializer.
935 llvm::Constant *Init = CGVT.CreateVTableInitializer(
936 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
937 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
938 VTable->setInitializer(Init);
939
940 // Set the correct linkage.
941 VTable->setLinkage(Linkage);
942
943 // Set the right visibility.
944 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
945
946 // If this is the magic class __cxxabiv1::__fundamental_type_info,
947 // we will emit the typeinfo for the fundamental types. This is the
948 // same behaviour as GCC.
949 const DeclContext *DC = RD->getDeclContext();
950 if (RD->getIdentifier() &&
951 RD->getIdentifier()->isStr("__fundamental_type_info") &&
952 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
953 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
954 DC->getParent()->isTranslationUnit())
955 CGM.EmitFundamentalRTTIDescriptors();
956}
957
958llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
959 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
960 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
961 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
962 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
963
964 llvm::Value *VTableAddressPoint;
965 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
966 // Get the secondary vpointer index.
967 uint64_t VirtualPointerIndex =
968 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
969
970 /// Load the VTT.
971 llvm::Value *VTT = CGF.LoadCXXVTT();
972 if (VirtualPointerIndex)
973 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
974
975 // And load the address point from the VTT.
976 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
977 } else {
978 llvm::Constant *VTable =
979 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
980 uint64_t AddressPoint = CGM.getVTableContext().getVTableLayout(VTableClass)
981 .getAddressPoint(Base);
982 VTableAddressPoint =
983 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
984 }
985
986 return VTableAddressPoint;
987}
988
989llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
990 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
991 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
992
993 // Find the appropriate vtable within the vtable group.
994 uint64_t AddressPoint =
995 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
996 llvm::Value *Indices[] = {
997 llvm::ConstantInt::get(CGM.Int64Ty, 0),
998 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
999 };
1000
1001 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1002}
1003
1004llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1005 CharUnits VPtrOffset) {
1006 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1007
1008 llvm::GlobalVariable *&VTable = VTables[RD];
1009 if (VTable)
1010 return VTable;
1011
1012 // Queue up this v-table for possible deferred emission.
1013 CGM.addDeferredVTable(RD);
1014
1015 SmallString<256> OutName;
1016 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001017 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001018 Out.flush();
1019 StringRef Name = OutName.str();
1020
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001021 ItaniumVTableContext &VTContext = CGM.getVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001022 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1023 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1024
1025 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1026 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1027 VTable->setUnnamedAddr(true);
1028 return VTable;
1029}
1030
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001031llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1032 GlobalDecl GD,
1033 llvm::Value *This,
1034 llvm::Type *Ty) {
1035 GD = GD.getCanonicalDecl();
1036 Ty = Ty->getPointerTo()->getPointerTo();
1037 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1038
1039 uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(GD);
1040 llvm::Value *VFuncPtr =
1041 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1042 return CGF.Builder.CreateLoad(VFuncPtr);
1043}
1044
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001045void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1046 const CXXDestructorDecl *Dtor,
1047 CXXDtorType DtorType,
1048 SourceLocation CallLoc,
1049 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001050 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1051
1052 const CGFunctionInfo *FInfo
1053 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1054 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001055 llvm::Value *Callee =
1056 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001057
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001058 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1059 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001060}
1061
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001062void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001063 CodeGenVTables &VTables = CGM.getVTables();
1064 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001065 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001066}
1067
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001068static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1069 llvm::Value *Ptr,
1070 int64_t NonVirtualAdjustment,
1071 int64_t VirtualAdjustment,
1072 bool IsReturnAdjustment) {
1073 if (!NonVirtualAdjustment && !VirtualAdjustment)
1074 return Ptr;
1075
1076 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1077 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1078
1079 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1080 // Perform the non-virtual adjustment for a base-to-derived cast.
1081 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1082 }
1083
1084 if (VirtualAdjustment) {
1085 llvm::Type *PtrDiffTy =
1086 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1087
1088 // Perform the virtual adjustment.
1089 llvm::Value *VTablePtrPtr =
1090 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1091
1092 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1093
1094 llvm::Value *OffsetPtr =
1095 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1096
1097 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1098
1099 // Load the adjustment offset from the vtable.
1100 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1101
1102 // Adjust our pointer.
1103 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1104 }
1105
1106 if (NonVirtualAdjustment && IsReturnAdjustment) {
1107 // Perform the non-virtual adjustment for a derived-to-base cast.
1108 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1109 }
1110
1111 // Cast back to the original type.
1112 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1113}
1114
1115llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1116 llvm::Value *This,
1117 const ThisAdjustment &TA) {
1118 return performTypeAdjustment(CGF, This, TA.NonVirtual, TA.VCallOffsetOffset,
1119 /*IsReturnAdjustment=*/false);
1120}
1121
1122llvm::Value *
1123ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1124 const ReturnAdjustment &RA) {
1125 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1126 RA.Virtual.Itanium.VBaseOffsetOffset,
1127 /*IsReturnAdjustment=*/true);
1128}
1129
John McCall5d865c322010-08-31 07:33:07 +00001130void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1131 RValue RV, QualType ResultType) {
1132 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1133 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1134
1135 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001136 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001137 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1138 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1139 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1140}
John McCall8ed55a52010-09-02 09:58:18 +00001141
1142/************************** Array allocation cookies **************************/
1143
John McCallb91cd662012-05-01 05:23:51 +00001144CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1145 // The array cookie is a size_t; pad that up to the element alignment.
1146 // The cookie is actually right-justified in that space.
1147 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1148 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001149}
1150
1151llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1152 llvm::Value *NewPtr,
1153 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001154 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001155 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001156 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001157
Micah Villmowea2fea22012-10-25 15:39:14 +00001158 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001159
John McCall9bca9232010-09-02 10:25:57 +00001160 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001161 QualType SizeTy = Ctx.getSizeType();
1162 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1163
1164 // The size of the cookie.
1165 CharUnits CookieSize =
1166 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001167 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001168
1169 // Compute an offset to the cookie.
1170 llvm::Value *CookiePtr = NewPtr;
1171 CharUnits CookieOffset = CookieSize - SizeSize;
1172 if (!CookieOffset.isZero())
1173 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1174 CookieOffset.getQuantity());
1175
1176 // Write the number of elements into the appropriate slot.
1177 llvm::Value *NumElementsPtr
1178 = CGF.Builder.CreateBitCast(CookiePtr,
1179 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1180 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1181
1182 // Finally, compute a pointer to the actual data buffer by skipping
1183 // over the cookie completely.
1184 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1185 CookieSize.getQuantity());
1186}
1187
John McCallb91cd662012-05-01 05:23:51 +00001188llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1189 llvm::Value *allocPtr,
1190 CharUnits cookieSize) {
1191 // The element size is right-justified in the cookie.
1192 llvm::Value *numElementsPtr = allocPtr;
1193 CharUnits numElementsOffset =
1194 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1195 if (!numElementsOffset.isZero())
1196 numElementsPtr =
1197 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1198 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001199
Micah Villmowea2fea22012-10-25 15:39:14 +00001200 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001201 numElementsPtr =
1202 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1203 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001204}
1205
John McCallb91cd662012-05-01 05:23:51 +00001206CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001207 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001208 // struct array_cookie {
1209 // std::size_t element_size; // element_size != 0
1210 // std::size_t element_count;
1211 // };
John McCallc19c7062013-01-25 23:36:19 +00001212 // But the base ABI doesn't give anything an alignment greater than
1213 // 8, so we can dismiss this as typical ABI-author blindness to
1214 // actual language complexity and round up to the element alignment.
1215 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1216 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001217}
1218
1219llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001220 llvm::Value *newPtr,
1221 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001222 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001223 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001224 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001225
John McCallc19c7062013-01-25 23:36:19 +00001226 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1227 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001228
1229 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001230 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001231
1232 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001233 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1234 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1235 getContext().getTypeSizeInChars(elementType).getQuantity());
1236 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001237
1238 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001239 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1240 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001241
1242 // Finally, compute a pointer to the actual data buffer by skipping
1243 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001244 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1245 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1246 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001247}
1248
John McCallb91cd662012-05-01 05:23:51 +00001249llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1250 llvm::Value *allocPtr,
1251 CharUnits cookieSize) {
1252 // The number of elements is at offset sizeof(size_t) relative to
1253 // the allocated pointer.
1254 llvm::Value *numElementsPtr
1255 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001256
Micah Villmowea2fea22012-10-25 15:39:14 +00001257 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001258 numElementsPtr =
1259 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1260 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001261}
1262
John McCall68ff0372010-09-08 01:44:27 +00001263/*********************** Static local initialization **************************/
1264
1265static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001266 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001267 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001268 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001269 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001270 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001271 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001272 llvm::AttributeSet::get(CGM.getLLVMContext(),
1273 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001274 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001275}
1276
1277static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001278 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001279 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001280 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001281 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001282 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001283 llvm::AttributeSet::get(CGM.getLLVMContext(),
1284 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001285 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001286}
1287
1288static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001289 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001290 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001291 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001292 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001293 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001294 llvm::AttributeSet::get(CGM.getLLVMContext(),
1295 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001296 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001297}
1298
1299namespace {
1300 struct CallGuardAbort : EHScopeStack::Cleanup {
1301 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001302 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001303
John McCall30317fd2011-07-12 20:27:29 +00001304 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall882987f2013-02-28 19:01:20 +00001305 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1306 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001307 }
1308 };
1309}
1310
1311/// The ARM code here follows the Itanium code closely enough that we
1312/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001313void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1314 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001315 llvm::GlobalVariable *var,
1316 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001317 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001318
Richard Smithdbf74ba2013-04-14 23:01:42 +00001319 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001320 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001321 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1322 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001323
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001324 // If we have a global variable with internal linkage and thread-safe statics
1325 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001326 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1327
1328 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001329 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001330 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001331 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001332 // Guard variables are 64 bits in the generic ABI and size width on ARM
1333 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001334 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001335 }
John McCallb88a5662012-03-30 21:00:39 +00001336 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001337
John McCallb88a5662012-03-30 21:00:39 +00001338 // Create the guard variable if we don't already have it (as we
1339 // might if we're double-emitting this function body).
1340 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1341 if (!guard) {
1342 // Mangle the name for the guard.
1343 SmallString<256> guardName;
1344 {
1345 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001346 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001347 out.flush();
1348 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001349
John McCallb88a5662012-03-30 21:00:39 +00001350 // Create the guard variable with a zero-initializer.
1351 // Just absorb linkage and visibility from the guarded variable.
1352 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1353 false, var->getLinkage(),
1354 llvm::ConstantInt::get(guardTy, 0),
1355 guardName.str());
1356 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001357 // If the variable is thread-local, so is its guard variable.
1358 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001359
1360 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1361 }
John McCall87590e62012-03-30 07:09:50 +00001362
John McCall68ff0372010-09-08 01:44:27 +00001363 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001364 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001365
1366 // ARM C++ ABI 3.2.3.1:
1367 // To support the potential use of initialization guard variables
1368 // as semaphores that are the target of ARM SWP and LDREX/STREX
1369 // synchronizing instructions we define a static initialization
1370 // guard variable to be a 4-byte aligned, 4- byte word with the
1371 // following inline access protocol.
1372 // #define INITIALIZED 1
1373 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1374 // if (__cxa_guard_acquire(&obj_guard))
1375 // ...
1376 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001377 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001378 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001379 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1380 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001381 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001382
1383 // Itanium C++ ABI 3.3.2:
1384 // The following is pseudo-code showing how these functions can be used:
1385 // if (obj_guard.first_byte == 0) {
1386 // if ( __cxa_guard_acquire (&obj_guard) ) {
1387 // try {
1388 // ... initialize the object ...;
1389 // } catch (...) {
1390 // __cxa_guard_abort (&obj_guard);
1391 // throw;
1392 // }
1393 // ... queue object destructor with __cxa_atexit() ...;
1394 // __cxa_guard_release (&obj_guard);
1395 // }
1396 // }
1397 } else {
1398 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001399 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001400 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001401 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001402
Eli Friedman84d28122011-09-13 22:21:56 +00001403 // Itanium ABI:
1404 // An implementation supporting thread-safety on multiprocessor
1405 // systems must also guarantee that references to the initialized
1406 // object do not occur before the load of the initialization flag.
1407 //
1408 // In LLVM, we do this by marking the load Acquire.
1409 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001410 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001411
John McCallb88a5662012-03-30 21:00:39 +00001412 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001413 }
1414
1415 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1416 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1417
1418 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001419 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001420
1421 CGF.EmitBlock(InitCheckBlock);
1422
1423 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001424 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001425 // Call __cxa_guard_acquire.
1426 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001427 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001428
1429 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1430
1431 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1432 InitBlock, EndBlock);
1433
1434 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001435 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001436
1437 CGF.EmitBlock(InitBlock);
1438 }
1439
1440 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001441 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001442
John McCall5aa52592011-06-17 07:33:57 +00001443 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001444 // Pop the guard-abort cleanup if we pushed one.
1445 CGF.PopCleanupBlock();
1446
1447 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001448 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001449 } else {
John McCallb88a5662012-03-30 21:00:39 +00001450 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001451 }
1452
1453 CGF.EmitBlock(EndBlock);
1454}
John McCallc84ed6a2012-05-01 06:13:13 +00001455
1456/// Register a global destructor using __cxa_atexit.
1457static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1458 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001459 llvm::Constant *addr,
1460 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001461 const char *Name = "__cxa_atexit";
1462 if (TLS) {
1463 const llvm::Triple &T = CGF.getTarget().getTriple();
1464 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1465 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001466
John McCallc84ed6a2012-05-01 06:13:13 +00001467 // We're assuming that the destructor function is something we can
1468 // reasonably call with the default CC. Go ahead and cast it to the
1469 // right prototype.
1470 llvm::Type *dtorTy =
1471 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1472
1473 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1474 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1475 llvm::FunctionType *atexitTy =
1476 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1477
1478 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001479 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001480 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1481 fn->setDoesNotThrow();
1482
1483 // Create a variable that binds the atexit to this shared object.
1484 llvm::Constant *handle =
1485 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1486
1487 llvm::Value *args[] = {
1488 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1489 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1490 handle
1491 };
John McCall882987f2013-02-28 19:01:20 +00001492 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001493}
1494
1495/// Register a global destructor as best as we know how.
1496void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001497 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001498 llvm::Constant *dtor,
1499 llvm::Constant *addr) {
1500 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001501 if (CGM.getCodeGenOpts().CXAAtExit)
1502 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1503
1504 if (D.getTLSKind())
1505 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001506
1507 // In Apple kexts, we want to add a global destructor entry.
1508 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001509 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001510 // Generate a global destructor entry.
1511 return CGM.AddCXXDtorEntry(dtor, addr);
1512 }
1513
David Blaikieebe87e12013-08-27 23:57:18 +00001514 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001515}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001516
1517/// Get the appropriate linkage for the wrapper function. This is essentially
1518/// the weak form of the variable's linkage; every translation unit which wneeds
1519/// the wrapper emits a copy, and we want the linker to merge them.
1520static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1521 llvm::GlobalValue::LinkageTypes VarLinkage) {
1522 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1523 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1524 // For internal linkage variables, we don't need an external or weak wrapper.
1525 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1526 return VarLinkage;
1527 return llvm::GlobalValue::WeakODRLinkage;
1528}
1529
1530llvm::Function *
1531ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1532 llvm::GlobalVariable *Var) {
1533 // Mangle the name for the thread_local wrapper function.
1534 SmallString<256> WrapperName;
1535 {
1536 llvm::raw_svector_ostream Out(WrapperName);
1537 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1538 Out.flush();
1539 }
1540
1541 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1542 return cast<llvm::Function>(V);
1543
1544 llvm::Type *RetTy = Var->getType();
1545 if (VD->getType()->isReferenceType())
1546 RetTy = RetTy->getPointerElementType();
1547
1548 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1549 llvm::Function *Wrapper = llvm::Function::Create(
1550 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1551 &CGM.getModule());
1552 // Always resolve references to the wrapper at link time.
1553 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1554 return Wrapper;
1555}
1556
1557void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1558 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1559 llvm::Function *InitFunc) {
1560 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1561 const VarDecl *VD = Decls[I].first;
1562 llvm::GlobalVariable *Var = Decls[I].second;
1563
1564 // Mangle the name for the thread_local initialization function.
1565 SmallString<256> InitFnName;
1566 {
1567 llvm::raw_svector_ostream Out(InitFnName);
1568 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1569 Out.flush();
1570 }
1571
1572 // If we have a definition for the variable, emit the initialization
1573 // function as an alias to the global Init function (if any). Otherwise,
1574 // produce a declaration of the initialization function.
1575 llvm::GlobalValue *Init = 0;
1576 bool InitIsInitFunc = false;
1577 if (VD->hasDefinition()) {
1578 InitIsInitFunc = true;
1579 if (InitFunc)
1580 Init =
1581 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1582 InitFnName.str(), InitFunc, &CGM.getModule());
1583 } else {
1584 // Emit a weak global function referring to the initialization function.
1585 // This function will not exist if the TU defining the thread_local
1586 // variable in question does not need any dynamic initialization for
1587 // its thread_local variables.
1588 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1589 Init = llvm::Function::Create(
1590 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1591 &CGM.getModule());
1592 }
1593
1594 if (Init)
1595 Init->setVisibility(Var->getVisibility());
1596
1597 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1598 llvm::LLVMContext &Context = CGM.getModule().getContext();
1599 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1600 CGBuilderTy Builder(Entry);
1601 if (InitIsInitFunc) {
1602 if (Init)
1603 Builder.CreateCall(Init);
1604 } else {
1605 // Don't know whether we have an init function. Call it if it exists.
1606 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1607 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1608 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1609 Builder.CreateCondBr(Have, InitBB, ExitBB);
1610
1611 Builder.SetInsertPoint(InitBB);
1612 Builder.CreateCall(Init);
1613 Builder.CreateBr(ExitBB);
1614
1615 Builder.SetInsertPoint(ExitBB);
1616 }
1617
1618 // For a reference, the result of the wrapper function is a pointer to
1619 // the referenced object.
1620 llvm::Value *Val = Var;
1621 if (VD->getType()->isReferenceType()) {
1622 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1623 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1624 Val = LI;
1625 }
1626
1627 Builder.CreateRet(Val);
1628 }
1629}
1630
1631LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1632 const DeclRefExpr *DRE) {
1633 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1634 QualType T = VD->getType();
1635 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1636 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1637 llvm::Function *Wrapper =
1638 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1639
1640 Val = CGF.Builder.CreateCall(Wrapper);
1641
1642 LValue LV;
1643 if (VD->getType()->isReferenceType())
1644 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1645 else
1646 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1647 CGF.getContext().getDeclAlign(VD));
1648 // FIXME: need setObjCGCLValueClass?
1649 return LV;
1650}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001651
1652/// Return whether the given global decl needs a VTT parameter, which it does
1653/// if it's a base constructor or destructor with virtual bases.
1654bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1655 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1656
1657 // We don't have any virtual bases, just return early.
1658 if (!MD->getParent()->getNumVBases())
1659 return false;
1660
1661 // Check if we have a base constructor.
1662 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1663 return true;
1664
1665 // Check if we have a base destructor.
1666 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1667 return true;
1668
1669 return false;
1670}