blob: 877d32cc5f803b2aaee9182424193702c2b1f81d [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 Majnemere2cb8d12014-07-07 06:20:47 +0000112 void EmitFundamentalRTTIDescriptor(QualType Type);
113 void EmitFundamentalRTTIDescriptors();
114 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
115
David Majnemer1162d252014-06-22 19:05:33 +0000116 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
117 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
118 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
119 llvm::Value *ThisPtr,
120 llvm::Type *StdTypeInfoPtrTy) override;
121
122 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
123 QualType SrcRecordTy) override;
124
125 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
126 QualType SrcRecordTy, QualType DestTy,
127 QualType DestRecordTy,
128 llvm::BasicBlock *CastEnd) override;
129
130 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
131 QualType SrcRecordTy,
132 QualType DestTy) override;
133
134 bool EmitBadCastCall(CodeGenFunction &CGF) override;
135
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Value *
137 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
138 const CXXRecordDecl *ClassDecl,
139 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000140
Craig Topper4f12f102014-03-12 06:41:41 +0000141 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000142
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000143 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
144 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000145
Reid Klecknere7de47e2013-07-22 13:51:44 +0000146 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000148 // Itanium does not emit any destructor variant as an inline thunk.
149 // Delegating may occur as an optimization, but all variants are either
150 // emitted with external linkage or as linkonce if they are inline and used.
151 return false;
152 }
153
Craig Topper4f12f102014-03-12 06:41:41 +0000154 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000155
Reid Kleckner89077a12013-12-17 19:46:40 +0000156 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000157 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000158
Craig Topper4f12f102014-03-12 06:41:41 +0000159 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000160
Reid Kleckner89077a12013-12-17 19:46:40 +0000161 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
162 const CXXConstructorDecl *D,
163 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000164 bool Delegating,
165 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000166
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
168 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000169 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000170
Craig Topper4f12f102014-03-12 06:41:41 +0000171 void emitVTableDefinitions(CodeGenVTables &CGVT,
172 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000173
174 llvm::Value *getVTableAddressPointInStructor(
175 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
176 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000177 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000178
179 llvm::Constant *
180 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000181 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000182
183 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000184 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000185
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000186 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 llvm::Value *This,
188 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000189
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000190 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
191 const CXXDestructorDecl *Dtor,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000192 CXXDtorType DtorType, llvm::Value *This,
193 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000194
Craig Topper4f12f102014-03-12 06:41:41 +0000195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000196
Hans Wennborgc94391d2014-06-06 20:04:01 +0000197 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
198 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000199 // Allow inlining of thunks by emitting them with available_externally
200 // linkage together with vtables when needed.
201 if (ForVTable)
202 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
203 }
204
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000205 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000207
208 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000209 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000210
David Majnemer196ac332014-09-11 23:05:02 +0000211 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
212 FunctionArgList &Args) const override {
213 assert(!Args.empty() && "expected the arglist to not be empty!");
214 return Args.size() - 1;
215 }
216
Craig Topper4f12f102014-03-12 06:41:41 +0000217 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
218 StringRef GetDeletedVirtualCallName() override
219 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000220
Craig Topper4f12f102014-03-12 06:41:41 +0000221 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000222 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
223 llvm::Value *NewPtr,
224 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000225 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000226 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000227 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
228 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000230
John McCallcdf7ef52010-11-06 09:44:32 +0000231 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000232 llvm::GlobalVariable *DeclPtr,
233 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000234 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000235 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000236
237 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
238 llvm::GlobalVariable *Var);
239 void EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +0000240 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000241 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000242 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
243 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000244
Craig Topper4f12f102014-03-12 06:41:41 +0000245 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000246
247 /**************************** RTTI Uniqueness ******************************/
248
249protected:
250 /// Returns true if the ABI requires RTTI type_info objects to be unique
251 /// across a program.
252 virtual bool shouldRTTIBeUnique() const { return true; }
253
254public:
255 /// What sort of unique-RTTI behavior should we use?
256 enum RTTIUniquenessKind {
257 /// We are guaranteeing, or need to guarantee, that the RTTI string
258 /// is unique.
259 RUK_Unique,
260
261 /// We are not guaranteeing uniqueness for the RTTI string, so we
262 /// can demote to hidden visibility but must use string comparisons.
263 RUK_NonUniqueHidden,
264
265 /// We are not guaranteeing uniqueness for the RTTI string, so we
266 /// have to use string comparisons, but we also have to emit it with
267 /// non-hidden visibility.
268 RUK_NonUniqueVisible
269 };
270
271 /// Return the required visibility status for the given type and linkage in
272 /// the current ABI.
273 RTTIUniquenessKind
274 classifyRTTIUniqueness(QualType CanTy,
275 llvm::GlobalValue::LinkageTypes Linkage) const;
276 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000277
278 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000279};
John McCall86353412010-08-21 22:46:04 +0000280
281class ARMCXXABI : public ItaniumCXXABI {
282public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000283 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
284 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
285 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000286
Craig Topper4f12f102014-03-12 06:41:41 +0000287 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000288 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
289 isa<CXXDestructorDecl>(GD.getDecl()) &&
290 GD.getDtorType() != Dtor_Deleting));
291 }
John McCall5d865c322010-08-31 07:33:07 +0000292
Craig Topper4f12f102014-03-12 06:41:41 +0000293 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
294 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000295
Craig Topper4f12f102014-03-12 06:41:41 +0000296 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000297 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
298 llvm::Value *NewPtr,
299 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000300 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000301 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000302 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000303 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000304};
Tim Northovera2ee4332014-03-29 15:09:45 +0000305
306class iOS64CXXABI : public ARMCXXABI {
307public:
308 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000309
310 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000311 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000312};
Charles Davis4e786dd2010-05-25 19:52:27 +0000313}
314
Charles Davis53c59df2010-08-16 03:33:14 +0000315CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000316 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000317 // For IR-generation purposes, there's no significant difference
318 // between the ARM and iOS ABIs.
319 case TargetCXXABI::GenericARM:
320 case TargetCXXABI::iOS:
321 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000322
Tim Northovera2ee4332014-03-29 15:09:45 +0000323 case TargetCXXABI::iOS64:
324 return new iOS64CXXABI(CGM);
325
Tim Northover9bb857a2013-01-31 12:13:10 +0000326 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
327 // include the other 32-bit ARM oddities: constructor/destructor return values
328 // and array cookies.
329 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000330 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
331 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000332
John McCall57625922013-01-25 23:36:14 +0000333 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000334 if (CGM.getContext().getTargetInfo().getTriple().getArch()
335 == llvm::Triple::le32) {
336 // For PNaCl, use ARM-style method pointers so that PNaCl code
337 // does not assume anything about the alignment of function
338 // pointers.
339 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
340 /* UseARMGuardVarABI = */ false);
341 }
John McCall57625922013-01-25 23:36:14 +0000342 return new ItaniumCXXABI(CGM);
343
344 case TargetCXXABI::Microsoft:
345 llvm_unreachable("Microsoft ABI is not Itanium-based");
346 }
347 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000348}
349
Chris Lattnera5f58b02011-07-09 17:41:47 +0000350llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000351ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
352 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000353 return CGM.PtrDiffTy;
354 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000355}
356
John McCalld9c6c0b2010-08-22 00:59:17 +0000357/// In the Itanium and ARM ABIs, method pointers have the form:
358/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
359///
360/// In the Itanium ABI:
361/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
362/// - the this-adjustment is (memptr.adj)
363/// - the virtual offset is (memptr.ptr - 1)
364///
365/// In the ARM ABI:
366/// - method pointers are virtual if (memptr.adj & 1) is nonzero
367/// - the this-adjustment is (memptr.adj >> 1)
368/// - the virtual offset is (memptr.ptr)
369/// ARM uses 'adj' for the virtual flag because Thumb functions
370/// may be only single-byte aligned.
371///
372/// If the member is virtual, the adjusted 'this' pointer points
373/// to a vtable pointer from which the virtual offset is applied.
374///
375/// If the member is non-virtual, memptr.ptr is the address of
376/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000377llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
378 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
379 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000380 CGBuilderTy &Builder = CGF.Builder;
381
382 const FunctionProtoType *FPT =
383 MPT->getPointeeType()->getAs<FunctionProtoType>();
384 const CXXRecordDecl *RD =
385 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
386
Chris Lattner2192fe52011-07-18 04:24:23 +0000387 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000388 CGM.getTypes().GetFunctionType(
389 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000390
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000391 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000392
John McCalld9c6c0b2010-08-22 00:59:17 +0000393 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
394 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
395 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
396
John McCalla1dee5302010-08-22 10:59:02 +0000397 // Extract memptr.adj, which is in the second field.
398 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000399
400 // Compute the true adjustment.
401 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000402 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000403 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000404
405 // Apply the adjustment and cast back to the original struct type
406 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000407 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
408 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
409 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000410
411 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000412 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000413
414 // If the LSB in the function pointer is 1, the function pointer points to
415 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000416 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000417 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000418 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
419 else
420 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
421 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000422 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
423
424 // In the virtual path, the adjustment left 'This' pointing to the
425 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000426 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000427 CGF.EmitBlock(FnVirtual);
428
429 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000430 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000431 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000432
433 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000434 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000435 if (!UseARMMethodPtrABI)
436 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000437 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000438
439 // Load the virtual function to call.
440 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000441 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000442 CGF.EmitBranch(FnEnd);
443
444 // In the non-virtual path, the function pointer is actually a
445 // function pointer.
446 CGF.EmitBlock(FnNonVirtual);
447 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000448 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000449
450 // We're done.
451 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000452 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000453 Callee->addIncoming(VirtualFn, FnVirtual);
454 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
455 return Callee;
456}
John McCalla8bbb822010-08-22 03:04:22 +0000457
John McCallc134eb52010-08-31 21:07:20 +0000458/// Compute an l-value by applying the given pointer-to-member to a
459/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000460llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
461 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
462 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000463 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000464
465 CGBuilderTy &Builder = CGF.Builder;
466
Micah Villmowea2fea22012-10-25 15:39:14 +0000467 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000468
469 // Cast to char*.
470 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
471
472 // Apply the offset, which we assume is non-null.
473 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
474
475 // Cast the address to the appropriate pointer type, adopting the
476 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000477 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000478 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000479 return Builder.CreateBitCast(Addr, PType);
480}
481
John McCallc62bb392012-02-15 01:22:51 +0000482/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
483/// conversion.
484///
485/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000486///
487/// Obligatory offset/adjustment diagram:
488/// <-- offset --> <-- adjustment -->
489/// |--------------------------|----------------------|--------------------|
490/// ^Derived address point ^Base address point ^Member address point
491///
492/// So when converting a base member pointer to a derived member pointer,
493/// we add the offset to the adjustment because the address point has
494/// decreased; and conversely, when converting a derived MP to a base MP
495/// we subtract the offset from the adjustment because the address point
496/// has increased.
497///
498/// The standard forbids (at compile time) conversion to and from
499/// virtual bases, which is why we don't have to consider them here.
500///
501/// The standard forbids (at run time) casting a derived MP to a base
502/// MP when the derived MP does not point to a member of the base.
503/// This is why -1 is a reasonable choice for null data member
504/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000505llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000506ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
507 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000508 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000509 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000510 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
511 E->getCastKind() == CK_ReinterpretMemberPointer);
512
513 // Under Itanium, reinterprets don't require any additional processing.
514 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
515
516 // Use constant emission if we can.
517 if (isa<llvm::Constant>(src))
518 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
519
520 llvm::Constant *adj = getMemberPointerAdjustment(E);
521 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000522
523 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000524 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000525
John McCallc62bb392012-02-15 01:22:51 +0000526 const MemberPointerType *destTy =
527 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000528
John McCall7a9aac22010-08-23 01:21:21 +0000529 // For member data pointers, this is just a matter of adding the
530 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000531 if (destTy->isMemberDataPointer()) {
532 llvm::Value *dst;
533 if (isDerivedToBase)
534 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000535 else
John McCallc62bb392012-02-15 01:22:51 +0000536 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000537
538 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000539 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
540 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
541 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000542 }
543
John McCalla1dee5302010-08-22 10:59:02 +0000544 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000545 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000546 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
547 offset <<= 1;
548 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000549 }
550
John McCallc62bb392012-02-15 01:22:51 +0000551 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
552 llvm::Value *dstAdj;
553 if (isDerivedToBase)
554 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000555 else
John McCallc62bb392012-02-15 01:22:51 +0000556 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000557
John McCallc62bb392012-02-15 01:22:51 +0000558 return Builder.CreateInsertValue(src, dstAdj, 1);
559}
560
561llvm::Constant *
562ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
563 llvm::Constant *src) {
564 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
565 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
566 E->getCastKind() == CK_ReinterpretMemberPointer);
567
568 // Under Itanium, reinterprets don't require any additional processing.
569 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
570
571 // If the adjustment is trivial, we don't need to do anything.
572 llvm::Constant *adj = getMemberPointerAdjustment(E);
573 if (!adj) return src;
574
575 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
576
577 const MemberPointerType *destTy =
578 E->getType()->castAs<MemberPointerType>();
579
580 // For member data pointers, this is just a matter of adding the
581 // offset if the source is non-null.
582 if (destTy->isMemberDataPointer()) {
583 // null maps to null.
584 if (src->isAllOnesValue()) return src;
585
586 if (isDerivedToBase)
587 return llvm::ConstantExpr::getNSWSub(src, adj);
588 else
589 return llvm::ConstantExpr::getNSWAdd(src, adj);
590 }
591
592 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000593 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000594 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
595 offset <<= 1;
596 adj = llvm::ConstantInt::get(adj->getType(), offset);
597 }
598
599 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
600 llvm::Constant *dstAdj;
601 if (isDerivedToBase)
602 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
603 else
604 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
605
606 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000607}
John McCall84fa5102010-08-22 04:16:24 +0000608
609llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000610ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000611 // Itanium C++ ABI 2.3:
612 // A NULL pointer is represented as -1.
613 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000614 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000615
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000616 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000617 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000618 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000619}
620
John McCallf3a88602011-02-03 08:15:49 +0000621llvm::Constant *
622ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
623 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000624 // Itanium C++ ABI 2.3:
625 // A pointer to data member is an offset from the base address of
626 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000627 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000628}
629
John McCall2979fe02011-04-12 00:42:48 +0000630llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000631 return BuildMemberPointer(MD, CharUnits::Zero());
632}
633
634llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
635 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000636 assert(MD->isInstance() && "Member function must not be static!");
637 MD = MD->getCanonicalDecl();
638
639 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000640
641 // Get the function pointer (or index if this is a virtual function).
642 llvm::Constant *MemPtr[2];
643 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000644 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000645
Ken Dyckdf016282011-04-09 01:30:02 +0000646 const ASTContext &Context = getContext();
647 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000648 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000649 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000650
Mark Seabornedf0d382013-07-24 16:25:13 +0000651 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000652 // ARM C++ ABI 3.2.1:
653 // This ABI specifies that adj contains twice the this
654 // adjustment, plus 1 if the member function is virtual. The
655 // least significant bit of adj then makes exactly the same
656 // discrimination as the least significant bit of ptr does for
657 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000658 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
659 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000660 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000661 } else {
662 // Itanium C++ ABI 2.3:
663 // For a virtual function, [the pointer field] is 1 plus the
664 // virtual table offset (in bytes) of the function,
665 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000666 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
667 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000668 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000669 }
670 } else {
John McCall2979fe02011-04-12 00:42:48 +0000671 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000672 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000673 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000674 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000675 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000676 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000677 } else {
John McCall2979fe02011-04-12 00:42:48 +0000678 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
679 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000680 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000681 }
John McCall2979fe02011-04-12 00:42:48 +0000682 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000683
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000684 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000685 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
686 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000687 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000688 }
John McCall1c456c82010-08-22 06:43:33 +0000689
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000690 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000691}
692
Richard Smithdafff942012-01-14 04:30:29 +0000693llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
694 QualType MPType) {
695 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
696 const ValueDecl *MPD = MP.getMemberPointerDecl();
697 if (!MPD)
698 return EmitNullMemberPointer(MPT);
699
Reid Kleckner452abac2013-05-09 21:01:17 +0000700 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000701
702 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
703 return BuildMemberPointer(MD, ThisAdjustment);
704
705 CharUnits FieldOffset =
706 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
707 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
708}
709
John McCall131d97d2010-08-22 08:30:07 +0000710/// The comparison algorithm is pretty easy: the member pointers are
711/// the same if they're either bitwise identical *or* both null.
712///
713/// ARM is different here only because null-ness is more complicated.
714llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000715ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
716 llvm::Value *L,
717 llvm::Value *R,
718 const MemberPointerType *MPT,
719 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000720 CGBuilderTy &Builder = CGF.Builder;
721
John McCall131d97d2010-08-22 08:30:07 +0000722 llvm::ICmpInst::Predicate Eq;
723 llvm::Instruction::BinaryOps And, Or;
724 if (Inequality) {
725 Eq = llvm::ICmpInst::ICMP_NE;
726 And = llvm::Instruction::Or;
727 Or = llvm::Instruction::And;
728 } else {
729 Eq = llvm::ICmpInst::ICMP_EQ;
730 And = llvm::Instruction::And;
731 Or = llvm::Instruction::Or;
732 }
733
John McCall7a9aac22010-08-23 01:21:21 +0000734 // Member data pointers are easy because there's a unique null
735 // value, so it just comes down to bitwise equality.
736 if (MPT->isMemberDataPointer())
737 return Builder.CreateICmp(Eq, L, R);
738
739 // For member function pointers, the tautologies are more complex.
740 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000741 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000742 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000743 // (L == R) <==> (L.ptr == R.ptr &&
744 // (L.adj == R.adj ||
745 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000746 // The inequality tautologies have exactly the same structure, except
747 // applying De Morgan's laws.
748
749 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
750 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
751
John McCall131d97d2010-08-22 08:30:07 +0000752 // This condition tests whether L.ptr == R.ptr. This must always be
753 // true for equality to hold.
754 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
755
756 // This condition, together with the assumption that L.ptr == R.ptr,
757 // tests whether the pointers are both null. ARM imposes an extra
758 // condition.
759 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
760 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
761
762 // This condition tests whether L.adj == R.adj. If this isn't
763 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000764 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
765 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000766 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
767
768 // Null member function pointers on ARM clear the low bit of Adj,
769 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000770 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000771 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
772
773 // Compute (l.adj | r.adj) & 1 and test it against zero.
774 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
775 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
776 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
777 "cmp.or.adj");
778 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
779 }
780
781 // Tie together all our conditions.
782 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
783 Result = Builder.CreateBinOp(And, PtrEq, Result,
784 Inequality ? "memptr.ne" : "memptr.eq");
785 return Result;
786}
787
788llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000789ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
790 llvm::Value *MemPtr,
791 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000792 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000793
794 /// For member data pointers, this is just a check against -1.
795 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000796 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000797 llvm::Value *NegativeOne =
798 llvm::Constant::getAllOnesValue(MemPtr->getType());
799 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
800 }
John McCall131d97d2010-08-22 08:30:07 +0000801
Daniel Dunbar914bc412011-04-19 23:10:47 +0000802 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000803 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000804
805 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
806 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
807
Daniel Dunbar914bc412011-04-19 23:10:47 +0000808 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
809 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000810 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000811 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000812 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000813 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000814 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
815 "memptr.isvirtual");
816 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000817 }
818
819 return Result;
820}
John McCall1c456c82010-08-22 06:43:33 +0000821
Reid Kleckner40ca9132014-05-13 22:05:45 +0000822bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
823 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
824 if (!RD)
825 return false;
826
Reid Klecknerd355ca72014-05-15 01:26:32 +0000827 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
828 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
829 // special members.
830 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000831 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
832 return true;
833 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000834 return false;
835}
836
John McCall614dbdc2010-08-22 21:01:12 +0000837/// The Itanium ABI requires non-zero initialization only for data
838/// member pointers, for which '0' is a valid offset.
839bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
840 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000841}
John McCall5d865c322010-08-31 07:33:07 +0000842
John McCall82fb8922012-09-25 10:10:39 +0000843/// The Itanium ABI always places an offset to the complete object
844/// at entry -2 in the vtable.
845llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
846 llvm::Value *ptr,
847 QualType type) {
848 // Grab the vtable pointer as an intptr_t*.
849 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
850
851 // Track back to entry -2 and pull out the offset there.
852 llvm::Value *offsetPtr =
853 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
854 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
855 offset->setAlignment(CGF.PointerAlignInBytes);
856
857 // Apply the offset.
858 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
859 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
860}
861
David Majnemer1162d252014-06-22 19:05:33 +0000862static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
863 // void *__dynamic_cast(const void *sub,
864 // const abi::__class_type_info *src,
865 // const abi::__class_type_info *dst,
866 // std::ptrdiff_t src2dst_offset);
867
868 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
869 llvm::Type *PtrDiffTy =
870 CGF.ConvertType(CGF.getContext().getPointerDiffType());
871
872 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
873
874 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
875
876 // Mark the function as nounwind readonly.
877 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
878 llvm::Attribute::ReadOnly };
879 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
880 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
881
882 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
883}
884
885static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
886 // void __cxa_bad_cast();
887 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
888 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
889}
890
891/// \brief Compute the src2dst_offset hint as described in the
892/// Itanium C++ ABI [2.9.7]
893static CharUnits computeOffsetHint(ASTContext &Context,
894 const CXXRecordDecl *Src,
895 const CXXRecordDecl *Dst) {
896 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
897 /*DetectVirtual=*/false);
898
899 // If Dst is not derived from Src we can skip the whole computation below and
900 // return that Src is not a public base of Dst. Record all inheritance paths.
901 if (!Dst->isDerivedFrom(Src, Paths))
902 return CharUnits::fromQuantity(-2ULL);
903
904 unsigned NumPublicPaths = 0;
905 CharUnits Offset;
906
907 // Now walk all possible inheritance paths.
908 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
909 ++I) {
910 if (I->Access != AS_public) // Ignore non-public inheritance.
911 continue;
912
913 ++NumPublicPaths;
914
915 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
916 // If the path contains a virtual base class we can't give any hint.
917 // -1: no hint.
918 if (J->Base->isVirtual())
919 return CharUnits::fromQuantity(-1ULL);
920
921 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
922 continue;
923
924 // Accumulate the base class offsets.
925 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
926 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
927 }
928 }
929
930 // -2: Src is not a public base of Dst.
931 if (NumPublicPaths == 0)
932 return CharUnits::fromQuantity(-2ULL);
933
934 // -3: Src is a multiple public base type but never a virtual base type.
935 if (NumPublicPaths > 1)
936 return CharUnits::fromQuantity(-3ULL);
937
938 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
939 // Return the offset of Src from the origin of Dst.
940 return Offset;
941}
942
943static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
944 // void __cxa_bad_typeid();
945 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
946
947 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
948}
949
950bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
951 QualType SrcRecordTy) {
952 return IsDeref;
953}
954
955void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
956 llvm::Value *Fn = getBadTypeidFn(CGF);
957 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
958 CGF.Builder.CreateUnreachable();
959}
960
961llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
962 QualType SrcRecordTy,
963 llvm::Value *ThisPtr,
964 llvm::Type *StdTypeInfoPtrTy) {
965 llvm::Value *Value =
966 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
967
968 // Load the type info.
969 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
970 return CGF.Builder.CreateLoad(Value);
971}
972
973bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
974 QualType SrcRecordTy) {
975 return SrcIsPtr;
976}
977
978llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
979 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
980 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
981 llvm::Type *PtrDiffLTy =
982 CGF.ConvertType(CGF.getContext().getPointerDiffType());
983 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
984
985 llvm::Value *SrcRTTI =
986 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
987 llvm::Value *DestRTTI =
988 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
989
990 // Compute the offset hint.
991 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
992 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
993 llvm::Value *OffsetHint = llvm::ConstantInt::get(
994 PtrDiffLTy,
995 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
996
997 // Emit the call to __dynamic_cast.
998 Value = CGF.EmitCastToVoidPtr(Value);
999
1000 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1001 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1002 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1003
1004 /// C++ [expr.dynamic.cast]p9:
1005 /// A failed cast to reference type throws std::bad_cast
1006 if (DestTy->isReferenceType()) {
1007 llvm::BasicBlock *BadCastBlock =
1008 CGF.createBasicBlock("dynamic_cast.bad_cast");
1009
1010 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1011 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1012
1013 CGF.EmitBlock(BadCastBlock);
1014 EmitBadCastCall(CGF);
1015 }
1016
1017 return Value;
1018}
1019
1020llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1021 llvm::Value *Value,
1022 QualType SrcRecordTy,
1023 QualType DestTy) {
1024 llvm::Type *PtrDiffLTy =
1025 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1026 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1027
1028 // Get the vtable pointer.
1029 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1030
1031 // Get the offset-to-top from the vtable.
1032 llvm::Value *OffsetToTop =
1033 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1034 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1035
1036 // Finally, add the offset to the pointer.
1037 Value = CGF.EmitCastToVoidPtr(Value);
1038 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1039
1040 return CGF.Builder.CreateBitCast(Value, DestLTy);
1041}
1042
1043bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1044 llvm::Value *Fn = getBadCastFn(CGF);
1045 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1046 CGF.Builder.CreateUnreachable();
1047 return true;
1048}
1049
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001050llvm::Value *
1051ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1052 llvm::Value *This,
1053 const CXXRecordDecl *ClassDecl,
1054 const CXXRecordDecl *BaseClassDecl) {
1055 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1056 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001057 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1058 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001059
1060 llvm::Value *VBaseOffsetPtr =
1061 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1062 "vbase.offset.ptr");
1063 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1064 CGM.PtrDiffTy->getPointerTo());
1065
1066 llvm::Value *VBaseOffset =
1067 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1068
1069 return VBaseOffset;
1070}
1071
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001072void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1073 // Just make sure we're in sync with TargetCXXABI.
1074 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1075
Rafael Espindolac3cde362013-12-09 14:51:17 +00001076 // The constructor used for constructing this as a base class;
1077 // ignores virtual bases.
1078 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1079
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001080 // The constructor used for constructing this as a complete class;
1081 // constucts the virtual bases, then calls the base constructor.
1082 if (!D->getParent()->isAbstract()) {
1083 // We don't need to emit the complete ctor if the class is abstract.
1084 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1085 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001086}
1087
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001088void
1089ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1090 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001091 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001092
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001093 // All parameters are already in place except VTT, which goes after 'this'.
1094 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001095
1096 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001097 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1098 ArgTys.insert(ArgTys.begin() + 1,
1099 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001100}
1101
Reid Klecknere7de47e2013-07-22 13:51:44 +00001102void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001103 // The destructor used for destructing this as a base class; ignores
1104 // virtual bases.
1105 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001106
1107 // The destructor used for destructing this as a most-derived class;
1108 // call the base destructor and then destructs any virtual bases.
1109 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1110
Rafael Espindolac3cde362013-12-09 14:51:17 +00001111 // The destructor in a virtual table is always a 'deleting'
1112 // destructor, which calls the complete destructor and then uses the
1113 // appropriate operator delete.
1114 if (D->isVirtual())
1115 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001116}
1117
Reid Kleckner89077a12013-12-17 19:46:40 +00001118void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1119 QualType &ResTy,
1120 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001121 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001122 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001123
1124 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001125 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001126 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001127
1128 // FIXME: avoid the fake decl
1129 QualType T = Context.getPointerType(Context.VoidPtrTy);
1130 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001131 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001132 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001133 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001134 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001135 }
1136}
1137
John McCall5d865c322010-08-31 07:33:07 +00001138void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1139 /// Initialize the 'this' slot.
1140 EmitThisParam(CGF);
1141
1142 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001143 if (getStructorImplicitParamDecl(CGF)) {
1144 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1145 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001146 }
John McCall5d865c322010-08-31 07:33:07 +00001147
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001148 /// If this is a function that the ABI specifies returns 'this', initialize
1149 /// the return slot to 'this' at the start of the function.
1150 ///
1151 /// Unlike the setting of return types, this is done within the ABI
1152 /// implementation instead of by clients of CGCXXABI because:
1153 /// 1) getThisValue is currently protected
1154 /// 2) in theory, an ABI could implement 'this' returns some other way;
1155 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001156 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001157 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001158}
1159
Reid Kleckner89077a12013-12-17 19:46:40 +00001160unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1161 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1162 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1163 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1164 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001165
Reid Kleckner89077a12013-12-17 19:46:40 +00001166 // Insert the implicit 'vtt' argument as the second argument.
1167 llvm::Value *VTT =
1168 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1169 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1170 Args.insert(Args.begin() + 1,
1171 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1172 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001173}
1174
1175void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1176 const CXXDestructorDecl *DD,
1177 CXXDtorType Type, bool ForVirtualBase,
1178 bool Delegating, llvm::Value *This) {
1179 GlobalDecl GD(DD, Type);
1180 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1181 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1182
Craig Topper8a13c412014-05-21 05:09:00 +00001183 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001184 if (getContext().getLangOpts().AppleKext)
1185 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1186
1187 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001188 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001189
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001190 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1191 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001192}
1193
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001194void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1195 const CXXRecordDecl *RD) {
1196 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1197 if (VTable->hasInitializer())
1198 return;
1199
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001200 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001201 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1202 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001203 llvm::Constant *RTTI =
1204 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001205
1206 // Create and set the initializer.
1207 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1208 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001209 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001210 VTable->setInitializer(Init);
1211
1212 // Set the correct linkage.
1213 VTable->setLinkage(Linkage);
1214
1215 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001216 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001217
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001218 // Use pointer alignment for the vtable. Otherwise we would align them based
1219 // on the size of the initializer which doesn't make sense as only single
1220 // values are read.
1221 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1222 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1223
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001224 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1225 // we will emit the typeinfo for the fundamental types. This is the
1226 // same behaviour as GCC.
1227 const DeclContext *DC = RD->getDeclContext();
1228 if (RD->getIdentifier() &&
1229 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1230 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1231 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1232 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001233 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001234}
1235
1236llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1237 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1238 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1239 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1240 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1241
1242 llvm::Value *VTableAddressPoint;
1243 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1244 // Get the secondary vpointer index.
1245 uint64_t VirtualPointerIndex =
1246 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1247
1248 /// Load the VTT.
1249 llvm::Value *VTT = CGF.LoadCXXVTT();
1250 if (VirtualPointerIndex)
1251 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1252
1253 // And load the address point from the VTT.
1254 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1255 } else {
1256 llvm::Constant *VTable =
1257 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001258 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1259 .getVTableLayout(VTableClass)
1260 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001261 VTableAddressPoint =
1262 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1263 }
1264
1265 return VTableAddressPoint;
1266}
1267
1268llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1269 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1270 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1271
1272 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001273 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1274 .getVTableLayout(VTableClass)
1275 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001276 llvm::Value *Indices[] = {
1277 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1278 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1279 };
1280
1281 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1282}
1283
1284llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1285 CharUnits VPtrOffset) {
1286 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1287
1288 llvm::GlobalVariable *&VTable = VTables[RD];
1289 if (VTable)
1290 return VTable;
1291
1292 // Queue up this v-table for possible deferred emission.
1293 CGM.addDeferredVTable(RD);
1294
1295 SmallString<256> OutName;
1296 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001297 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001298 Out.flush();
1299 StringRef Name = OutName.str();
1300
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001301 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001302 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1303 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1304
1305 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1306 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1307 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001308
1309 if (RD->hasAttr<DLLImportAttr>())
1310 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1311 else if (RD->hasAttr<DLLExportAttr>())
1312 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1313
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001314 return VTable;
1315}
1316
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001317llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1318 GlobalDecl GD,
1319 llvm::Value *This,
1320 llvm::Type *Ty) {
1321 GD = GD.getCanonicalDecl();
1322 Ty = Ty->getPointerTo()->getPointerTo();
1323 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1324
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001325 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001326 llvm::Value *VFuncPtr =
1327 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1328 return CGF.Builder.CreateLoad(VFuncPtr);
1329}
1330
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001331void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1332 const CXXDestructorDecl *Dtor,
1333 CXXDtorType DtorType,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001334 llvm::Value *This,
1335 const CXXMemberCallExpr *CE) {
1336 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001337 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1338
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001339 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1340 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001341 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001342 llvm::Value *Callee =
1343 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001344
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001345 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1346 /*ImplicitParam=*/nullptr, QualType(), CE);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001347}
1348
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001349void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001350 CodeGenVTables &VTables = CGM.getVTables();
1351 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001352 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001353}
1354
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001355static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1356 llvm::Value *Ptr,
1357 int64_t NonVirtualAdjustment,
1358 int64_t VirtualAdjustment,
1359 bool IsReturnAdjustment) {
1360 if (!NonVirtualAdjustment && !VirtualAdjustment)
1361 return Ptr;
1362
1363 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1364 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1365
1366 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1367 // Perform the non-virtual adjustment for a base-to-derived cast.
1368 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1369 }
1370
1371 if (VirtualAdjustment) {
1372 llvm::Type *PtrDiffTy =
1373 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1374
1375 // Perform the virtual adjustment.
1376 llvm::Value *VTablePtrPtr =
1377 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1378
1379 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1380
1381 llvm::Value *OffsetPtr =
1382 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1383
1384 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1385
1386 // Load the adjustment offset from the vtable.
1387 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1388
1389 // Adjust our pointer.
1390 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1391 }
1392
1393 if (NonVirtualAdjustment && IsReturnAdjustment) {
1394 // Perform the non-virtual adjustment for a derived-to-base cast.
1395 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1396 }
1397
1398 // Cast back to the original type.
1399 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1400}
1401
1402llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1403 llvm::Value *This,
1404 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001405 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1406 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001407 /*IsReturnAdjustment=*/false);
1408}
1409
1410llvm::Value *
1411ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1412 const ReturnAdjustment &RA) {
1413 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1414 RA.Virtual.Itanium.VBaseOffsetOffset,
1415 /*IsReturnAdjustment=*/true);
1416}
1417
John McCall5d865c322010-08-31 07:33:07 +00001418void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1419 RValue RV, QualType ResultType) {
1420 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1421 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1422
1423 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001424 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001425 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1426 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1427 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1428}
John McCall8ed55a52010-09-02 09:58:18 +00001429
1430/************************** Array allocation cookies **************************/
1431
John McCallb91cd662012-05-01 05:23:51 +00001432CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1433 // The array cookie is a size_t; pad that up to the element alignment.
1434 // The cookie is actually right-justified in that space.
1435 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1436 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001437}
1438
1439llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1440 llvm::Value *NewPtr,
1441 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001442 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001443 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001444 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001445
Micah Villmowea2fea22012-10-25 15:39:14 +00001446 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001447
John McCall9bca9232010-09-02 10:25:57 +00001448 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001449 QualType SizeTy = Ctx.getSizeType();
1450 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1451
1452 // The size of the cookie.
1453 CharUnits CookieSize =
1454 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001455 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001456
1457 // Compute an offset to the cookie.
1458 llvm::Value *CookiePtr = NewPtr;
1459 CharUnits CookieOffset = CookieSize - SizeSize;
1460 if (!CookieOffset.isZero())
1461 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1462 CookieOffset.getQuantity());
1463
1464 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001465 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1466 llvm::Value *NumElementsPtr =
1467 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1468 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001469 if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001470 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001471 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001472 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1473 llvm::FunctionType *FTy =
1474 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1475 llvm::Constant *F =
1476 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1477 CGF.Builder.CreateCall(F, NumElementsPtr);
1478 }
John McCall8ed55a52010-09-02 09:58:18 +00001479
1480 // Finally, compute a pointer to the actual data buffer by skipping
1481 // over the cookie completely.
1482 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1483 CookieSize.getQuantity());
1484}
1485
John McCallb91cd662012-05-01 05:23:51 +00001486llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1487 llvm::Value *allocPtr,
1488 CharUnits cookieSize) {
1489 // The element size is right-justified in the cookie.
1490 llvm::Value *numElementsPtr = allocPtr;
1491 CharUnits numElementsOffset =
1492 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1493 if (!numElementsOffset.isZero())
1494 numElementsPtr =
1495 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1496 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001497
Micah Villmowea2fea22012-10-25 15:39:14 +00001498 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001499 numElementsPtr =
1500 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001501 if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1502 return CGF.Builder.CreateLoad(numElementsPtr);
1503 // In asan mode emit a function call instead of a regular load and let the
1504 // run-time deal with it: if the shadow is properly poisoned return the
1505 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1506 // We can't simply ignore this load using nosanitize metadata because
1507 // the metadata may be lost.
1508 llvm::FunctionType *FTy =
1509 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1510 llvm::Constant *F =
1511 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1512 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001513}
1514
John McCallb91cd662012-05-01 05:23:51 +00001515CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001516 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001517 // struct array_cookie {
1518 // std::size_t element_size; // element_size != 0
1519 // std::size_t element_count;
1520 // };
John McCallc19c7062013-01-25 23:36:19 +00001521 // But the base ABI doesn't give anything an alignment greater than
1522 // 8, so we can dismiss this as typical ABI-author blindness to
1523 // actual language complexity and round up to the element alignment.
1524 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1525 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001526}
1527
1528llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001529 llvm::Value *newPtr,
1530 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001531 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001532 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001533 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001534
John McCallc19c7062013-01-25 23:36:19 +00001535 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1536 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001537
1538 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001539 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001540
1541 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001542 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1543 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1544 getContext().getTypeSizeInChars(elementType).getQuantity());
1545 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001546
1547 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001548 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1549 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001550
1551 // Finally, compute a pointer to the actual data buffer by skipping
1552 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001553 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1554 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1555 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001556}
1557
John McCallb91cd662012-05-01 05:23:51 +00001558llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1559 llvm::Value *allocPtr,
1560 CharUnits cookieSize) {
1561 // The number of elements is at offset sizeof(size_t) relative to
1562 // the allocated pointer.
1563 llvm::Value *numElementsPtr
1564 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001565
Micah Villmowea2fea22012-10-25 15:39:14 +00001566 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001567 numElementsPtr =
1568 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1569 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001570}
1571
John McCall68ff0372010-09-08 01:44:27 +00001572/*********************** Static local initialization **************************/
1573
1574static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001575 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001576 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001577 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001578 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001579 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001580 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001581 llvm::AttributeSet::get(CGM.getLLVMContext(),
1582 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001583 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001584}
1585
1586static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001587 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001588 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001589 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001590 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001591 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001592 llvm::AttributeSet::get(CGM.getLLVMContext(),
1593 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001594 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001595}
1596
1597static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001598 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001599 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001600 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001601 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001602 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001603 llvm::AttributeSet::get(CGM.getLLVMContext(),
1604 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001605 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001606}
1607
1608namespace {
1609 struct CallGuardAbort : EHScopeStack::Cleanup {
1610 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001611 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001612
Craig Topper4f12f102014-03-12 06:41:41 +00001613 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001614 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1615 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001616 }
1617 };
1618}
1619
1620/// The ARM code here follows the Itanium code closely enough that we
1621/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001622void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1623 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001624 llvm::GlobalVariable *var,
1625 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001626 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001627
Richard Smithdbf74ba2013-04-14 23:01:42 +00001628 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001629 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001630 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1631 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001632
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001633 // If we have a global variable with internal linkage and thread-safe statics
1634 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001635 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1636
1637 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001638 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001639 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001640 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001641 // Guard variables are 64 bits in the generic ABI and size width on ARM
1642 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001643 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001644 }
John McCallb88a5662012-03-30 21:00:39 +00001645 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001646
John McCallb88a5662012-03-30 21:00:39 +00001647 // Create the guard variable if we don't already have it (as we
1648 // might if we're double-emitting this function body).
1649 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1650 if (!guard) {
1651 // Mangle the name for the guard.
1652 SmallString<256> guardName;
1653 {
1654 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001655 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001656 out.flush();
1657 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001658
John McCallb88a5662012-03-30 21:00:39 +00001659 // Create the guard variable with a zero-initializer.
1660 // Just absorb linkage and visibility from the guarded variable.
1661 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1662 false, var->getLinkage(),
1663 llvm::ConstantInt::get(guardTy, 0),
1664 guardName.str());
1665 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001666 // If the variable is thread-local, so is its guard variable.
1667 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001668
1669 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1670 }
John McCall87590e62012-03-30 07:09:50 +00001671
John McCall68ff0372010-09-08 01:44:27 +00001672 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001673 //
John McCall68ff0372010-09-08 01:44:27 +00001674 // Itanium C++ ABI 3.3.2:
1675 // The following is pseudo-code showing how these functions can be used:
1676 // if (obj_guard.first_byte == 0) {
1677 // if ( __cxa_guard_acquire (&obj_guard) ) {
1678 // try {
1679 // ... initialize the object ...;
1680 // } catch (...) {
1681 // __cxa_guard_abort (&obj_guard);
1682 // throw;
1683 // }
1684 // ... queue object destructor with __cxa_atexit() ...;
1685 // __cxa_guard_release (&obj_guard);
1686 // }
1687 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001688
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001689 // Load the first byte of the guard variable.
1690 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001691 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001692 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001693
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001694 // Itanium ABI:
1695 // An implementation supporting thread-safety on multiprocessor
1696 // systems must also guarantee that references to the initialized
1697 // object do not occur before the load of the initialization flag.
1698 //
1699 // In LLVM, we do this by marking the load Acquire.
1700 if (threadsafe)
1701 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001702
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001703 // For ARM, we should only check the first bit, rather than the entire byte:
1704 //
1705 // ARM C++ ABI 3.2.3.1:
1706 // To support the potential use of initialization guard variables
1707 // as semaphores that are the target of ARM SWP and LDREX/STREX
1708 // synchronizing instructions we define a static initialization
1709 // guard variable to be a 4-byte aligned, 4-byte word with the
1710 // following inline access protocol.
1711 // #define INITIALIZED 1
1712 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1713 // if (__cxa_guard_acquire(&obj_guard))
1714 // ...
1715 // }
1716 //
1717 // and similarly for ARM64:
1718 //
1719 // ARM64 C++ ABI 3.2.2:
1720 // This ABI instead only specifies the value bit 0 of the static guard
1721 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1722 // variable is not initialized and 1 when it is.
1723 llvm::Value *V =
1724 (UseARMGuardVarABI && !useInt8GuardVariable)
1725 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1726 : LI;
1727 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001728
1729 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1730 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1731
1732 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001733 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001734
1735 CGF.EmitBlock(InitCheckBlock);
1736
1737 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001738 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001739 // Call __cxa_guard_acquire.
1740 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001741 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001742
1743 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1744
1745 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1746 InitBlock, EndBlock);
1747
1748 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001749 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001750
1751 CGF.EmitBlock(InitBlock);
1752 }
1753
1754 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001755 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001756
John McCall5aa52592011-06-17 07:33:57 +00001757 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001758 // Pop the guard-abort cleanup if we pushed one.
1759 CGF.PopCleanupBlock();
1760
1761 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001762 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001763 } else {
John McCallb88a5662012-03-30 21:00:39 +00001764 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001765 }
1766
1767 CGF.EmitBlock(EndBlock);
1768}
John McCallc84ed6a2012-05-01 06:13:13 +00001769
1770/// Register a global destructor using __cxa_atexit.
1771static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1772 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001773 llvm::Constant *addr,
1774 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001775 const char *Name = "__cxa_atexit";
1776 if (TLS) {
1777 const llvm::Triple &T = CGF.getTarget().getTriple();
1778 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1779 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001780
John McCallc84ed6a2012-05-01 06:13:13 +00001781 // We're assuming that the destructor function is something we can
1782 // reasonably call with the default CC. Go ahead and cast it to the
1783 // right prototype.
1784 llvm::Type *dtorTy =
1785 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1786
1787 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1788 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1789 llvm::FunctionType *atexitTy =
1790 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1791
1792 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001793 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001794 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1795 fn->setDoesNotThrow();
1796
1797 // Create a variable that binds the atexit to this shared object.
1798 llvm::Constant *handle =
1799 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1800
1801 llvm::Value *args[] = {
1802 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1803 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1804 handle
1805 };
John McCall882987f2013-02-28 19:01:20 +00001806 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001807}
1808
1809/// Register a global destructor as best as we know how.
1810void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001811 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001812 llvm::Constant *dtor,
1813 llvm::Constant *addr) {
1814 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001815 if (CGM.getCodeGenOpts().CXAAtExit)
1816 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1817
1818 if (D.getTLSKind())
1819 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001820
1821 // In Apple kexts, we want to add a global destructor entry.
1822 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001823 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001824 // Generate a global destructor entry.
1825 return CGM.AddCXXDtorEntry(dtor, addr);
1826 }
1827
David Blaikieebe87e12013-08-27 23:57:18 +00001828 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001829}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001830
David Majnemer9b21c332014-07-11 20:28:10 +00001831static bool isThreadWrapperReplaceable(const VarDecl *VD,
1832 CodeGen::CodeGenModule &CGM) {
1833 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1834 // OS X prefers to have references to thread local variables to go through
1835 // the thread wrapper instead of directly referencing the backing variable.
1836 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1837 CGM.getTarget().getTriple().isMacOSX();
1838}
1839
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001840/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001841/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001842/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001843static llvm::GlobalValue::LinkageTypes
1844getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1845 llvm::GlobalValue::LinkageTypes VarLinkage =
1846 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1847
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001848 // For internal linkage variables, we don't need an external or weak wrapper.
1849 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1850 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001851
David Majnemer9b21c332014-07-11 20:28:10 +00001852 // If the thread wrapper is replaceable, give it appropriate linkage.
1853 if (isThreadWrapperReplaceable(VD, CGM)) {
1854 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1855 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1856 return llvm::GlobalVariable::WeakAnyLinkage;
1857 return VarLinkage;
1858 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001859 return llvm::GlobalValue::WeakODRLinkage;
1860}
1861
1862llvm::Function *
1863ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1864 llvm::GlobalVariable *Var) {
1865 // Mangle the name for the thread_local wrapper function.
1866 SmallString<256> WrapperName;
1867 {
1868 llvm::raw_svector_ostream Out(WrapperName);
1869 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1870 Out.flush();
1871 }
1872
1873 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1874 return cast<llvm::Function>(V);
1875
1876 llvm::Type *RetTy = Var->getType();
1877 if (VD->getType()->isReferenceType())
1878 RetTy = RetTy->getPointerElementType();
1879
1880 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001881 llvm::Function *Wrapper =
1882 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1883 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001884 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001885 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001886 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001887 return Wrapper;
1888}
1889
1890void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +00001891 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001892 llvm::Function *InitFunc) {
1893 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1894 const VarDecl *VD = Decls[I].first;
1895 llvm::GlobalVariable *Var = Decls[I].second;
1896
David Majnemer9b21c332014-07-11 20:28:10 +00001897 // Some targets require that all access to thread local variables go through
1898 // the thread wrapper. This means that we cannot attempt to create a thread
1899 // wrapper or a thread helper.
1900 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1901 continue;
1902
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001903 // Mangle the name for the thread_local initialization function.
1904 SmallString<256> InitFnName;
1905 {
1906 llvm::raw_svector_ostream Out(InitFnName);
1907 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1908 Out.flush();
1909 }
1910
1911 // If we have a definition for the variable, emit the initialization
1912 // function as an alias to the global Init function (if any). Otherwise,
1913 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001914 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001915 bool InitIsInitFunc = false;
1916 if (VD->hasDefinition()) {
1917 InitIsInitFunc = true;
1918 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001919 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1920 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001921 } else {
1922 // Emit a weak global function referring to the initialization function.
1923 // This function will not exist if the TU defining the thread_local
1924 // variable in question does not need any dynamic initialization for
1925 // its thread_local variables.
1926 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1927 Init = llvm::Function::Create(
1928 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1929 &CGM.getModule());
1930 }
1931
1932 if (Init)
1933 Init->setVisibility(Var->getVisibility());
1934
1935 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1936 llvm::LLVMContext &Context = CGM.getModule().getContext();
1937 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1938 CGBuilderTy Builder(Entry);
1939 if (InitIsInitFunc) {
1940 if (Init)
1941 Builder.CreateCall(Init);
1942 } else {
1943 // Don't know whether we have an init function. Call it if it exists.
1944 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1945 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1946 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1947 Builder.CreateCondBr(Have, InitBB, ExitBB);
1948
1949 Builder.SetInsertPoint(InitBB);
1950 Builder.CreateCall(Init);
1951 Builder.CreateBr(ExitBB);
1952
1953 Builder.SetInsertPoint(ExitBB);
1954 }
1955
1956 // For a reference, the result of the wrapper function is a pointer to
1957 // the referenced object.
1958 llvm::Value *Val = Var;
1959 if (VD->getType()->isReferenceType()) {
1960 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1961 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1962 Val = LI;
1963 }
1964
1965 Builder.CreateRet(Val);
1966 }
1967}
1968
Richard Smith0f383742014-03-26 22:48:22 +00001969LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1970 const VarDecl *VD,
1971 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001972 QualType T = VD->getType();
1973 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1974 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1975 llvm::Function *Wrapper =
1976 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1977
1978 Val = CGF.Builder.CreateCall(Wrapper);
1979
1980 LValue LV;
1981 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001982 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001983 else
Richard Smith0f383742014-03-26 22:48:22 +00001984 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001985 // FIXME: need setObjCGCLValueClass?
1986 return LV;
1987}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001988
1989/// Return whether the given global decl needs a VTT parameter, which it does
1990/// if it's a base constructor or destructor with virtual bases.
1991bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1992 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1993
1994 // We don't have any virtual bases, just return early.
1995 if (!MD->getParent()->getNumVBases())
1996 return false;
1997
1998 // Check if we have a base constructor.
1999 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2000 return true;
2001
2002 // Check if we have a base destructor.
2003 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2004 return true;
2005
2006 return false;
2007}
David Majnemere2cb8d12014-07-07 06:20:47 +00002008
2009namespace {
2010class ItaniumRTTIBuilder {
2011 CodeGenModule &CGM; // Per-module state.
2012 llvm::LLVMContext &VMContext;
2013 const ItaniumCXXABI &CXXABI; // Per-module state.
2014
2015 /// Fields - The fields of the RTTI descriptor currently being built.
2016 SmallVector<llvm::Constant *, 16> Fields;
2017
2018 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2019 llvm::GlobalVariable *
2020 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2021
2022 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2023 /// descriptor of the given type.
2024 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2025
2026 /// BuildVTablePointer - Build the vtable pointer for the given type.
2027 void BuildVTablePointer(const Type *Ty);
2028
2029 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2030 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2031 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2032
2033 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2034 /// classes with bases that do not satisfy the abi::__si_class_type_info
2035 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2036 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2037
2038 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2039 /// for pointer types.
2040 void BuildPointerTypeInfo(QualType PointeeTy);
2041
2042 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2043 /// type_info for an object type.
2044 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2045
2046 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2047 /// struct, used for member pointer types.
2048 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2049
2050public:
2051 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2052 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2053
2054 // Pointer type info flags.
2055 enum {
2056 /// PTI_Const - Type has const qualifier.
2057 PTI_Const = 0x1,
2058
2059 /// PTI_Volatile - Type has volatile qualifier.
2060 PTI_Volatile = 0x2,
2061
2062 /// PTI_Restrict - Type has restrict qualifier.
2063 PTI_Restrict = 0x4,
2064
2065 /// PTI_Incomplete - Type is incomplete.
2066 PTI_Incomplete = 0x8,
2067
2068 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2069 /// (in pointer to member).
2070 PTI_ContainingClassIncomplete = 0x10
2071 };
2072
2073 // VMI type info flags.
2074 enum {
2075 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2076 VMI_NonDiamondRepeat = 0x1,
2077
2078 /// VMI_DiamondShaped - Class is diamond shaped.
2079 VMI_DiamondShaped = 0x2
2080 };
2081
2082 // Base class type info flags.
2083 enum {
2084 /// BCTI_Virtual - Base class is virtual.
2085 BCTI_Virtual = 0x1,
2086
2087 /// BCTI_Public - Base class is public.
2088 BCTI_Public = 0x2
2089 };
2090
2091 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2092 ///
2093 /// \param Force - true to force the creation of this RTTI value
2094 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2095};
2096}
2097
2098llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2099 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2100 SmallString<256> OutName;
2101 llvm::raw_svector_ostream Out(OutName);
2102 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2103 Out.flush();
2104 StringRef Name = OutName.str();
2105
2106 // We know that the mangled name of the type starts at index 4 of the
2107 // mangled name of the typename, so we can just index into it in order to
2108 // get the mangled name of the type.
2109 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2110 Name.substr(4));
2111
2112 llvm::GlobalVariable *GV =
2113 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2114
2115 GV->setInitializer(Init);
2116
2117 return GV;
2118}
2119
2120llvm::Constant *
2121ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2122 // Mangle the RTTI name.
2123 SmallString<256> OutName;
2124 llvm::raw_svector_ostream Out(OutName);
2125 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2126 Out.flush();
2127 StringRef Name = OutName.str();
2128
2129 // Look for an existing global.
2130 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2131
2132 if (!GV) {
2133 // Create a new global variable.
2134 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2135 /*Constant=*/true,
2136 llvm::GlobalValue::ExternalLinkage, nullptr,
2137 Name);
2138 }
2139
2140 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2141}
2142
2143/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2144/// info for that type is defined in the standard library.
2145static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2146 // Itanium C++ ABI 2.9.2:
2147 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2148 // the run-time support library. Specifically, the run-time support
2149 // library should contain type_info objects for the types X, X* and
2150 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2151 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2152 // long, unsigned long, long long, unsigned long long, float, double,
2153 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2154 // half-precision floating point types.
2155 switch (Ty->getKind()) {
2156 case BuiltinType::Void:
2157 case BuiltinType::NullPtr:
2158 case BuiltinType::Bool:
2159 case BuiltinType::WChar_S:
2160 case BuiltinType::WChar_U:
2161 case BuiltinType::Char_U:
2162 case BuiltinType::Char_S:
2163 case BuiltinType::UChar:
2164 case BuiltinType::SChar:
2165 case BuiltinType::Short:
2166 case BuiltinType::UShort:
2167 case BuiltinType::Int:
2168 case BuiltinType::UInt:
2169 case BuiltinType::Long:
2170 case BuiltinType::ULong:
2171 case BuiltinType::LongLong:
2172 case BuiltinType::ULongLong:
2173 case BuiltinType::Half:
2174 case BuiltinType::Float:
2175 case BuiltinType::Double:
2176 case BuiltinType::LongDouble:
2177 case BuiltinType::Char16:
2178 case BuiltinType::Char32:
2179 case BuiltinType::Int128:
2180 case BuiltinType::UInt128:
2181 case BuiltinType::OCLImage1d:
2182 case BuiltinType::OCLImage1dArray:
2183 case BuiltinType::OCLImage1dBuffer:
2184 case BuiltinType::OCLImage2d:
2185 case BuiltinType::OCLImage2dArray:
2186 case BuiltinType::OCLImage3d:
2187 case BuiltinType::OCLSampler:
2188 case BuiltinType::OCLEvent:
2189 return true;
2190
2191 case BuiltinType::Dependent:
2192#define BUILTIN_TYPE(Id, SingletonId)
2193#define PLACEHOLDER_TYPE(Id, SingletonId) \
2194 case BuiltinType::Id:
2195#include "clang/AST/BuiltinTypes.def"
2196 llvm_unreachable("asking for RRTI for a placeholder type!");
2197
2198 case BuiltinType::ObjCId:
2199 case BuiltinType::ObjCClass:
2200 case BuiltinType::ObjCSel:
2201 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2202 }
2203
2204 llvm_unreachable("Invalid BuiltinType Kind!");
2205}
2206
2207static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2208 QualType PointeeTy = PointerTy->getPointeeType();
2209 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2210 if (!BuiltinTy)
2211 return false;
2212
2213 // Check the qualifiers.
2214 Qualifiers Quals = PointeeTy.getQualifiers();
2215 Quals.removeConst();
2216
2217 if (!Quals.empty())
2218 return false;
2219
2220 return TypeInfoIsInStandardLibrary(BuiltinTy);
2221}
2222
2223/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2224/// information for the given type exists in the standard library.
2225static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2226 // Type info for builtin types is defined in the standard library.
2227 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2228 return TypeInfoIsInStandardLibrary(BuiltinTy);
2229
2230 // Type info for some pointer types to builtin types is defined in the
2231 // standard library.
2232 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2233 return TypeInfoIsInStandardLibrary(PointerTy);
2234
2235 return false;
2236}
2237
2238/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2239/// the given type exists somewhere else, and that we should not emit the type
2240/// information in this translation unit. Assumes that it is not a
2241/// standard-library type.
2242static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2243 QualType Ty) {
2244 ASTContext &Context = CGM.getContext();
2245
2246 // If RTTI is disabled, assume it might be disabled in the
2247 // translation unit that defines any potential key function, too.
2248 if (!Context.getLangOpts().RTTI) return false;
2249
2250 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2251 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2252 if (!RD->hasDefinition())
2253 return false;
2254
2255 if (!RD->isDynamicClass())
2256 return false;
2257
2258 // FIXME: this may need to be reconsidered if the key function
2259 // changes.
2260 return CGM.getVTables().isVTableExternal(RD);
2261 }
2262
2263 return false;
2264}
2265
2266/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2267static bool IsIncompleteClassType(const RecordType *RecordTy) {
2268 return !RecordTy->getDecl()->isCompleteDefinition();
2269}
2270
2271/// ContainsIncompleteClassType - Returns whether the given type contains an
2272/// incomplete class type. This is true if
2273///
2274/// * The given type is an incomplete class type.
2275/// * The given type is a pointer type whose pointee type contains an
2276/// incomplete class type.
2277/// * The given type is a member pointer type whose class is an incomplete
2278/// class type.
2279/// * The given type is a member pointer type whoise pointee type contains an
2280/// incomplete class type.
2281/// is an indirect or direct pointer to an incomplete class type.
2282static bool ContainsIncompleteClassType(QualType Ty) {
2283 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2284 if (IsIncompleteClassType(RecordTy))
2285 return true;
2286 }
2287
2288 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2289 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2290
2291 if (const MemberPointerType *MemberPointerTy =
2292 dyn_cast<MemberPointerType>(Ty)) {
2293 // Check if the class type is incomplete.
2294 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2295 if (IsIncompleteClassType(ClassType))
2296 return true;
2297
2298 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2299 }
2300
2301 return false;
2302}
2303
2304// CanUseSingleInheritance - Return whether the given record decl has a "single,
2305// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2306// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2307static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2308 // Check the number of bases.
2309 if (RD->getNumBases() != 1)
2310 return false;
2311
2312 // Get the base.
2313 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2314
2315 // Check that the base is not virtual.
2316 if (Base->isVirtual())
2317 return false;
2318
2319 // Check that the base is public.
2320 if (Base->getAccessSpecifier() != AS_public)
2321 return false;
2322
2323 // Check that the class is dynamic iff the base is.
2324 const CXXRecordDecl *BaseDecl =
2325 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2326 if (!BaseDecl->isEmpty() &&
2327 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2328 return false;
2329
2330 return true;
2331}
2332
2333void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2334 // abi::__class_type_info.
2335 static const char * const ClassTypeInfo =
2336 "_ZTVN10__cxxabiv117__class_type_infoE";
2337 // abi::__si_class_type_info.
2338 static const char * const SIClassTypeInfo =
2339 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2340 // abi::__vmi_class_type_info.
2341 static const char * const VMIClassTypeInfo =
2342 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2343
2344 const char *VTableName = nullptr;
2345
2346 switch (Ty->getTypeClass()) {
2347#define TYPE(Class, Base)
2348#define ABSTRACT_TYPE(Class, Base)
2349#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2350#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2351#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2352#include "clang/AST/TypeNodes.def"
2353 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2354
2355 case Type::LValueReference:
2356 case Type::RValueReference:
2357 llvm_unreachable("References shouldn't get here");
2358
2359 case Type::Auto:
2360 llvm_unreachable("Undeduced auto type shouldn't get here");
2361
2362 case Type::Builtin:
2363 // GCC treats vector and complex types as fundamental types.
2364 case Type::Vector:
2365 case Type::ExtVector:
2366 case Type::Complex:
2367 case Type::Atomic:
2368 // FIXME: GCC treats block pointers as fundamental types?!
2369 case Type::BlockPointer:
2370 // abi::__fundamental_type_info.
2371 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2372 break;
2373
2374 case Type::ConstantArray:
2375 case Type::IncompleteArray:
2376 case Type::VariableArray:
2377 // abi::__array_type_info.
2378 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2379 break;
2380
2381 case Type::FunctionNoProto:
2382 case Type::FunctionProto:
2383 // abi::__function_type_info.
2384 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2385 break;
2386
2387 case Type::Enum:
2388 // abi::__enum_type_info.
2389 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2390 break;
2391
2392 case Type::Record: {
2393 const CXXRecordDecl *RD =
2394 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2395
2396 if (!RD->hasDefinition() || !RD->getNumBases()) {
2397 VTableName = ClassTypeInfo;
2398 } else if (CanUseSingleInheritance(RD)) {
2399 VTableName = SIClassTypeInfo;
2400 } else {
2401 VTableName = VMIClassTypeInfo;
2402 }
2403
2404 break;
2405 }
2406
2407 case Type::ObjCObject:
2408 // Ignore protocol qualifiers.
2409 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2410
2411 // Handle id and Class.
2412 if (isa<BuiltinType>(Ty)) {
2413 VTableName = ClassTypeInfo;
2414 break;
2415 }
2416
2417 assert(isa<ObjCInterfaceType>(Ty));
2418 // Fall through.
2419
2420 case Type::ObjCInterface:
2421 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2422 VTableName = SIClassTypeInfo;
2423 } else {
2424 VTableName = ClassTypeInfo;
2425 }
2426 break;
2427
2428 case Type::ObjCObjectPointer:
2429 case Type::Pointer:
2430 // abi::__pointer_type_info.
2431 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2432 break;
2433
2434 case Type::MemberPointer:
2435 // abi::__pointer_to_member_type_info.
2436 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2437 break;
2438 }
2439
2440 llvm::Constant *VTable =
2441 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2442
2443 llvm::Type *PtrDiffTy =
2444 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2445
2446 // The vtable address point is 2.
2447 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2448 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2449 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2450
2451 Fields.push_back(VTable);
2452}
2453
2454/// \brief Return the linkage that the type info and type info name constants
2455/// should have for the given type.
2456static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2457 QualType Ty) {
2458 // Itanium C++ ABI 2.9.5p7:
2459 // In addition, it and all of the intermediate abi::__pointer_type_info
2460 // structs in the chain down to the abi::__class_type_info for the
2461 // incomplete class type must be prevented from resolving to the
2462 // corresponding type_info structs for the complete class type, possibly
2463 // by making them local static objects. Finally, a dummy class RTTI is
2464 // generated for the incomplete type that will not resolve to the final
2465 // complete class RTTI (because the latter need not exist), possibly by
2466 // making it a local static object.
2467 if (ContainsIncompleteClassType(Ty))
2468 return llvm::GlobalValue::InternalLinkage;
2469
2470 switch (Ty->getLinkage()) {
2471 case NoLinkage:
2472 case InternalLinkage:
2473 case UniqueExternalLinkage:
2474 return llvm::GlobalValue::InternalLinkage;
2475
2476 case VisibleNoLinkage:
2477 case ExternalLinkage:
2478 if (!CGM.getLangOpts().RTTI) {
2479 // RTTI is not enabled, which means that this type info struct is going
2480 // to be used for exception handling. Give it linkonce_odr linkage.
2481 return llvm::GlobalValue::LinkOnceODRLinkage;
2482 }
2483
2484 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2485 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2486 if (RD->hasAttr<WeakAttr>())
2487 return llvm::GlobalValue::WeakODRLinkage;
2488 if (RD->isDynamicClass())
2489 return CGM.getVTableLinkage(RD);
2490 }
2491
2492 return llvm::GlobalValue::LinkOnceODRLinkage;
2493 }
2494
2495 llvm_unreachable("Invalid linkage!");
2496}
2497
2498llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2499 // We want to operate on the canonical type.
2500 Ty = CGM.getContext().getCanonicalType(Ty);
2501
2502 // Check if we've already emitted an RTTI descriptor for this type.
2503 SmallString<256> OutName;
2504 llvm::raw_svector_ostream Out(OutName);
2505 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2506 Out.flush();
2507 StringRef Name = OutName.str();
2508
2509 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2510 if (OldGV && !OldGV->isDeclaration()) {
2511 assert(!OldGV->hasAvailableExternallyLinkage() &&
2512 "available_externally typeinfos not yet implemented");
2513
2514 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2515 }
2516
2517 // Check if there is already an external RTTI descriptor for this type.
2518 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2519 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2520 return GetAddrOfExternalRTTIDescriptor(Ty);
2521
2522 // Emit the standard library with external linkage.
2523 llvm::GlobalVariable::LinkageTypes Linkage;
2524 if (IsStdLib)
2525 Linkage = llvm::GlobalValue::ExternalLinkage;
2526 else
2527 Linkage = getTypeInfoLinkage(CGM, Ty);
2528
2529 // Add the vtable pointer.
2530 BuildVTablePointer(cast<Type>(Ty));
2531
2532 // And the name.
2533 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2534 llvm::Constant *TypeNameField;
2535
2536 // If we're supposed to demote the visibility, be sure to set a flag
2537 // to use a string comparison for type_info comparisons.
2538 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2539 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2540 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2541 // The flag is the sign bit, which on ARM64 is defined to be clear
2542 // for global pointers. This is very ARM64-specific.
2543 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2544 llvm::Constant *flag =
2545 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2546 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2547 TypeNameField =
2548 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2549 } else {
2550 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2551 }
2552 Fields.push_back(TypeNameField);
2553
2554 switch (Ty->getTypeClass()) {
2555#define TYPE(Class, Base)
2556#define ABSTRACT_TYPE(Class, Base)
2557#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2558#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2559#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2560#include "clang/AST/TypeNodes.def"
2561 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2562
2563 // GCC treats vector types as fundamental types.
2564 case Type::Builtin:
2565 case Type::Vector:
2566 case Type::ExtVector:
2567 case Type::Complex:
2568 case Type::BlockPointer:
2569 // Itanium C++ ABI 2.9.5p4:
2570 // abi::__fundamental_type_info adds no data members to std::type_info.
2571 break;
2572
2573 case Type::LValueReference:
2574 case Type::RValueReference:
2575 llvm_unreachable("References shouldn't get here");
2576
2577 case Type::Auto:
2578 llvm_unreachable("Undeduced auto type shouldn't get here");
2579
2580 case Type::ConstantArray:
2581 case Type::IncompleteArray:
2582 case Type::VariableArray:
2583 // Itanium C++ ABI 2.9.5p5:
2584 // abi::__array_type_info adds no data members to std::type_info.
2585 break;
2586
2587 case Type::FunctionNoProto:
2588 case Type::FunctionProto:
2589 // Itanium C++ ABI 2.9.5p5:
2590 // abi::__function_type_info adds no data members to std::type_info.
2591 break;
2592
2593 case Type::Enum:
2594 // Itanium C++ ABI 2.9.5p5:
2595 // abi::__enum_type_info adds no data members to std::type_info.
2596 break;
2597
2598 case Type::Record: {
2599 const CXXRecordDecl *RD =
2600 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2601 if (!RD->hasDefinition() || !RD->getNumBases()) {
2602 // We don't need to emit any fields.
2603 break;
2604 }
2605
2606 if (CanUseSingleInheritance(RD))
2607 BuildSIClassTypeInfo(RD);
2608 else
2609 BuildVMIClassTypeInfo(RD);
2610
2611 break;
2612 }
2613
2614 case Type::ObjCObject:
2615 case Type::ObjCInterface:
2616 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2617 break;
2618
2619 case Type::ObjCObjectPointer:
2620 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2621 break;
2622
2623 case Type::Pointer:
2624 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2625 break;
2626
2627 case Type::MemberPointer:
2628 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2629 break;
2630
2631 case Type::Atomic:
2632 // No fields, at least for the moment.
2633 break;
2634 }
2635
2636 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2637
2638 llvm::GlobalVariable *GV =
2639 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2640 /*Constant=*/true, Linkage, Init, Name);
2641
2642 // If there's already an old global variable, replace it with the new one.
2643 if (OldGV) {
2644 GV->takeName(OldGV);
2645 llvm::Constant *NewPtr =
2646 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2647 OldGV->replaceAllUsesWith(NewPtr);
2648 OldGV->eraseFromParent();
2649 }
2650
2651 // The Itanium ABI specifies that type_info objects must be globally
2652 // unique, with one exception: if the type is an incomplete class
2653 // type or a (possibly indirect) pointer to one. That exception
2654 // affects the general case of comparing type_info objects produced
2655 // by the typeid operator, which is why the comparison operators on
2656 // std::type_info generally use the type_info name pointers instead
2657 // of the object addresses. However, the language's built-in uses
2658 // of RTTI generally require class types to be complete, even when
2659 // manipulating pointers to those class types. This allows the
2660 // implementation of dynamic_cast to rely on address equality tests,
2661 // which is much faster.
2662
2663 // All of this is to say that it's important that both the type_info
2664 // object and the type_info name be uniqued when weakly emitted.
2665
2666 // Give the type_info object and name the formal visibility of the
2667 // type itself.
2668 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2669 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2670 // If the linkage is local, only default visibility makes sense.
2671 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2672 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2673 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2674 else
2675 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2676 TypeName->setVisibility(llvmVisibility);
2677 GV->setVisibility(llvmVisibility);
2678
2679 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2680}
2681
2682/// ComputeQualifierFlags - Compute the pointer type info flags from the
2683/// given qualifier.
2684static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2685 unsigned Flags = 0;
2686
2687 if (Quals.hasConst())
2688 Flags |= ItaniumRTTIBuilder::PTI_Const;
2689 if (Quals.hasVolatile())
2690 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2691 if (Quals.hasRestrict())
2692 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2693
2694 return Flags;
2695}
2696
2697/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2698/// for the given Objective-C object type.
2699void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2700 // Drop qualifiers.
2701 const Type *T = OT->getBaseType().getTypePtr();
2702 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2703
2704 // The builtin types are abi::__class_type_infos and don't require
2705 // extra fields.
2706 if (isa<BuiltinType>(T)) return;
2707
2708 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2709 ObjCInterfaceDecl *Super = Class->getSuperClass();
2710
2711 // Root classes are also __class_type_info.
2712 if (!Super) return;
2713
2714 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2715
2716 // Everything else is single inheritance.
2717 llvm::Constant *BaseTypeInfo =
2718 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2719 Fields.push_back(BaseTypeInfo);
2720}
2721
2722/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2723/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2724void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2725 // Itanium C++ ABI 2.9.5p6b:
2726 // It adds to abi::__class_type_info a single member pointing to the
2727 // type_info structure for the base type,
2728 llvm::Constant *BaseTypeInfo =
2729 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2730 Fields.push_back(BaseTypeInfo);
2731}
2732
2733namespace {
2734 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2735 /// a class hierarchy.
2736 struct SeenBases {
2737 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2738 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2739 };
2740}
2741
2742/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2743/// abi::__vmi_class_type_info.
2744///
2745static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2746 SeenBases &Bases) {
2747
2748 unsigned Flags = 0;
2749
2750 const CXXRecordDecl *BaseDecl =
2751 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2752
2753 if (Base->isVirtual()) {
2754 // Mark the virtual base as seen.
2755 if (!Bases.VirtualBases.insert(BaseDecl)) {
2756 // If this virtual base has been seen before, then the class is diamond
2757 // shaped.
2758 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2759 } else {
2760 if (Bases.NonVirtualBases.count(BaseDecl))
2761 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2762 }
2763 } else {
2764 // Mark the non-virtual base as seen.
2765 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2766 // If this non-virtual base has been seen before, then the class has non-
2767 // diamond shaped repeated inheritance.
2768 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2769 } else {
2770 if (Bases.VirtualBases.count(BaseDecl))
2771 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2772 }
2773 }
2774
2775 // Walk all bases.
2776 for (const auto &I : BaseDecl->bases())
2777 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2778
2779 return Flags;
2780}
2781
2782static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2783 unsigned Flags = 0;
2784 SeenBases Bases;
2785
2786 // Walk all bases.
2787 for (const auto &I : RD->bases())
2788 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2789
2790 return Flags;
2791}
2792
2793/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2794/// classes with bases that do not satisfy the abi::__si_class_type_info
2795/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2796void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2797 llvm::Type *UnsignedIntLTy =
2798 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2799
2800 // Itanium C++ ABI 2.9.5p6c:
2801 // __flags is a word with flags describing details about the class
2802 // structure, which may be referenced by using the __flags_masks
2803 // enumeration. These flags refer to both direct and indirect bases.
2804 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2805 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2806
2807 // Itanium C++ ABI 2.9.5p6c:
2808 // __base_count is a word with the number of direct proper base class
2809 // descriptions that follow.
2810 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2811
2812 if (!RD->getNumBases())
2813 return;
2814
2815 llvm::Type *LongLTy =
2816 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2817
2818 // Now add the base class descriptions.
2819
2820 // Itanium C++ ABI 2.9.5p6c:
2821 // __base_info[] is an array of base class descriptions -- one for every
2822 // direct proper base. Each description is of the type:
2823 //
2824 // struct abi::__base_class_type_info {
2825 // public:
2826 // const __class_type_info *__base_type;
2827 // long __offset_flags;
2828 //
2829 // enum __offset_flags_masks {
2830 // __virtual_mask = 0x1,
2831 // __public_mask = 0x2,
2832 // __offset_shift = 8
2833 // };
2834 // };
2835 for (const auto &Base : RD->bases()) {
2836 // The __base_type member points to the RTTI for the base type.
2837 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2838
2839 const CXXRecordDecl *BaseDecl =
2840 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2841
2842 int64_t OffsetFlags = 0;
2843
2844 // All but the lower 8 bits of __offset_flags are a signed offset.
2845 // For a non-virtual base, this is the offset in the object of the base
2846 // subobject. For a virtual base, this is the offset in the virtual table of
2847 // the virtual base offset for the virtual base referenced (negative).
2848 CharUnits Offset;
2849 if (Base.isVirtual())
2850 Offset =
2851 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2852 else {
2853 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2854 Offset = Layout.getBaseClassOffset(BaseDecl);
2855 };
2856
2857 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2858
2859 // The low-order byte of __offset_flags contains flags, as given by the
2860 // masks from the enumeration __offset_flags_masks.
2861 if (Base.isVirtual())
2862 OffsetFlags |= BCTI_Virtual;
2863 if (Base.getAccessSpecifier() == AS_public)
2864 OffsetFlags |= BCTI_Public;
2865
2866 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2867 }
2868}
2869
2870/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2871/// used for pointer types.
2872void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2873 Qualifiers Quals;
2874 QualType UnqualifiedPointeeTy =
2875 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2876
2877 // Itanium C++ ABI 2.9.5p7:
2878 // __flags is a flag word describing the cv-qualification and other
2879 // attributes of the type pointed to
2880 unsigned Flags = ComputeQualifierFlags(Quals);
2881
2882 // Itanium C++ ABI 2.9.5p7:
2883 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2884 // incomplete class type, the incomplete target type flag is set.
2885 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2886 Flags |= PTI_Incomplete;
2887
2888 llvm::Type *UnsignedIntLTy =
2889 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2890 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2891
2892 // Itanium C++ ABI 2.9.5p7:
2893 // __pointee is a pointer to the std::type_info derivation for the
2894 // unqualified type being pointed to.
2895 llvm::Constant *PointeeTypeInfo =
2896 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2897 Fields.push_back(PointeeTypeInfo);
2898}
2899
2900/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2901/// struct, used for member pointer types.
2902void
2903ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2904 QualType PointeeTy = Ty->getPointeeType();
2905
2906 Qualifiers Quals;
2907 QualType UnqualifiedPointeeTy =
2908 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2909
2910 // Itanium C++ ABI 2.9.5p7:
2911 // __flags is a flag word describing the cv-qualification and other
2912 // attributes of the type pointed to.
2913 unsigned Flags = ComputeQualifierFlags(Quals);
2914
2915 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2916
2917 // Itanium C++ ABI 2.9.5p7:
2918 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2919 // incomplete class type, the incomplete target type flag is set.
2920 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2921 Flags |= PTI_Incomplete;
2922
2923 if (IsIncompleteClassType(ClassType))
2924 Flags |= PTI_ContainingClassIncomplete;
2925
2926 llvm::Type *UnsignedIntLTy =
2927 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2928 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2929
2930 // Itanium C++ ABI 2.9.5p7:
2931 // __pointee is a pointer to the std::type_info derivation for the
2932 // unqualified type being pointed to.
2933 llvm::Constant *PointeeTypeInfo =
2934 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2935 Fields.push_back(PointeeTypeInfo);
2936
2937 // Itanium C++ ABI 2.9.5p9:
2938 // __context is a pointer to an abi::__class_type_info corresponding to the
2939 // class type containing the member pointed to
2940 // (e.g., the "A" in "int A::*").
2941 Fields.push_back(
2942 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2943}
2944
2945llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2946 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2947}
2948
2949void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2950 QualType PointerType = getContext().getPointerType(Type);
2951 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2952 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2953 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2954 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2955}
2956
2957void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2958 QualType FundamentalTypes[] = {
2959 getContext().VoidTy, getContext().NullPtrTy,
2960 getContext().BoolTy, getContext().WCharTy,
2961 getContext().CharTy, getContext().UnsignedCharTy,
2962 getContext().SignedCharTy, getContext().ShortTy,
2963 getContext().UnsignedShortTy, getContext().IntTy,
2964 getContext().UnsignedIntTy, getContext().LongTy,
2965 getContext().UnsignedLongTy, getContext().LongLongTy,
2966 getContext().UnsignedLongLongTy, getContext().HalfTy,
2967 getContext().FloatTy, getContext().DoubleTy,
2968 getContext().LongDoubleTy, getContext().Char16Ty,
2969 getContext().Char32Ty,
2970 };
2971 for (const QualType &FundamentalType : FundamentalTypes)
2972 EmitFundamentalRTTIDescriptor(FundamentalType);
2973}
2974
2975/// What sort of uniqueness rules should we use for the RTTI for the
2976/// given type?
2977ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2978 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2979 if (shouldRTTIBeUnique())
2980 return RUK_Unique;
2981
2982 // It's only necessary for linkonce_odr or weak_odr linkage.
2983 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2984 Linkage != llvm::GlobalValue::WeakODRLinkage)
2985 return RUK_Unique;
2986
2987 // It's only necessary with default visibility.
2988 if (CanTy->getVisibility() != DefaultVisibility)
2989 return RUK_Unique;
2990
2991 // If we're not required to publish this symbol, hide it.
2992 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
2993 return RUK_NonUniqueHidden;
2994
2995 // If we're required to publish this symbol, as we might be under an
2996 // explicit instantiation, leave it with default visibility but
2997 // enable string-comparisons.
2998 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
2999 return RUK_NonUniqueVisible;
3000}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003001
3002static void emitCXXConstructor(CodeGenModule &CGM,
3003 const CXXConstructorDecl *ctor,
3004 StructorType ctorType) {
3005 if (!CGM.getTarget().getCXXABI().hasConstructorVariants()) {
3006 // If there are no constructor variants, always emit the complete
3007 // destructor.
3008 ctorType = StructorType::Complete;
3009 } else if (!ctor->getParent()->getNumVBases() &&
3010 (ctorType == StructorType::Complete ||
3011 ctorType == StructorType::Base)) {
3012 // The complete constructor is equivalent to the base constructor
3013 // for classes with no virtual bases. Try to emit it as an alias.
3014 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3015 GlobalDecl(ctor, Ctor_Complete), GlobalDecl(ctor, Ctor_Base), true);
3016 if (ctorType == StructorType::Complete && ProducedAlias)
3017 return;
3018 }
3019
3020 const CGFunctionInfo &fnInfo =
3021 CGM.getTypes().arrangeCXXStructorDeclaration(ctor, ctorType);
3022
3023 auto *fn = cast<llvm::Function>(
3024 CGM.getAddrOfCXXStructor(ctor, ctorType, &fnInfo, nullptr, true));
3025 GlobalDecl GD(ctor, toCXXCtorType(ctorType));
3026 CGM.setFunctionLinkage(GD, fn);
3027 CodeGenFunction(CGM).GenerateCode(GD, fn, fnInfo);
3028
3029 CGM.setFunctionDefinitionAttributes(ctor, fn);
3030 CGM.SetLLVMFunctionAttributesForDefinition(ctor, fn);
3031}
3032
3033static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3034 StructorType dtorType) {
3035 // The complete destructor is equivalent to the base destructor for
3036 // classes with no virtual bases, so try to emit it as an alias.
3037 if (!dtor->getParent()->getNumVBases() &&
3038 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3039 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3040 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3041 if (ProducedAlias) {
3042 if (dtorType == StructorType::Complete)
3043 return;
3044 if (dtor->isVirtual())
3045 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3046 }
3047 }
3048
3049 // The base destructor is equivalent to the base destructor of its
3050 // base class if there is exactly one non-virtual base class with a
3051 // non-trivial destructor, there are no fields with a non-trivial
3052 // destructor, and the body of the destructor is trivial.
3053 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3054 return;
3055
3056 const CGFunctionInfo &fnInfo =
3057 CGM.getTypes().arrangeCXXStructorDeclaration(dtor, dtorType);
3058
3059 auto *fn = cast<llvm::Function>(
3060 CGM.getAddrOfCXXStructor(dtor, dtorType, &fnInfo, nullptr, true));
3061
3062 GlobalDecl GD(dtor, toCXXDtorType(dtorType));
3063 CGM.setFunctionLinkage(GD, fn);
3064 CodeGenFunction(CGM).GenerateCode(GD, fn, fnInfo);
3065
3066 CGM.setFunctionDefinitionAttributes(dtor, fn);
3067 CGM.SetLLVMFunctionAttributesForDefinition(dtor, fn);
3068}
3069
3070void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3071 StructorType Type) {
3072 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3073 emitCXXConstructor(CGM, CD, Type);
3074 return;
3075 }
3076 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3077}