blob: c33eb62ce2af73cebdd0d69af0e7ca6263076e3d [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"
David Majnemer1162d252014-06-22 19:05:33 +000028#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000032
33using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000034using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000035
36namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000037class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000038 /// VTables - All the vtables which have been defined.
39 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
40
John McCall475999d2010-08-22 00:05:51 +000041protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000042 bool UseARMMethodPtrABI;
43 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000044
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000045 ItaniumMangleContext &getMangleContext() {
46 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
47 }
48
Charles Davis4e786dd2010-05-25 19:52:27 +000049public:
Mark Seabornedf0d382013-07-24 16:25:13 +000050 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
51 bool UseARMMethodPtrABI = false,
52 bool UseARMGuardVarABI = false) :
53 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
54 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000055
Reid Kleckner40ca9132014-05-13 22:05:45 +000056 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000057
Craig Topper4f12f102014-03-12 06:41:41 +000058 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000059 // Structures with either a non-trivial destructor or a non-trivial
60 // copy constructor are always indirect.
61 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
62 // special members.
63 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064 return RAA_Indirect;
65 return RAA_Default;
66 }
67
Craig Topper4f12f102014-03-12 06:41:41 +000068 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000069
Craig Topper4f12f102014-03-12 06:41:41 +000070 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000071
Craig Topper4f12f102014-03-12 06:41:41 +000072 llvm::Value *
73 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74 const Expr *E,
75 llvm::Value *&This,
76 llvm::Value *MemFnPtr,
77 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000078
Craig Topper4f12f102014-03-12 06:41:41 +000079 llvm::Value *
80 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
81 llvm::Value *Base,
82 llvm::Value *MemPtr,
83 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000084
John McCall7a9aac22010-08-23 01:21:21 +000085 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
86 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000087 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000088 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000089 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000090
Craig Topper4f12f102014-03-12 06:41:41 +000091 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000092
Craig Topper4f12f102014-03-12 06:41:41 +000093 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000094 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000095 CharUnits offset) override;
96 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +000097 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
98 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +000099
John McCall7a9aac22010-08-23 01:21:21 +0000100 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000101 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000102 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000103 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000104
John McCall7a9aac22010-08-23 01:21:21 +0000105 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000106 llvm::Value *Addr,
107 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000108
Craig Topper4f12f102014-03-12 06:41:41 +0000109 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
110 QualType type) override;
John McCall82fb8922012-09-25 10:10:39 +0000111
David Majnemer1162d252014-06-22 19:05:33 +0000112 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
113 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
114 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
115 llvm::Value *ThisPtr,
116 llvm::Type *StdTypeInfoPtrTy) override;
117
118 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
119 QualType SrcRecordTy) override;
120
121 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
122 QualType SrcRecordTy, QualType DestTy,
123 QualType DestRecordTy,
124 llvm::BasicBlock *CastEnd) override;
125
126 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
127 QualType SrcRecordTy,
128 QualType DestTy) override;
129
130 bool EmitBadCastCall(CodeGenFunction &CGF) override;
131
Craig Topper4f12f102014-03-12 06:41:41 +0000132 llvm::Value *
133 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
134 const CXXRecordDecl *ClassDecl,
135 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000136
John McCall5d865c322010-08-31 07:33:07 +0000137 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
Craig Topper4f12f102014-03-12 06:41:41 +0000138 CXXCtorType T, CanQualType &ResTy,
139 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000140
Craig Topper4f12f102014-03-12 06:41:41 +0000141 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000142
John McCall5d865c322010-08-31 07:33:07 +0000143 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 CXXDtorType T, CanQualType &ResTy,
145 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000146
Reid Klecknere7de47e2013-07-22 13:51:44 +0000147 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000148 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000149 // Itanium does not emit any destructor variant as an inline thunk.
150 // Delegating may occur as an optimization, but all variants are either
151 // emitted with external linkage or as linkonce if they are inline and used.
152 return false;
153 }
154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000156
Reid Kleckner89077a12013-12-17 19:46:40 +0000157 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000158 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000159
Craig Topper4f12f102014-03-12 06:41:41 +0000160 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000161
Reid Kleckner89077a12013-12-17 19:46:40 +0000162 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
163 const CXXConstructorDecl *D,
164 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000165 bool Delegating,
166 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000167
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000168 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
169 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000170 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000171
Craig Topper4f12f102014-03-12 06:41:41 +0000172 void emitVTableDefinitions(CodeGenVTables &CGVT,
173 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000174
175 llvm::Value *getVTableAddressPointInStructor(
176 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
177 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000178 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000179
180 llvm::Constant *
181 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000182 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000183
184 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000185 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000186
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000187 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000188 llvm::Value *This,
189 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000190
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000191 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
192 const CXXDestructorDecl *Dtor,
193 CXXDtorType DtorType, SourceLocation CallLoc,
Craig Topper4f12f102014-03-12 06:41:41 +0000194 llvm::Value *This) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000195
Craig Topper4f12f102014-03-12 06:41:41 +0000196 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000197
Hans Wennborgc94391d2014-06-06 20:04:01 +0000198 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
199 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000200 // Allow inlining of thunks by emitting them with available_externally
201 // linkage together with vtables when needed.
202 if (ForVTable)
203 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
204 }
205
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000206 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000207 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000208
209 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000211
Craig Topper4f12f102014-03-12 06:41:41 +0000212 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
213 StringRef GetDeletedVirtualCallName() override
214 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000215
Craig Topper4f12f102014-03-12 06:41:41 +0000216 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000217 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
218 llvm::Value *NewPtr,
219 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000220 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000222 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
223 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000224 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000225
John McCallcdf7ef52010-11-06 09:44:32 +0000226 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000227 llvm::GlobalVariable *DeclPtr,
228 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000229 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000231
232 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
233 llvm::GlobalVariable *Var);
234 void EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +0000235 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000236 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000237 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
238 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000239
Craig Topper4f12f102014-03-12 06:41:41 +0000240 bool NeedsVTTParameter(GlobalDecl GD) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000241};
John McCall86353412010-08-21 22:46:04 +0000242
243class ARMCXXABI : public ItaniumCXXABI {
244public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000245 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
246 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
247 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000248
Craig Topper4f12f102014-03-12 06:41:41 +0000249 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000250 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
251 isa<CXXDestructorDecl>(GD.getDecl()) &&
252 GD.getDtorType() != Dtor_Deleting));
253 }
John McCall5d865c322010-08-31 07:33:07 +0000254
Craig Topper4f12f102014-03-12 06:41:41 +0000255 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
256 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000257
Craig Topper4f12f102014-03-12 06:41:41 +0000258 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000259 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
260 llvm::Value *NewPtr,
261 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000262 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000263 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000264 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000265 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000266};
Tim Northovera2ee4332014-03-29 15:09:45 +0000267
268class iOS64CXXABI : public ARMCXXABI {
269public:
270 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000271
272 // ARM64 libraries are prepared for non-unique RTTI.
273 bool shouldRTTIBeUnique() override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000274};
Charles Davis4e786dd2010-05-25 19:52:27 +0000275}
276
Charles Davis53c59df2010-08-16 03:33:14 +0000277CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000278 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000279 // For IR-generation purposes, there's no significant difference
280 // between the ARM and iOS ABIs.
281 case TargetCXXABI::GenericARM:
282 case TargetCXXABI::iOS:
283 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000284
Tim Northovera2ee4332014-03-29 15:09:45 +0000285 case TargetCXXABI::iOS64:
286 return new iOS64CXXABI(CGM);
287
Tim Northover9bb857a2013-01-31 12:13:10 +0000288 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
289 // include the other 32-bit ARM oddities: constructor/destructor return values
290 // and array cookies.
291 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000292 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
293 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000294
John McCall57625922013-01-25 23:36:14 +0000295 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000296 if (CGM.getContext().getTargetInfo().getTriple().getArch()
297 == llvm::Triple::le32) {
298 // For PNaCl, use ARM-style method pointers so that PNaCl code
299 // does not assume anything about the alignment of function
300 // pointers.
301 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
302 /* UseARMGuardVarABI = */ false);
303 }
John McCall57625922013-01-25 23:36:14 +0000304 return new ItaniumCXXABI(CGM);
305
306 case TargetCXXABI::Microsoft:
307 llvm_unreachable("Microsoft ABI is not Itanium-based");
308 }
309 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000310}
311
Chris Lattnera5f58b02011-07-09 17:41:47 +0000312llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000313ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
314 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000315 return CGM.PtrDiffTy;
316 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000317}
318
John McCalld9c6c0b2010-08-22 00:59:17 +0000319/// In the Itanium and ARM ABIs, method pointers have the form:
320/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
321///
322/// In the Itanium ABI:
323/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
324/// - the this-adjustment is (memptr.adj)
325/// - the virtual offset is (memptr.ptr - 1)
326///
327/// In the ARM ABI:
328/// - method pointers are virtual if (memptr.adj & 1) is nonzero
329/// - the this-adjustment is (memptr.adj >> 1)
330/// - the virtual offset is (memptr.ptr)
331/// ARM uses 'adj' for the virtual flag because Thumb functions
332/// may be only single-byte aligned.
333///
334/// If the member is virtual, the adjusted 'this' pointer points
335/// to a vtable pointer from which the virtual offset is applied.
336///
337/// If the member is non-virtual, memptr.ptr is the address of
338/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000339llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
340 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
341 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000342 CGBuilderTy &Builder = CGF.Builder;
343
344 const FunctionProtoType *FPT =
345 MPT->getPointeeType()->getAs<FunctionProtoType>();
346 const CXXRecordDecl *RD =
347 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
348
Chris Lattner2192fe52011-07-18 04:24:23 +0000349 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000350 CGM.getTypes().GetFunctionType(
351 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000352
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000353 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000354
John McCalld9c6c0b2010-08-22 00:59:17 +0000355 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
356 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
357 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
358
John McCalla1dee5302010-08-22 10:59:02 +0000359 // Extract memptr.adj, which is in the second field.
360 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000361
362 // Compute the true adjustment.
363 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000364 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000365 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000366
367 // Apply the adjustment and cast back to the original struct type
368 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000369 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
370 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
371 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000372
373 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000374 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000375
376 // If the LSB in the function pointer is 1, the function pointer points to
377 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000378 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000379 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000380 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
381 else
382 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
383 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000384 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
385
386 // In the virtual path, the adjustment left 'This' pointing to the
387 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000388 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000389 CGF.EmitBlock(FnVirtual);
390
391 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000392 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000393 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000394
395 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000396 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000397 if (!UseARMMethodPtrABI)
398 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000399 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000400
401 // Load the virtual function to call.
402 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000403 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000404 CGF.EmitBranch(FnEnd);
405
406 // In the non-virtual path, the function pointer is actually a
407 // function pointer.
408 CGF.EmitBlock(FnNonVirtual);
409 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000410 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000411
412 // We're done.
413 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000414 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000415 Callee->addIncoming(VirtualFn, FnVirtual);
416 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
417 return Callee;
418}
John McCalla8bbb822010-08-22 03:04:22 +0000419
John McCallc134eb52010-08-31 21:07:20 +0000420/// Compute an l-value by applying the given pointer-to-member to a
421/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000422llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
423 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
424 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000425 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000426
427 CGBuilderTy &Builder = CGF.Builder;
428
Micah Villmowea2fea22012-10-25 15:39:14 +0000429 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000430
431 // Cast to char*.
432 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
433
434 // Apply the offset, which we assume is non-null.
435 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
436
437 // Cast the address to the appropriate pointer type, adopting the
438 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000439 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000440 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000441 return Builder.CreateBitCast(Addr, PType);
442}
443
John McCallc62bb392012-02-15 01:22:51 +0000444/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
445/// conversion.
446///
447/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000448///
449/// Obligatory offset/adjustment diagram:
450/// <-- offset --> <-- adjustment -->
451/// |--------------------------|----------------------|--------------------|
452/// ^Derived address point ^Base address point ^Member address point
453///
454/// So when converting a base member pointer to a derived member pointer,
455/// we add the offset to the adjustment because the address point has
456/// decreased; and conversely, when converting a derived MP to a base MP
457/// we subtract the offset from the adjustment because the address point
458/// has increased.
459///
460/// The standard forbids (at compile time) conversion to and from
461/// virtual bases, which is why we don't have to consider them here.
462///
463/// The standard forbids (at run time) casting a derived MP to a base
464/// MP when the derived MP does not point to a member of the base.
465/// This is why -1 is a reasonable choice for null data member
466/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000467llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000468ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
469 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000470 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000471 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000472 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
473 E->getCastKind() == CK_ReinterpretMemberPointer);
474
475 // Under Itanium, reinterprets don't require any additional processing.
476 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
477
478 // Use constant emission if we can.
479 if (isa<llvm::Constant>(src))
480 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
481
482 llvm::Constant *adj = getMemberPointerAdjustment(E);
483 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000484
485 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000486 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000487
John McCallc62bb392012-02-15 01:22:51 +0000488 const MemberPointerType *destTy =
489 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000490
John McCall7a9aac22010-08-23 01:21:21 +0000491 // For member data pointers, this is just a matter of adding the
492 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000493 if (destTy->isMemberDataPointer()) {
494 llvm::Value *dst;
495 if (isDerivedToBase)
496 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000497 else
John McCallc62bb392012-02-15 01:22:51 +0000498 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000499
500 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000501 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
502 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
503 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000504 }
505
John McCalla1dee5302010-08-22 10:59:02 +0000506 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000507 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000508 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
509 offset <<= 1;
510 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000511 }
512
John McCallc62bb392012-02-15 01:22:51 +0000513 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
514 llvm::Value *dstAdj;
515 if (isDerivedToBase)
516 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000517 else
John McCallc62bb392012-02-15 01:22:51 +0000518 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000519
John McCallc62bb392012-02-15 01:22:51 +0000520 return Builder.CreateInsertValue(src, dstAdj, 1);
521}
522
523llvm::Constant *
524ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
525 llvm::Constant *src) {
526 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
527 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
528 E->getCastKind() == CK_ReinterpretMemberPointer);
529
530 // Under Itanium, reinterprets don't require any additional processing.
531 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
532
533 // If the adjustment is trivial, we don't need to do anything.
534 llvm::Constant *adj = getMemberPointerAdjustment(E);
535 if (!adj) return src;
536
537 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
538
539 const MemberPointerType *destTy =
540 E->getType()->castAs<MemberPointerType>();
541
542 // For member data pointers, this is just a matter of adding the
543 // offset if the source is non-null.
544 if (destTy->isMemberDataPointer()) {
545 // null maps to null.
546 if (src->isAllOnesValue()) return src;
547
548 if (isDerivedToBase)
549 return llvm::ConstantExpr::getNSWSub(src, adj);
550 else
551 return llvm::ConstantExpr::getNSWAdd(src, adj);
552 }
553
554 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000555 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000556 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
557 offset <<= 1;
558 adj = llvm::ConstantInt::get(adj->getType(), offset);
559 }
560
561 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
562 llvm::Constant *dstAdj;
563 if (isDerivedToBase)
564 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
565 else
566 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
567
568 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000569}
John McCall84fa5102010-08-22 04:16:24 +0000570
571llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000572ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000573 // Itanium C++ ABI 2.3:
574 // A NULL pointer is represented as -1.
575 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000576 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000577
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000578 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000579 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000580 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000581}
582
John McCallf3a88602011-02-03 08:15:49 +0000583llvm::Constant *
584ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
585 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000586 // Itanium C++ ABI 2.3:
587 // A pointer to data member is an offset from the base address of
588 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000589 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000590}
591
John McCall2979fe02011-04-12 00:42:48 +0000592llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000593 return BuildMemberPointer(MD, CharUnits::Zero());
594}
595
596llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
597 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000598 assert(MD->isInstance() && "Member function must not be static!");
599 MD = MD->getCanonicalDecl();
600
601 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000602
603 // Get the function pointer (or index if this is a virtual function).
604 llvm::Constant *MemPtr[2];
605 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000606 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000607
Ken Dyckdf016282011-04-09 01:30:02 +0000608 const ASTContext &Context = getContext();
609 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000610 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000611 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000612
Mark Seabornedf0d382013-07-24 16:25:13 +0000613 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000614 // ARM C++ ABI 3.2.1:
615 // This ABI specifies that adj contains twice the this
616 // adjustment, plus 1 if the member function is virtual. The
617 // least significant bit of adj then makes exactly the same
618 // discrimination as the least significant bit of ptr does for
619 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000620 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
621 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000622 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000623 } else {
624 // Itanium C++ ABI 2.3:
625 // For a virtual function, [the pointer field] is 1 plus the
626 // virtual table offset (in bytes) of the function,
627 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000628 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
629 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000630 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000631 }
632 } else {
John McCall2979fe02011-04-12 00:42:48 +0000633 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000634 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000635 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000636 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000637 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000638 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000639 } else {
John McCall2979fe02011-04-12 00:42:48 +0000640 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
641 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000642 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000643 }
John McCall2979fe02011-04-12 00:42:48 +0000644 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000645
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000646 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000647 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
648 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000649 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000650 }
John McCall1c456c82010-08-22 06:43:33 +0000651
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000652 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000653}
654
Richard Smithdafff942012-01-14 04:30:29 +0000655llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
656 QualType MPType) {
657 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
658 const ValueDecl *MPD = MP.getMemberPointerDecl();
659 if (!MPD)
660 return EmitNullMemberPointer(MPT);
661
Reid Kleckner452abac2013-05-09 21:01:17 +0000662 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000663
664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
665 return BuildMemberPointer(MD, ThisAdjustment);
666
667 CharUnits FieldOffset =
668 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
669 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
670}
671
John McCall131d97d2010-08-22 08:30:07 +0000672/// The comparison algorithm is pretty easy: the member pointers are
673/// the same if they're either bitwise identical *or* both null.
674///
675/// ARM is different here only because null-ness is more complicated.
676llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000677ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
678 llvm::Value *L,
679 llvm::Value *R,
680 const MemberPointerType *MPT,
681 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000682 CGBuilderTy &Builder = CGF.Builder;
683
John McCall131d97d2010-08-22 08:30:07 +0000684 llvm::ICmpInst::Predicate Eq;
685 llvm::Instruction::BinaryOps And, Or;
686 if (Inequality) {
687 Eq = llvm::ICmpInst::ICMP_NE;
688 And = llvm::Instruction::Or;
689 Or = llvm::Instruction::And;
690 } else {
691 Eq = llvm::ICmpInst::ICMP_EQ;
692 And = llvm::Instruction::And;
693 Or = llvm::Instruction::Or;
694 }
695
John McCall7a9aac22010-08-23 01:21:21 +0000696 // Member data pointers are easy because there's a unique null
697 // value, so it just comes down to bitwise equality.
698 if (MPT->isMemberDataPointer())
699 return Builder.CreateICmp(Eq, L, R);
700
701 // For member function pointers, the tautologies are more complex.
702 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000703 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000704 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000705 // (L == R) <==> (L.ptr == R.ptr &&
706 // (L.adj == R.adj ||
707 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000708 // The inequality tautologies have exactly the same structure, except
709 // applying De Morgan's laws.
710
711 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
712 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
713
John McCall131d97d2010-08-22 08:30:07 +0000714 // This condition tests whether L.ptr == R.ptr. This must always be
715 // true for equality to hold.
716 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
717
718 // This condition, together with the assumption that L.ptr == R.ptr,
719 // tests whether the pointers are both null. ARM imposes an extra
720 // condition.
721 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
722 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
723
724 // This condition tests whether L.adj == R.adj. If this isn't
725 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000726 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
727 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000728 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
729
730 // Null member function pointers on ARM clear the low bit of Adj,
731 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000732 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000733 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
734
735 // Compute (l.adj | r.adj) & 1 and test it against zero.
736 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
737 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
738 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
739 "cmp.or.adj");
740 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
741 }
742
743 // Tie together all our conditions.
744 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
745 Result = Builder.CreateBinOp(And, PtrEq, Result,
746 Inequality ? "memptr.ne" : "memptr.eq");
747 return Result;
748}
749
750llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000751ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
752 llvm::Value *MemPtr,
753 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000754 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000755
756 /// For member data pointers, this is just a check against -1.
757 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000758 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000759 llvm::Value *NegativeOne =
760 llvm::Constant::getAllOnesValue(MemPtr->getType());
761 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
762 }
John McCall131d97d2010-08-22 08:30:07 +0000763
Daniel Dunbar914bc412011-04-19 23:10:47 +0000764 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000765 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000766
767 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
768 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
769
Daniel Dunbar914bc412011-04-19 23:10:47 +0000770 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
771 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000772 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000773 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000774 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000775 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000776 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
777 "memptr.isvirtual");
778 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000779 }
780
781 return Result;
782}
John McCall1c456c82010-08-22 06:43:33 +0000783
Reid Kleckner40ca9132014-05-13 22:05:45 +0000784bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
785 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
786 if (!RD)
787 return false;
788
Reid Klecknerd355ca72014-05-15 01:26:32 +0000789 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
790 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
791 // special members.
792 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000793 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
794 return true;
795 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000796 return false;
797}
798
John McCall614dbdc2010-08-22 21:01:12 +0000799/// The Itanium ABI requires non-zero initialization only for data
800/// member pointers, for which '0' is a valid offset.
801bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
802 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000803}
John McCall5d865c322010-08-31 07:33:07 +0000804
John McCall82fb8922012-09-25 10:10:39 +0000805/// The Itanium ABI always places an offset to the complete object
806/// at entry -2 in the vtable.
807llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
808 llvm::Value *ptr,
809 QualType type) {
810 // Grab the vtable pointer as an intptr_t*.
811 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
812
813 // Track back to entry -2 and pull out the offset there.
814 llvm::Value *offsetPtr =
815 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
816 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
817 offset->setAlignment(CGF.PointerAlignInBytes);
818
819 // Apply the offset.
820 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
821 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
822}
823
David Majnemer1162d252014-06-22 19:05:33 +0000824static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
825 // void *__dynamic_cast(const void *sub,
826 // const abi::__class_type_info *src,
827 // const abi::__class_type_info *dst,
828 // std::ptrdiff_t src2dst_offset);
829
830 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
831 llvm::Type *PtrDiffTy =
832 CGF.ConvertType(CGF.getContext().getPointerDiffType());
833
834 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
835
836 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
837
838 // Mark the function as nounwind readonly.
839 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
840 llvm::Attribute::ReadOnly };
841 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
842 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
843
844 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
845}
846
847static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
848 // void __cxa_bad_cast();
849 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
850 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
851}
852
853/// \brief Compute the src2dst_offset hint as described in the
854/// Itanium C++ ABI [2.9.7]
855static CharUnits computeOffsetHint(ASTContext &Context,
856 const CXXRecordDecl *Src,
857 const CXXRecordDecl *Dst) {
858 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
859 /*DetectVirtual=*/false);
860
861 // If Dst is not derived from Src we can skip the whole computation below and
862 // return that Src is not a public base of Dst. Record all inheritance paths.
863 if (!Dst->isDerivedFrom(Src, Paths))
864 return CharUnits::fromQuantity(-2ULL);
865
866 unsigned NumPublicPaths = 0;
867 CharUnits Offset;
868
869 // Now walk all possible inheritance paths.
870 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
871 ++I) {
872 if (I->Access != AS_public) // Ignore non-public inheritance.
873 continue;
874
875 ++NumPublicPaths;
876
877 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
878 // If the path contains a virtual base class we can't give any hint.
879 // -1: no hint.
880 if (J->Base->isVirtual())
881 return CharUnits::fromQuantity(-1ULL);
882
883 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
884 continue;
885
886 // Accumulate the base class offsets.
887 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
888 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
889 }
890 }
891
892 // -2: Src is not a public base of Dst.
893 if (NumPublicPaths == 0)
894 return CharUnits::fromQuantity(-2ULL);
895
896 // -3: Src is a multiple public base type but never a virtual base type.
897 if (NumPublicPaths > 1)
898 return CharUnits::fromQuantity(-3ULL);
899
900 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
901 // Return the offset of Src from the origin of Dst.
902 return Offset;
903}
904
905static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
906 // void __cxa_bad_typeid();
907 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
908
909 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
910}
911
912bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
913 QualType SrcRecordTy) {
914 return IsDeref;
915}
916
917void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
918 llvm::Value *Fn = getBadTypeidFn(CGF);
919 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
920 CGF.Builder.CreateUnreachable();
921}
922
923llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
924 QualType SrcRecordTy,
925 llvm::Value *ThisPtr,
926 llvm::Type *StdTypeInfoPtrTy) {
927 llvm::Value *Value =
928 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
929
930 // Load the type info.
931 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
932 return CGF.Builder.CreateLoad(Value);
933}
934
935bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
936 QualType SrcRecordTy) {
937 return SrcIsPtr;
938}
939
940llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
941 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
942 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
943 llvm::Type *PtrDiffLTy =
944 CGF.ConvertType(CGF.getContext().getPointerDiffType());
945 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
946
947 llvm::Value *SrcRTTI =
948 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
949 llvm::Value *DestRTTI =
950 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
951
952 // Compute the offset hint.
953 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
954 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
955 llvm::Value *OffsetHint = llvm::ConstantInt::get(
956 PtrDiffLTy,
957 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
958
959 // Emit the call to __dynamic_cast.
960 Value = CGF.EmitCastToVoidPtr(Value);
961
962 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
963 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
964 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
965
966 /// C++ [expr.dynamic.cast]p9:
967 /// A failed cast to reference type throws std::bad_cast
968 if (DestTy->isReferenceType()) {
969 llvm::BasicBlock *BadCastBlock =
970 CGF.createBasicBlock("dynamic_cast.bad_cast");
971
972 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
973 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
974
975 CGF.EmitBlock(BadCastBlock);
976 EmitBadCastCall(CGF);
977 }
978
979 return Value;
980}
981
982llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
983 llvm::Value *Value,
984 QualType SrcRecordTy,
985 QualType DestTy) {
986 llvm::Type *PtrDiffLTy =
987 CGF.ConvertType(CGF.getContext().getPointerDiffType());
988 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
989
990 // Get the vtable pointer.
991 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
992
993 // Get the offset-to-top from the vtable.
994 llvm::Value *OffsetToTop =
995 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
996 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
997
998 // Finally, add the offset to the pointer.
999 Value = CGF.EmitCastToVoidPtr(Value);
1000 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1001
1002 return CGF.Builder.CreateBitCast(Value, DestLTy);
1003}
1004
1005bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1006 llvm::Value *Fn = getBadCastFn(CGF);
1007 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1008 CGF.Builder.CreateUnreachable();
1009 return true;
1010}
1011
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001012llvm::Value *
1013ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1014 llvm::Value *This,
1015 const CXXRecordDecl *ClassDecl,
1016 const CXXRecordDecl *BaseClassDecl) {
1017 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1018 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001019 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1020 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001021
1022 llvm::Value *VBaseOffsetPtr =
1023 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1024 "vbase.offset.ptr");
1025 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1026 CGM.PtrDiffTy->getPointerTo());
1027
1028 llvm::Value *VBaseOffset =
1029 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1030
1031 return VBaseOffset;
1032}
1033
John McCall5d865c322010-08-31 07:33:07 +00001034/// The generic ABI passes 'this', plus a VTT if it's initializing a
1035/// base subobject.
Reid Kleckner89077a12013-12-17 19:46:40 +00001036void
1037ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
1038 CXXCtorType Type, CanQualType &ResTy,
1039 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001040 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001041
Reid Kleckner89077a12013-12-17 19:46:40 +00001042 // All parameters are already in place except VTT, which goes after 'this'.
1043 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001044
1045 // Check if we need to add a VTT parameter (which has type void **).
1046 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
Reid Kleckner89077a12013-12-17 19:46:40 +00001047 ArgTys.insert(ArgTys.begin() + 1,
1048 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001049}
1050
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001051void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1052 // Just make sure we're in sync with TargetCXXABI.
1053 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1054
Rafael Espindolac3cde362013-12-09 14:51:17 +00001055 // The constructor used for constructing this as a base class;
1056 // ignores virtual bases.
1057 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1058
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001059 // The constructor used for constructing this as a complete class;
1060 // constucts the virtual bases, then calls the base constructor.
1061 if (!D->getParent()->isAbstract()) {
1062 // We don't need to emit the complete ctor if the class is abstract.
1063 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1064 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001065}
1066
John McCall5d865c322010-08-31 07:33:07 +00001067/// The generic ABI passes 'this', plus a VTT if it's destroying a
1068/// base subobject.
1069void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
1070 CXXDtorType Type,
1071 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001073 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001074
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001075 // 'this' parameter is already there, as well as 'this' return if
1076 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +00001077
1078 // Check if we need to add a VTT parameter (which has type void **).
1079 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
1080 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
1081}
1082
Reid Klecknere7de47e2013-07-22 13:51:44 +00001083void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001084 // The destructor used for destructing this as a base class; ignores
1085 // virtual bases.
1086 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001087
1088 // The destructor used for destructing this as a most-derived class;
1089 // call the base destructor and then destructs any virtual bases.
1090 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1091
Rafael Espindolac3cde362013-12-09 14:51:17 +00001092 // The destructor in a virtual table is always a 'deleting'
1093 // destructor, which calls the complete destructor and then uses the
1094 // appropriate operator delete.
1095 if (D->isVirtual())
1096 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001097}
1098
Reid Kleckner89077a12013-12-17 19:46:40 +00001099void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1100 QualType &ResTy,
1101 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001102 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001103 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001104
1105 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001106 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001107 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001108
1109 // FIXME: avoid the fake decl
1110 QualType T = Context.getPointerType(Context.VoidPtrTy);
1111 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001112 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001113 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001114 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001115 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001116 }
1117}
1118
John McCall5d865c322010-08-31 07:33:07 +00001119void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1120 /// Initialize the 'this' slot.
1121 EmitThisParam(CGF);
1122
1123 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001124 if (getStructorImplicitParamDecl(CGF)) {
1125 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1126 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001127 }
John McCall5d865c322010-08-31 07:33:07 +00001128
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001129 /// If this is a function that the ABI specifies returns 'this', initialize
1130 /// the return slot to 'this' at the start of the function.
1131 ///
1132 /// Unlike the setting of return types, this is done within the ABI
1133 /// implementation instead of by clients of CGCXXABI because:
1134 /// 1) getThisValue is currently protected
1135 /// 2) in theory, an ABI could implement 'this' returns some other way;
1136 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001137 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001138 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001139}
1140
Reid Kleckner89077a12013-12-17 19:46:40 +00001141unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1142 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1143 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1144 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1145 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001146
Reid Kleckner89077a12013-12-17 19:46:40 +00001147 // Insert the implicit 'vtt' argument as the second argument.
1148 llvm::Value *VTT =
1149 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1150 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1151 Args.insert(Args.begin() + 1,
1152 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1153 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001154}
1155
1156void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1157 const CXXDestructorDecl *DD,
1158 CXXDtorType Type, bool ForVirtualBase,
1159 bool Delegating, llvm::Value *This) {
1160 GlobalDecl GD(DD, Type);
1161 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1162 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1163
Craig Topper8a13c412014-05-21 05:09:00 +00001164 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001165 if (getContext().getLangOpts().AppleKext)
1166 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1167
1168 if (!Callee)
1169 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1170
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001171 // FIXME: Provide a source location here.
1172 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Craig Topper8a13c412014-05-21 05:09:00 +00001173 VTT, VTTTy, nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001174}
1175
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001176void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1177 const CXXRecordDecl *RD) {
1178 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1179 if (VTable->hasInitializer())
1180 return;
1181
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001182 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001183 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1184 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001185 llvm::Constant *RTTI =
1186 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001187
1188 // Create and set the initializer.
1189 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1190 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001191 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001192 VTable->setInitializer(Init);
1193
1194 // Set the correct linkage.
1195 VTable->setLinkage(Linkage);
1196
1197 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001198 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001199
1200 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1201 // we will emit the typeinfo for the fundamental types. This is the
1202 // same behaviour as GCC.
1203 const DeclContext *DC = RD->getDeclContext();
1204 if (RD->getIdentifier() &&
1205 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1206 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1207 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1208 DC->getParent()->isTranslationUnit())
1209 CGM.EmitFundamentalRTTIDescriptors();
1210}
1211
1212llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1213 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1214 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1215 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1216 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1217
1218 llvm::Value *VTableAddressPoint;
1219 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1220 // Get the secondary vpointer index.
1221 uint64_t VirtualPointerIndex =
1222 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1223
1224 /// Load the VTT.
1225 llvm::Value *VTT = CGF.LoadCXXVTT();
1226 if (VirtualPointerIndex)
1227 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1228
1229 // And load the address point from the VTT.
1230 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1231 } else {
1232 llvm::Constant *VTable =
1233 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001234 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1235 .getVTableLayout(VTableClass)
1236 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001237 VTableAddressPoint =
1238 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1239 }
1240
1241 return VTableAddressPoint;
1242}
1243
1244llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1245 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1246 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1247
1248 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001249 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1250 .getVTableLayout(VTableClass)
1251 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001252 llvm::Value *Indices[] = {
1253 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1254 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1255 };
1256
1257 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1258}
1259
1260llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1261 CharUnits VPtrOffset) {
1262 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1263
1264 llvm::GlobalVariable *&VTable = VTables[RD];
1265 if (VTable)
1266 return VTable;
1267
1268 // Queue up this v-table for possible deferred emission.
1269 CGM.addDeferredVTable(RD);
1270
1271 SmallString<256> OutName;
1272 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001273 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001274 Out.flush();
1275 StringRef Name = OutName.str();
1276
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001277 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001278 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1279 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1280
1281 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1282 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1283 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001284
1285 if (RD->hasAttr<DLLImportAttr>())
1286 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1287 else if (RD->hasAttr<DLLExportAttr>())
1288 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1289
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001290 return VTable;
1291}
1292
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001293llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1294 GlobalDecl GD,
1295 llvm::Value *This,
1296 llvm::Type *Ty) {
1297 GD = GD.getCanonicalDecl();
1298 Ty = Ty->getPointerTo()->getPointerTo();
1299 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1300
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001301 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001302 llvm::Value *VFuncPtr =
1303 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1304 return CGF.Builder.CreateLoad(VFuncPtr);
1305}
1306
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001307void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1308 const CXXDestructorDecl *Dtor,
1309 CXXDtorType DtorType,
1310 SourceLocation CallLoc,
1311 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001312 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1313
1314 const CGFunctionInfo *FInfo
1315 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1316 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001317 llvm::Value *Callee =
1318 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001319
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001320 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Craig Topper8a13c412014-05-21 05:09:00 +00001321 /*ImplicitParam=*/nullptr, QualType(), nullptr,
1322 nullptr);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001323}
1324
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001325void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001326 CodeGenVTables &VTables = CGM.getVTables();
1327 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001328 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001329}
1330
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001331static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1332 llvm::Value *Ptr,
1333 int64_t NonVirtualAdjustment,
1334 int64_t VirtualAdjustment,
1335 bool IsReturnAdjustment) {
1336 if (!NonVirtualAdjustment && !VirtualAdjustment)
1337 return Ptr;
1338
1339 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1340 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1341
1342 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1343 // Perform the non-virtual adjustment for a base-to-derived cast.
1344 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1345 }
1346
1347 if (VirtualAdjustment) {
1348 llvm::Type *PtrDiffTy =
1349 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1350
1351 // Perform the virtual adjustment.
1352 llvm::Value *VTablePtrPtr =
1353 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1354
1355 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1356
1357 llvm::Value *OffsetPtr =
1358 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1359
1360 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1361
1362 // Load the adjustment offset from the vtable.
1363 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1364
1365 // Adjust our pointer.
1366 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1367 }
1368
1369 if (NonVirtualAdjustment && IsReturnAdjustment) {
1370 // Perform the non-virtual adjustment for a derived-to-base cast.
1371 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1372 }
1373
1374 // Cast back to the original type.
1375 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1376}
1377
1378llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1379 llvm::Value *This,
1380 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001381 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1382 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001383 /*IsReturnAdjustment=*/false);
1384}
1385
1386llvm::Value *
1387ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1388 const ReturnAdjustment &RA) {
1389 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1390 RA.Virtual.Itanium.VBaseOffsetOffset,
1391 /*IsReturnAdjustment=*/true);
1392}
1393
John McCall5d865c322010-08-31 07:33:07 +00001394void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1395 RValue RV, QualType ResultType) {
1396 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1397 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1398
1399 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001400 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001401 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1402 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1403 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1404}
John McCall8ed55a52010-09-02 09:58:18 +00001405
1406/************************** Array allocation cookies **************************/
1407
John McCallb91cd662012-05-01 05:23:51 +00001408CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1409 // The array cookie is a size_t; pad that up to the element alignment.
1410 // The cookie is actually right-justified in that space.
1411 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1412 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001413}
1414
1415llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1416 llvm::Value *NewPtr,
1417 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001418 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001419 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001420 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001421
Micah Villmowea2fea22012-10-25 15:39:14 +00001422 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001423
John McCall9bca9232010-09-02 10:25:57 +00001424 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001425 QualType SizeTy = Ctx.getSizeType();
1426 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1427
1428 // The size of the cookie.
1429 CharUnits CookieSize =
1430 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001431 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001432
1433 // Compute an offset to the cookie.
1434 llvm::Value *CookiePtr = NewPtr;
1435 CharUnits CookieOffset = CookieSize - SizeSize;
1436 if (!CookieOffset.isZero())
1437 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1438 CookieOffset.getQuantity());
1439
1440 // Write the number of elements into the appropriate slot.
1441 llvm::Value *NumElementsPtr
1442 = CGF.Builder.CreateBitCast(CookiePtr,
1443 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1444 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1445
1446 // Finally, compute a pointer to the actual data buffer by skipping
1447 // over the cookie completely.
1448 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1449 CookieSize.getQuantity());
1450}
1451
John McCallb91cd662012-05-01 05:23:51 +00001452llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1453 llvm::Value *allocPtr,
1454 CharUnits cookieSize) {
1455 // The element size is right-justified in the cookie.
1456 llvm::Value *numElementsPtr = allocPtr;
1457 CharUnits numElementsOffset =
1458 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1459 if (!numElementsOffset.isZero())
1460 numElementsPtr =
1461 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1462 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001463
Micah Villmowea2fea22012-10-25 15:39:14 +00001464 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001465 numElementsPtr =
1466 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1467 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001468}
1469
John McCallb91cd662012-05-01 05:23:51 +00001470CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001471 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001472 // struct array_cookie {
1473 // std::size_t element_size; // element_size != 0
1474 // std::size_t element_count;
1475 // };
John McCallc19c7062013-01-25 23:36:19 +00001476 // But the base ABI doesn't give anything an alignment greater than
1477 // 8, so we can dismiss this as typical ABI-author blindness to
1478 // actual language complexity and round up to the element alignment.
1479 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1480 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001481}
1482
1483llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001484 llvm::Value *newPtr,
1485 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001486 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001487 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001488 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001489
John McCallc19c7062013-01-25 23:36:19 +00001490 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1491 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001492
1493 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001494 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001495
1496 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001497 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1498 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1499 getContext().getTypeSizeInChars(elementType).getQuantity());
1500 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001501
1502 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001503 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1504 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001505
1506 // Finally, compute a pointer to the actual data buffer by skipping
1507 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001508 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1509 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1510 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001511}
1512
John McCallb91cd662012-05-01 05:23:51 +00001513llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1514 llvm::Value *allocPtr,
1515 CharUnits cookieSize) {
1516 // The number of elements is at offset sizeof(size_t) relative to
1517 // the allocated pointer.
1518 llvm::Value *numElementsPtr
1519 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001520
Micah Villmowea2fea22012-10-25 15:39:14 +00001521 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001522 numElementsPtr =
1523 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1524 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001525}
1526
John McCall68ff0372010-09-08 01:44:27 +00001527/*********************** Static local initialization **************************/
1528
1529static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001530 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001531 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001532 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001533 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001534 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001535 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001536 llvm::AttributeSet::get(CGM.getLLVMContext(),
1537 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001538 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001539}
1540
1541static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001542 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001543 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001544 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001545 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001546 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001547 llvm::AttributeSet::get(CGM.getLLVMContext(),
1548 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001549 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001550}
1551
1552static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001553 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001554 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001555 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001556 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001557 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001558 llvm::AttributeSet::get(CGM.getLLVMContext(),
1559 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001560 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001561}
1562
1563namespace {
1564 struct CallGuardAbort : EHScopeStack::Cleanup {
1565 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001566 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001567
Craig Topper4f12f102014-03-12 06:41:41 +00001568 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001569 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1570 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001571 }
1572 };
1573}
1574
1575/// The ARM code here follows the Itanium code closely enough that we
1576/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001577void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1578 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001579 llvm::GlobalVariable *var,
1580 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001581 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001582
Richard Smithdbf74ba2013-04-14 23:01:42 +00001583 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001584 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001585 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1586 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001587
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001588 // If we have a global variable with internal linkage and thread-safe statics
1589 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001590 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1591
1592 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001593 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001594 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001595 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001596 // Guard variables are 64 bits in the generic ABI and size width on ARM
1597 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001598 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001599 }
John McCallb88a5662012-03-30 21:00:39 +00001600 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001601
John McCallb88a5662012-03-30 21:00:39 +00001602 // Create the guard variable if we don't already have it (as we
1603 // might if we're double-emitting this function body).
1604 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1605 if (!guard) {
1606 // Mangle the name for the guard.
1607 SmallString<256> guardName;
1608 {
1609 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001610 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001611 out.flush();
1612 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001613
John McCallb88a5662012-03-30 21:00:39 +00001614 // Create the guard variable with a zero-initializer.
1615 // Just absorb linkage and visibility from the guarded variable.
1616 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1617 false, var->getLinkage(),
1618 llvm::ConstantInt::get(guardTy, 0),
1619 guardName.str());
1620 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001621 // If the variable is thread-local, so is its guard variable.
1622 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001623
1624 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1625 }
John McCall87590e62012-03-30 07:09:50 +00001626
John McCall68ff0372010-09-08 01:44:27 +00001627 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001628 //
John McCall68ff0372010-09-08 01:44:27 +00001629 // Itanium C++ ABI 3.3.2:
1630 // The following is pseudo-code showing how these functions can be used:
1631 // if (obj_guard.first_byte == 0) {
1632 // if ( __cxa_guard_acquire (&obj_guard) ) {
1633 // try {
1634 // ... initialize the object ...;
1635 // } catch (...) {
1636 // __cxa_guard_abort (&obj_guard);
1637 // throw;
1638 // }
1639 // ... queue object destructor with __cxa_atexit() ...;
1640 // __cxa_guard_release (&obj_guard);
1641 // }
1642 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001643
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001644 // Load the first byte of the guard variable.
1645 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001646 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001647 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001648
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001649 // Itanium ABI:
1650 // An implementation supporting thread-safety on multiprocessor
1651 // systems must also guarantee that references to the initialized
1652 // object do not occur before the load of the initialization flag.
1653 //
1654 // In LLVM, we do this by marking the load Acquire.
1655 if (threadsafe)
1656 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001657
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001658 // For ARM, we should only check the first bit, rather than the entire byte:
1659 //
1660 // ARM C++ ABI 3.2.3.1:
1661 // To support the potential use of initialization guard variables
1662 // as semaphores that are the target of ARM SWP and LDREX/STREX
1663 // synchronizing instructions we define a static initialization
1664 // guard variable to be a 4-byte aligned, 4-byte word with the
1665 // following inline access protocol.
1666 // #define INITIALIZED 1
1667 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1668 // if (__cxa_guard_acquire(&obj_guard))
1669 // ...
1670 // }
1671 //
1672 // and similarly for ARM64:
1673 //
1674 // ARM64 C++ ABI 3.2.2:
1675 // This ABI instead only specifies the value bit 0 of the static guard
1676 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1677 // variable is not initialized and 1 when it is.
1678 llvm::Value *V =
1679 (UseARMGuardVarABI && !useInt8GuardVariable)
1680 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1681 : LI;
1682 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001683
1684 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1685 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1686
1687 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001688 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001689
1690 CGF.EmitBlock(InitCheckBlock);
1691
1692 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001693 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001694 // Call __cxa_guard_acquire.
1695 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001696 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001697
1698 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1699
1700 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1701 InitBlock, EndBlock);
1702
1703 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001704 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001705
1706 CGF.EmitBlock(InitBlock);
1707 }
1708
1709 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001710 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001711
John McCall5aa52592011-06-17 07:33:57 +00001712 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001713 // Pop the guard-abort cleanup if we pushed one.
1714 CGF.PopCleanupBlock();
1715
1716 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001717 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001718 } else {
John McCallb88a5662012-03-30 21:00:39 +00001719 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001720 }
1721
1722 CGF.EmitBlock(EndBlock);
1723}
John McCallc84ed6a2012-05-01 06:13:13 +00001724
1725/// Register a global destructor using __cxa_atexit.
1726static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1727 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001728 llvm::Constant *addr,
1729 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001730 const char *Name = "__cxa_atexit";
1731 if (TLS) {
1732 const llvm::Triple &T = CGF.getTarget().getTriple();
1733 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1734 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001735
John McCallc84ed6a2012-05-01 06:13:13 +00001736 // We're assuming that the destructor function is something we can
1737 // reasonably call with the default CC. Go ahead and cast it to the
1738 // right prototype.
1739 llvm::Type *dtorTy =
1740 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1741
1742 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1743 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1744 llvm::FunctionType *atexitTy =
1745 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1746
1747 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001748 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001749 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1750 fn->setDoesNotThrow();
1751
1752 // Create a variable that binds the atexit to this shared object.
1753 llvm::Constant *handle =
1754 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1755
1756 llvm::Value *args[] = {
1757 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1758 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1759 handle
1760 };
John McCall882987f2013-02-28 19:01:20 +00001761 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001762}
1763
1764/// Register a global destructor as best as we know how.
1765void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001766 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001767 llvm::Constant *dtor,
1768 llvm::Constant *addr) {
1769 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001770 if (CGM.getCodeGenOpts().CXAAtExit)
1771 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1772
1773 if (D.getTLSKind())
1774 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001775
1776 // In Apple kexts, we want to add a global destructor entry.
1777 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001778 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001779 // Generate a global destructor entry.
1780 return CGM.AddCXXDtorEntry(dtor, addr);
1781 }
1782
David Blaikieebe87e12013-08-27 23:57:18 +00001783 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001784}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001785
1786/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001787/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001788/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001789static llvm::GlobalValue::LinkageTypes
1790getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1791 llvm::GlobalValue::LinkageTypes VarLinkage =
1792 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1793
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001794 // For internal linkage variables, we don't need an external or weak wrapper.
1795 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1796 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001797
1798 // All accesses to the thread_local variable go through the thread wrapper.
1799 // However, this means that we cannot allow the thread wrapper to get inlined
1800 // into any functions.
1801 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1802 CGM.getTarget().getTriple().isMacOSX())
1803 return llvm::GlobalValue::WeakAnyLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001804 return llvm::GlobalValue::WeakODRLinkage;
1805}
1806
1807llvm::Function *
1808ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1809 llvm::GlobalVariable *Var) {
1810 // Mangle the name for the thread_local wrapper function.
1811 SmallString<256> WrapperName;
1812 {
1813 llvm::raw_svector_ostream Out(WrapperName);
1814 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1815 Out.flush();
1816 }
1817
1818 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1819 return cast<llvm::Function>(V);
1820
1821 llvm::Type *RetTy = Var->getType();
1822 if (VD->getType()->isReferenceType())
1823 RetTy = RetTy->getPointerElementType();
1824
1825 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001826 llvm::Function *Wrapper =
1827 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1828 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001829 // Always resolve references to the wrapper at link time.
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001830 if (!Wrapper->hasLocalLinkage())
1831 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001832 return Wrapper;
1833}
1834
1835void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +00001836 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001837 llvm::Function *InitFunc) {
1838 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1839 const VarDecl *VD = Decls[I].first;
1840 llvm::GlobalVariable *Var = Decls[I].second;
1841
1842 // Mangle the name for the thread_local initialization function.
1843 SmallString<256> InitFnName;
1844 {
1845 llvm::raw_svector_ostream Out(InitFnName);
1846 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1847 Out.flush();
1848 }
1849
1850 // If we have a definition for the variable, emit the initialization
1851 // function as an alias to the global Init function (if any). Otherwise,
1852 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001853 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001854 bool InitIsInitFunc = false;
1855 if (VD->hasDefinition()) {
1856 InitIsInitFunc = true;
1857 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001858 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1859 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001860 } else {
1861 // Emit a weak global function referring to the initialization function.
1862 // This function will not exist if the TU defining the thread_local
1863 // variable in question does not need any dynamic initialization for
1864 // its thread_local variables.
1865 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1866 Init = llvm::Function::Create(
1867 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1868 &CGM.getModule());
1869 }
1870
1871 if (Init)
1872 Init->setVisibility(Var->getVisibility());
1873
1874 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1875 llvm::LLVMContext &Context = CGM.getModule().getContext();
1876 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1877 CGBuilderTy Builder(Entry);
1878 if (InitIsInitFunc) {
1879 if (Init)
1880 Builder.CreateCall(Init);
1881 } else {
1882 // Don't know whether we have an init function. Call it if it exists.
1883 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1884 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1885 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1886 Builder.CreateCondBr(Have, InitBB, ExitBB);
1887
1888 Builder.SetInsertPoint(InitBB);
1889 Builder.CreateCall(Init);
1890 Builder.CreateBr(ExitBB);
1891
1892 Builder.SetInsertPoint(ExitBB);
1893 }
1894
1895 // For a reference, the result of the wrapper function is a pointer to
1896 // the referenced object.
1897 llvm::Value *Val = Var;
1898 if (VD->getType()->isReferenceType()) {
1899 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1900 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1901 Val = LI;
1902 }
1903
1904 Builder.CreateRet(Val);
1905 }
1906}
1907
Richard Smith0f383742014-03-26 22:48:22 +00001908LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1909 const VarDecl *VD,
1910 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001911 QualType T = VD->getType();
1912 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1913 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1914 llvm::Function *Wrapper =
1915 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1916
1917 Val = CGF.Builder.CreateCall(Wrapper);
1918
1919 LValue LV;
1920 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001921 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001922 else
Richard Smith0f383742014-03-26 22:48:22 +00001923 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001924 // FIXME: need setObjCGCLValueClass?
1925 return LV;
1926}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001927
1928/// Return whether the given global decl needs a VTT parameter, which it does
1929/// if it's a base constructor or destructor with virtual bases.
1930bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1931 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1932
1933 // We don't have any virtual bases, just return early.
1934 if (!MD->getParent()->getNumVBases())
1935 return false;
1936
1937 // Check if we have a base constructor.
1938 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1939 return true;
1940
1941 // Check if we have a base destructor.
1942 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1943 return true;
1944
1945 return false;
1946}