blob: 824eba9fdb19ba29f636ebd37d1d8a9de5495d83 [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,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000238 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000239 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000240 CodeGenModule &CGM,
241 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
242 CXXThreadLocals,
243 ArrayRef<llvm::Function *> CXXThreadLocalInits,
244 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
245
246 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000247 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
248 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000249
Craig Topper4f12f102014-03-12 06:41:41 +0000250 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000251
252 /**************************** RTTI Uniqueness ******************************/
253
254protected:
255 /// Returns true if the ABI requires RTTI type_info objects to be unique
256 /// across a program.
257 virtual bool shouldRTTIBeUnique() const { return true; }
258
259public:
260 /// What sort of unique-RTTI behavior should we use?
261 enum RTTIUniquenessKind {
262 /// We are guaranteeing, or need to guarantee, that the RTTI string
263 /// is unique.
264 RUK_Unique,
265
266 /// We are not guaranteeing uniqueness for the RTTI string, so we
267 /// can demote to hidden visibility but must use string comparisons.
268 RUK_NonUniqueHidden,
269
270 /// We are not guaranteeing uniqueness for the RTTI string, so we
271 /// have to use string comparisons, but we also have to emit it with
272 /// non-hidden visibility.
273 RUK_NonUniqueVisible
274 };
275
276 /// Return the required visibility status for the given type and linkage in
277 /// the current ABI.
278 RTTIUniquenessKind
279 classifyRTTIUniqueness(QualType CanTy,
280 llvm::GlobalValue::LinkageTypes Linkage) const;
281 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000282
283 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000284};
John McCall86353412010-08-21 22:46:04 +0000285
286class ARMCXXABI : public ItaniumCXXABI {
287public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000288 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
289 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
290 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000291
Craig Topper4f12f102014-03-12 06:41:41 +0000292 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000293 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
294 isa<CXXDestructorDecl>(GD.getDecl()) &&
295 GD.getDtorType() != Dtor_Deleting));
296 }
John McCall5d865c322010-08-31 07:33:07 +0000297
Craig Topper4f12f102014-03-12 06:41:41 +0000298 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
299 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000300
Craig Topper4f12f102014-03-12 06:41:41 +0000301 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000302 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
303 llvm::Value *NewPtr,
304 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000305 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000306 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000307 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000308 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000309};
Tim Northovera2ee4332014-03-29 15:09:45 +0000310
311class iOS64CXXABI : public ARMCXXABI {
312public:
313 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000314
315 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000316 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000317};
Charles Davis4e786dd2010-05-25 19:52:27 +0000318}
319
Charles Davis53c59df2010-08-16 03:33:14 +0000320CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000321 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000322 // For IR-generation purposes, there's no significant difference
323 // between the ARM and iOS ABIs.
324 case TargetCXXABI::GenericARM:
325 case TargetCXXABI::iOS:
326 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000327
Tim Northovera2ee4332014-03-29 15:09:45 +0000328 case TargetCXXABI::iOS64:
329 return new iOS64CXXABI(CGM);
330
Tim Northover9bb857a2013-01-31 12:13:10 +0000331 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
332 // include the other 32-bit ARM oddities: constructor/destructor return values
333 // and array cookies.
334 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000335 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
336 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000337
John McCall57625922013-01-25 23:36:14 +0000338 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000339 if (CGM.getContext().getTargetInfo().getTriple().getArch()
340 == llvm::Triple::le32) {
341 // For PNaCl, use ARM-style method pointers so that PNaCl code
342 // does not assume anything about the alignment of function
343 // pointers.
344 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
345 /* UseARMGuardVarABI = */ false);
346 }
John McCall57625922013-01-25 23:36:14 +0000347 return new ItaniumCXXABI(CGM);
348
349 case TargetCXXABI::Microsoft:
350 llvm_unreachable("Microsoft ABI is not Itanium-based");
351 }
352 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000353}
354
Chris Lattnera5f58b02011-07-09 17:41:47 +0000355llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000356ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
357 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000358 return CGM.PtrDiffTy;
359 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000360}
361
John McCalld9c6c0b2010-08-22 00:59:17 +0000362/// In the Itanium and ARM ABIs, method pointers have the form:
363/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
364///
365/// In the Itanium ABI:
366/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
367/// - the this-adjustment is (memptr.adj)
368/// - the virtual offset is (memptr.ptr - 1)
369///
370/// In the ARM ABI:
371/// - method pointers are virtual if (memptr.adj & 1) is nonzero
372/// - the this-adjustment is (memptr.adj >> 1)
373/// - the virtual offset is (memptr.ptr)
374/// ARM uses 'adj' for the virtual flag because Thumb functions
375/// may be only single-byte aligned.
376///
377/// If the member is virtual, the adjusted 'this' pointer points
378/// to a vtable pointer from which the virtual offset is applied.
379///
380/// If the member is non-virtual, memptr.ptr is the address of
381/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000382llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
383 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
384 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000385 CGBuilderTy &Builder = CGF.Builder;
386
387 const FunctionProtoType *FPT =
388 MPT->getPointeeType()->getAs<FunctionProtoType>();
389 const CXXRecordDecl *RD =
390 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
391
Chris Lattner2192fe52011-07-18 04:24:23 +0000392 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000393 CGM.getTypes().GetFunctionType(
394 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000395
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000396 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000397
John McCalld9c6c0b2010-08-22 00:59:17 +0000398 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
399 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
400 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
401
John McCalla1dee5302010-08-22 10:59:02 +0000402 // Extract memptr.adj, which is in the second field.
403 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000404
405 // Compute the true adjustment.
406 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000407 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000408 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000409
410 // Apply the adjustment and cast back to the original struct type
411 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000412 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
413 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
414 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000415
416 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000417 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000418
419 // If the LSB in the function pointer is 1, the function pointer points to
420 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000421 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000422 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000423 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
424 else
425 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
426 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000427 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
428
429 // In the virtual path, the adjustment left 'This' pointing to the
430 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000431 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000432 CGF.EmitBlock(FnVirtual);
433
434 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000435 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000436 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000437
438 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000439 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000440 if (!UseARMMethodPtrABI)
441 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000442 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000443
444 // Load the virtual function to call.
445 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000446 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000447 CGF.EmitBranch(FnEnd);
448
449 // In the non-virtual path, the function pointer is actually a
450 // function pointer.
451 CGF.EmitBlock(FnNonVirtual);
452 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000453 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000454
455 // We're done.
456 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000457 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000458 Callee->addIncoming(VirtualFn, FnVirtual);
459 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
460 return Callee;
461}
John McCalla8bbb822010-08-22 03:04:22 +0000462
John McCallc134eb52010-08-31 21:07:20 +0000463/// Compute an l-value by applying the given pointer-to-member to a
464/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000465llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
466 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
467 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000468 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000469
470 CGBuilderTy &Builder = CGF.Builder;
471
Micah Villmowea2fea22012-10-25 15:39:14 +0000472 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000473
474 // Cast to char*.
475 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
476
477 // Apply the offset, which we assume is non-null.
478 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
479
480 // Cast the address to the appropriate pointer type, adopting the
481 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000482 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000483 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000484 return Builder.CreateBitCast(Addr, PType);
485}
486
John McCallc62bb392012-02-15 01:22:51 +0000487/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
488/// conversion.
489///
490/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000491///
492/// Obligatory offset/adjustment diagram:
493/// <-- offset --> <-- adjustment -->
494/// |--------------------------|----------------------|--------------------|
495/// ^Derived address point ^Base address point ^Member address point
496///
497/// So when converting a base member pointer to a derived member pointer,
498/// we add the offset to the adjustment because the address point has
499/// decreased; and conversely, when converting a derived MP to a base MP
500/// we subtract the offset from the adjustment because the address point
501/// has increased.
502///
503/// The standard forbids (at compile time) conversion to and from
504/// virtual bases, which is why we don't have to consider them here.
505///
506/// The standard forbids (at run time) casting a derived MP to a base
507/// MP when the derived MP does not point to a member of the base.
508/// This is why -1 is a reasonable choice for null data member
509/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000510llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000511ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
512 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000513 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000514 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000515 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
516 E->getCastKind() == CK_ReinterpretMemberPointer);
517
518 // Under Itanium, reinterprets don't require any additional processing.
519 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
520
521 // Use constant emission if we can.
522 if (isa<llvm::Constant>(src))
523 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
524
525 llvm::Constant *adj = getMemberPointerAdjustment(E);
526 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000527
528 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000529 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000530
John McCallc62bb392012-02-15 01:22:51 +0000531 const MemberPointerType *destTy =
532 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000533
John McCall7a9aac22010-08-23 01:21:21 +0000534 // For member data pointers, this is just a matter of adding the
535 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000536 if (destTy->isMemberDataPointer()) {
537 llvm::Value *dst;
538 if (isDerivedToBase)
539 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000540 else
John McCallc62bb392012-02-15 01:22:51 +0000541 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000542
543 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000544 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
545 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
546 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000547 }
548
John McCalla1dee5302010-08-22 10:59:02 +0000549 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000550 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000551 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
552 offset <<= 1;
553 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000554 }
555
John McCallc62bb392012-02-15 01:22:51 +0000556 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
557 llvm::Value *dstAdj;
558 if (isDerivedToBase)
559 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000560 else
John McCallc62bb392012-02-15 01:22:51 +0000561 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000562
John McCallc62bb392012-02-15 01:22:51 +0000563 return Builder.CreateInsertValue(src, dstAdj, 1);
564}
565
566llvm::Constant *
567ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
568 llvm::Constant *src) {
569 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
570 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
571 E->getCastKind() == CK_ReinterpretMemberPointer);
572
573 // Under Itanium, reinterprets don't require any additional processing.
574 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
575
576 // If the adjustment is trivial, we don't need to do anything.
577 llvm::Constant *adj = getMemberPointerAdjustment(E);
578 if (!adj) return src;
579
580 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
581
582 const MemberPointerType *destTy =
583 E->getType()->castAs<MemberPointerType>();
584
585 // For member data pointers, this is just a matter of adding the
586 // offset if the source is non-null.
587 if (destTy->isMemberDataPointer()) {
588 // null maps to null.
589 if (src->isAllOnesValue()) return src;
590
591 if (isDerivedToBase)
592 return llvm::ConstantExpr::getNSWSub(src, adj);
593 else
594 return llvm::ConstantExpr::getNSWAdd(src, adj);
595 }
596
597 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000598 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000599 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
600 offset <<= 1;
601 adj = llvm::ConstantInt::get(adj->getType(), offset);
602 }
603
604 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
605 llvm::Constant *dstAdj;
606 if (isDerivedToBase)
607 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
608 else
609 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
610
611 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000612}
John McCall84fa5102010-08-22 04:16:24 +0000613
614llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000615ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000616 // Itanium C++ ABI 2.3:
617 // A NULL pointer is represented as -1.
618 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000619 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000620
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000621 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000622 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000623 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000624}
625
John McCallf3a88602011-02-03 08:15:49 +0000626llvm::Constant *
627ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
628 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000629 // Itanium C++ ABI 2.3:
630 // A pointer to data member is an offset from the base address of
631 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000632 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000633}
634
John McCall2979fe02011-04-12 00:42:48 +0000635llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000636 return BuildMemberPointer(MD, CharUnits::Zero());
637}
638
639llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
640 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000641 assert(MD->isInstance() && "Member function must not be static!");
642 MD = MD->getCanonicalDecl();
643
644 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000645
646 // Get the function pointer (or index if this is a virtual function).
647 llvm::Constant *MemPtr[2];
648 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000649 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000650
Ken Dyckdf016282011-04-09 01:30:02 +0000651 const ASTContext &Context = getContext();
652 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000653 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000654 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000655
Mark Seabornedf0d382013-07-24 16:25:13 +0000656 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000657 // ARM C++ ABI 3.2.1:
658 // This ABI specifies that adj contains twice the this
659 // adjustment, plus 1 if the member function is virtual. The
660 // least significant bit of adj then makes exactly the same
661 // discrimination as the least significant bit of ptr does for
662 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000663 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
664 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000665 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000666 } else {
667 // Itanium C++ ABI 2.3:
668 // For a virtual function, [the pointer field] is 1 plus the
669 // virtual table offset (in bytes) of the function,
670 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000671 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
672 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000673 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000674 }
675 } else {
John McCall2979fe02011-04-12 00:42:48 +0000676 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000677 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000678 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000679 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000680 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000681 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000682 } else {
John McCall2979fe02011-04-12 00:42:48 +0000683 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
684 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000685 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000686 }
John McCall2979fe02011-04-12 00:42:48 +0000687 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000688
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000689 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000690 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
691 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000692 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000693 }
John McCall1c456c82010-08-22 06:43:33 +0000694
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000695 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000696}
697
Richard Smithdafff942012-01-14 04:30:29 +0000698llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
699 QualType MPType) {
700 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
701 const ValueDecl *MPD = MP.getMemberPointerDecl();
702 if (!MPD)
703 return EmitNullMemberPointer(MPT);
704
Reid Kleckner452abac2013-05-09 21:01:17 +0000705 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000706
707 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
708 return BuildMemberPointer(MD, ThisAdjustment);
709
710 CharUnits FieldOffset =
711 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
712 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
713}
714
John McCall131d97d2010-08-22 08:30:07 +0000715/// The comparison algorithm is pretty easy: the member pointers are
716/// the same if they're either bitwise identical *or* both null.
717///
718/// ARM is different here only because null-ness is more complicated.
719llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000720ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
721 llvm::Value *L,
722 llvm::Value *R,
723 const MemberPointerType *MPT,
724 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000725 CGBuilderTy &Builder = CGF.Builder;
726
John McCall131d97d2010-08-22 08:30:07 +0000727 llvm::ICmpInst::Predicate Eq;
728 llvm::Instruction::BinaryOps And, Or;
729 if (Inequality) {
730 Eq = llvm::ICmpInst::ICMP_NE;
731 And = llvm::Instruction::Or;
732 Or = llvm::Instruction::And;
733 } else {
734 Eq = llvm::ICmpInst::ICMP_EQ;
735 And = llvm::Instruction::And;
736 Or = llvm::Instruction::Or;
737 }
738
John McCall7a9aac22010-08-23 01:21:21 +0000739 // Member data pointers are easy because there's a unique null
740 // value, so it just comes down to bitwise equality.
741 if (MPT->isMemberDataPointer())
742 return Builder.CreateICmp(Eq, L, R);
743
744 // For member function pointers, the tautologies are more complex.
745 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000746 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000747 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000748 // (L == R) <==> (L.ptr == R.ptr &&
749 // (L.adj == R.adj ||
750 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000751 // The inequality tautologies have exactly the same structure, except
752 // applying De Morgan's laws.
753
754 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
755 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
756
John McCall131d97d2010-08-22 08:30:07 +0000757 // This condition tests whether L.ptr == R.ptr. This must always be
758 // true for equality to hold.
759 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
760
761 // This condition, together with the assumption that L.ptr == R.ptr,
762 // tests whether the pointers are both null. ARM imposes an extra
763 // condition.
764 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
765 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
766
767 // This condition tests whether L.adj == R.adj. If this isn't
768 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000769 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
770 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000771 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
772
773 // Null member function pointers on ARM clear the low bit of Adj,
774 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000775 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000776 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
777
778 // Compute (l.adj | r.adj) & 1 and test it against zero.
779 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
780 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
781 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
782 "cmp.or.adj");
783 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
784 }
785
786 // Tie together all our conditions.
787 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
788 Result = Builder.CreateBinOp(And, PtrEq, Result,
789 Inequality ? "memptr.ne" : "memptr.eq");
790 return Result;
791}
792
793llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000794ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
795 llvm::Value *MemPtr,
796 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000797 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000798
799 /// For member data pointers, this is just a check against -1.
800 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000801 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000802 llvm::Value *NegativeOne =
803 llvm::Constant::getAllOnesValue(MemPtr->getType());
804 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
805 }
John McCall131d97d2010-08-22 08:30:07 +0000806
Daniel Dunbar914bc412011-04-19 23:10:47 +0000807 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000808 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000809
810 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
811 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
812
Daniel Dunbar914bc412011-04-19 23:10:47 +0000813 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
814 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000815 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000816 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000817 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000818 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000819 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
820 "memptr.isvirtual");
821 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000822 }
823
824 return Result;
825}
John McCall1c456c82010-08-22 06:43:33 +0000826
Reid Kleckner40ca9132014-05-13 22:05:45 +0000827bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
828 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
829 if (!RD)
830 return false;
831
Reid Klecknerd355ca72014-05-15 01:26:32 +0000832 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
833 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
834 // special members.
835 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000836 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
837 return true;
838 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000839 return false;
840}
841
John McCall614dbdc2010-08-22 21:01:12 +0000842/// The Itanium ABI requires non-zero initialization only for data
843/// member pointers, for which '0' is a valid offset.
844bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
845 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000846}
John McCall5d865c322010-08-31 07:33:07 +0000847
John McCall82fb8922012-09-25 10:10:39 +0000848/// The Itanium ABI always places an offset to the complete object
849/// at entry -2 in the vtable.
850llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
851 llvm::Value *ptr,
852 QualType type) {
853 // Grab the vtable pointer as an intptr_t*.
854 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
855
856 // Track back to entry -2 and pull out the offset there.
857 llvm::Value *offsetPtr =
858 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
859 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
860 offset->setAlignment(CGF.PointerAlignInBytes);
861
862 // Apply the offset.
863 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
864 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
865}
866
David Majnemer1162d252014-06-22 19:05:33 +0000867static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
868 // void *__dynamic_cast(const void *sub,
869 // const abi::__class_type_info *src,
870 // const abi::__class_type_info *dst,
871 // std::ptrdiff_t src2dst_offset);
872
873 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
874 llvm::Type *PtrDiffTy =
875 CGF.ConvertType(CGF.getContext().getPointerDiffType());
876
877 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
878
879 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
880
881 // Mark the function as nounwind readonly.
882 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
883 llvm::Attribute::ReadOnly };
884 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
885 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
886
887 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
888}
889
890static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
891 // void __cxa_bad_cast();
892 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
893 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
894}
895
896/// \brief Compute the src2dst_offset hint as described in the
897/// Itanium C++ ABI [2.9.7]
898static CharUnits computeOffsetHint(ASTContext &Context,
899 const CXXRecordDecl *Src,
900 const CXXRecordDecl *Dst) {
901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
902 /*DetectVirtual=*/false);
903
904 // If Dst is not derived from Src we can skip the whole computation below and
905 // return that Src is not a public base of Dst. Record all inheritance paths.
906 if (!Dst->isDerivedFrom(Src, Paths))
907 return CharUnits::fromQuantity(-2ULL);
908
909 unsigned NumPublicPaths = 0;
910 CharUnits Offset;
911
912 // Now walk all possible inheritance paths.
913 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
914 ++I) {
915 if (I->Access != AS_public) // Ignore non-public inheritance.
916 continue;
917
918 ++NumPublicPaths;
919
920 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
921 // If the path contains a virtual base class we can't give any hint.
922 // -1: no hint.
923 if (J->Base->isVirtual())
924 return CharUnits::fromQuantity(-1ULL);
925
926 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
927 continue;
928
929 // Accumulate the base class offsets.
930 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
931 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
932 }
933 }
934
935 // -2: Src is not a public base of Dst.
936 if (NumPublicPaths == 0)
937 return CharUnits::fromQuantity(-2ULL);
938
939 // -3: Src is a multiple public base type but never a virtual base type.
940 if (NumPublicPaths > 1)
941 return CharUnits::fromQuantity(-3ULL);
942
943 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
944 // Return the offset of Src from the origin of Dst.
945 return Offset;
946}
947
948static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
949 // void __cxa_bad_typeid();
950 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
951
952 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
953}
954
955bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
956 QualType SrcRecordTy) {
957 return IsDeref;
958}
959
960void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
961 llvm::Value *Fn = getBadTypeidFn(CGF);
962 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
963 CGF.Builder.CreateUnreachable();
964}
965
966llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
967 QualType SrcRecordTy,
968 llvm::Value *ThisPtr,
969 llvm::Type *StdTypeInfoPtrTy) {
970 llvm::Value *Value =
971 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
972
973 // Load the type info.
974 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
975 return CGF.Builder.CreateLoad(Value);
976}
977
978bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
979 QualType SrcRecordTy) {
980 return SrcIsPtr;
981}
982
983llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
984 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
985 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
986 llvm::Type *PtrDiffLTy =
987 CGF.ConvertType(CGF.getContext().getPointerDiffType());
988 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
989
990 llvm::Value *SrcRTTI =
991 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
992 llvm::Value *DestRTTI =
993 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
994
995 // Compute the offset hint.
996 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
997 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
998 llvm::Value *OffsetHint = llvm::ConstantInt::get(
999 PtrDiffLTy,
1000 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1001
1002 // Emit the call to __dynamic_cast.
1003 Value = CGF.EmitCastToVoidPtr(Value);
1004
1005 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1006 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1007 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1008
1009 /// C++ [expr.dynamic.cast]p9:
1010 /// A failed cast to reference type throws std::bad_cast
1011 if (DestTy->isReferenceType()) {
1012 llvm::BasicBlock *BadCastBlock =
1013 CGF.createBasicBlock("dynamic_cast.bad_cast");
1014
1015 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1016 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1017
1018 CGF.EmitBlock(BadCastBlock);
1019 EmitBadCastCall(CGF);
1020 }
1021
1022 return Value;
1023}
1024
1025llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1026 llvm::Value *Value,
1027 QualType SrcRecordTy,
1028 QualType DestTy) {
1029 llvm::Type *PtrDiffLTy =
1030 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1031 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1032
1033 // Get the vtable pointer.
1034 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1035
1036 // Get the offset-to-top from the vtable.
1037 llvm::Value *OffsetToTop =
1038 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1039 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1040
1041 // Finally, add the offset to the pointer.
1042 Value = CGF.EmitCastToVoidPtr(Value);
1043 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1044
1045 return CGF.Builder.CreateBitCast(Value, DestLTy);
1046}
1047
1048bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1049 llvm::Value *Fn = getBadCastFn(CGF);
1050 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1051 CGF.Builder.CreateUnreachable();
1052 return true;
1053}
1054
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001055llvm::Value *
1056ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1057 llvm::Value *This,
1058 const CXXRecordDecl *ClassDecl,
1059 const CXXRecordDecl *BaseClassDecl) {
1060 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1061 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001062 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1063 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001064
1065 llvm::Value *VBaseOffsetPtr =
1066 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1067 "vbase.offset.ptr");
1068 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1069 CGM.PtrDiffTy->getPointerTo());
1070
1071 llvm::Value *VBaseOffset =
1072 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1073
1074 return VBaseOffset;
1075}
1076
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001077void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1078 // Just make sure we're in sync with TargetCXXABI.
1079 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1080
Rafael Espindolac3cde362013-12-09 14:51:17 +00001081 // The constructor used for constructing this as a base class;
1082 // ignores virtual bases.
1083 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1084
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001085 // The constructor used for constructing this as a complete class;
1086 // constucts the virtual bases, then calls the base constructor.
1087 if (!D->getParent()->isAbstract()) {
1088 // We don't need to emit the complete ctor if the class is abstract.
1089 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1090 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001091}
1092
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001093void
1094ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1095 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001096 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001097
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001098 // All parameters are already in place except VTT, which goes after 'this'.
1099 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001100
1101 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001102 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1103 ArgTys.insert(ArgTys.begin() + 1,
1104 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001105}
1106
Reid Klecknere7de47e2013-07-22 13:51:44 +00001107void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001108 // The destructor used for destructing this as a base class; ignores
1109 // virtual bases.
1110 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001111
1112 // The destructor used for destructing this as a most-derived class;
1113 // call the base destructor and then destructs any virtual bases.
1114 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1115
Rafael Espindolac3cde362013-12-09 14:51:17 +00001116 // The destructor in a virtual table is always a 'deleting'
1117 // destructor, which calls the complete destructor and then uses the
1118 // appropriate operator delete.
1119 if (D->isVirtual())
1120 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001121}
1122
Reid Kleckner89077a12013-12-17 19:46:40 +00001123void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1124 QualType &ResTy,
1125 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001126 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001127 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001128
1129 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001130 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001131 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001132
1133 // FIXME: avoid the fake decl
1134 QualType T = Context.getPointerType(Context.VoidPtrTy);
1135 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001136 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001137 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001138 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001139 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001140 }
1141}
1142
John McCall5d865c322010-08-31 07:33:07 +00001143void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1144 /// Initialize the 'this' slot.
1145 EmitThisParam(CGF);
1146
1147 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001148 if (getStructorImplicitParamDecl(CGF)) {
1149 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1150 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001151 }
John McCall5d865c322010-08-31 07:33:07 +00001152
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001153 /// If this is a function that the ABI specifies returns 'this', initialize
1154 /// the return slot to 'this' at the start of the function.
1155 ///
1156 /// Unlike the setting of return types, this is done within the ABI
1157 /// implementation instead of by clients of CGCXXABI because:
1158 /// 1) getThisValue is currently protected
1159 /// 2) in theory, an ABI could implement 'this' returns some other way;
1160 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001161 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001162 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001163}
1164
Reid Kleckner89077a12013-12-17 19:46:40 +00001165unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1166 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1167 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1168 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1169 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001170
Reid Kleckner89077a12013-12-17 19:46:40 +00001171 // Insert the implicit 'vtt' argument as the second argument.
1172 llvm::Value *VTT =
1173 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1174 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1175 Args.insert(Args.begin() + 1,
1176 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1177 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001178}
1179
1180void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1181 const CXXDestructorDecl *DD,
1182 CXXDtorType Type, bool ForVirtualBase,
1183 bool Delegating, llvm::Value *This) {
1184 GlobalDecl GD(DD, Type);
1185 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1186 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1187
Craig Topper8a13c412014-05-21 05:09:00 +00001188 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001189 if (getContext().getLangOpts().AppleKext)
1190 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1191
1192 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001193 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001194
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001195 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1196 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001197}
1198
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001199void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1200 const CXXRecordDecl *RD) {
1201 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1202 if (VTable->hasInitializer())
1203 return;
1204
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001205 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001206 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1207 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001208 llvm::Constant *RTTI =
1209 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001210
1211 // Create and set the initializer.
1212 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1213 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001214 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001215 VTable->setInitializer(Init);
1216
1217 // Set the correct linkage.
1218 VTable->setLinkage(Linkage);
1219
1220 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001221 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001222
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001223 // Use pointer alignment for the vtable. Otherwise we would align them based
1224 // on the size of the initializer which doesn't make sense as only single
1225 // values are read.
1226 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1227 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1228
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001229 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1230 // we will emit the typeinfo for the fundamental types. This is the
1231 // same behaviour as GCC.
1232 const DeclContext *DC = RD->getDeclContext();
1233 if (RD->getIdentifier() &&
1234 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1235 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1236 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1237 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001238 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001239}
1240
1241llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1242 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1243 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1244 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1245 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1246
1247 llvm::Value *VTableAddressPoint;
1248 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1249 // Get the secondary vpointer index.
1250 uint64_t VirtualPointerIndex =
1251 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1252
1253 /// Load the VTT.
1254 llvm::Value *VTT = CGF.LoadCXXVTT();
1255 if (VirtualPointerIndex)
1256 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1257
1258 // And load the address point from the VTT.
1259 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1260 } else {
1261 llvm::Constant *VTable =
1262 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001263 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1264 .getVTableLayout(VTableClass)
1265 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001266 VTableAddressPoint =
1267 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1268 }
1269
1270 return VTableAddressPoint;
1271}
1272
1273llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1274 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1275 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1276
1277 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001278 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1279 .getVTableLayout(VTableClass)
1280 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001281 llvm::Value *Indices[] = {
1282 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1283 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1284 };
1285
1286 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1287}
1288
1289llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1290 CharUnits VPtrOffset) {
1291 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1292
1293 llvm::GlobalVariable *&VTable = VTables[RD];
1294 if (VTable)
1295 return VTable;
1296
1297 // Queue up this v-table for possible deferred emission.
1298 CGM.addDeferredVTable(RD);
1299
1300 SmallString<256> OutName;
1301 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001302 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001303 Out.flush();
1304 StringRef Name = OutName.str();
1305
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001306 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001307 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1308 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1309
1310 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1311 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1312 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001313
1314 if (RD->hasAttr<DLLImportAttr>())
1315 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1316 else if (RD->hasAttr<DLLExportAttr>())
1317 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1318
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001319 return VTable;
1320}
1321
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001322llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1323 GlobalDecl GD,
1324 llvm::Value *This,
1325 llvm::Type *Ty) {
1326 GD = GD.getCanonicalDecl();
1327 Ty = Ty->getPointerTo()->getPointerTo();
1328 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1329
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001330 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001331 llvm::Value *VFuncPtr =
1332 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1333 return CGF.Builder.CreateLoad(VFuncPtr);
1334}
1335
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001336void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1337 const CXXDestructorDecl *Dtor,
1338 CXXDtorType DtorType,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001339 llvm::Value *This,
1340 const CXXMemberCallExpr *CE) {
1341 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001342 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1343
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001344 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1345 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001346 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001347 llvm::Value *Callee =
1348 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001349
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001350 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1351 /*ImplicitParam=*/nullptr, QualType(), CE);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001352}
1353
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001354void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001355 CodeGenVTables &VTables = CGM.getVTables();
1356 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001357 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001358}
1359
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001360static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1361 llvm::Value *Ptr,
1362 int64_t NonVirtualAdjustment,
1363 int64_t VirtualAdjustment,
1364 bool IsReturnAdjustment) {
1365 if (!NonVirtualAdjustment && !VirtualAdjustment)
1366 return Ptr;
1367
1368 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1369 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1370
1371 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1372 // Perform the non-virtual adjustment for a base-to-derived cast.
1373 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1374 }
1375
1376 if (VirtualAdjustment) {
1377 llvm::Type *PtrDiffTy =
1378 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1379
1380 // Perform the virtual adjustment.
1381 llvm::Value *VTablePtrPtr =
1382 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1383
1384 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1385
1386 llvm::Value *OffsetPtr =
1387 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1388
1389 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1390
1391 // Load the adjustment offset from the vtable.
1392 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1393
1394 // Adjust our pointer.
1395 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1396 }
1397
1398 if (NonVirtualAdjustment && IsReturnAdjustment) {
1399 // Perform the non-virtual adjustment for a derived-to-base cast.
1400 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1401 }
1402
1403 // Cast back to the original type.
1404 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1405}
1406
1407llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1408 llvm::Value *This,
1409 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001410 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1411 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001412 /*IsReturnAdjustment=*/false);
1413}
1414
1415llvm::Value *
1416ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1417 const ReturnAdjustment &RA) {
1418 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1419 RA.Virtual.Itanium.VBaseOffsetOffset,
1420 /*IsReturnAdjustment=*/true);
1421}
1422
John McCall5d865c322010-08-31 07:33:07 +00001423void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1424 RValue RV, QualType ResultType) {
1425 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1426 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1427
1428 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001429 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001430 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1431 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1432 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1433}
John McCall8ed55a52010-09-02 09:58:18 +00001434
1435/************************** Array allocation cookies **************************/
1436
John McCallb91cd662012-05-01 05:23:51 +00001437CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1438 // The array cookie is a size_t; pad that up to the element alignment.
1439 // The cookie is actually right-justified in that space.
1440 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1441 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001442}
1443
1444llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1445 llvm::Value *NewPtr,
1446 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001447 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001448 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001449 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001450
Micah Villmowea2fea22012-10-25 15:39:14 +00001451 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001452
John McCall9bca9232010-09-02 10:25:57 +00001453 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001454 QualType SizeTy = Ctx.getSizeType();
1455 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1456
1457 // The size of the cookie.
1458 CharUnits CookieSize =
1459 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001460 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001461
1462 // Compute an offset to the cookie.
1463 llvm::Value *CookiePtr = NewPtr;
1464 CharUnits CookieOffset = CookieSize - SizeSize;
1465 if (!CookieOffset.isZero())
1466 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1467 CookieOffset.getQuantity());
1468
1469 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001470 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1471 llvm::Value *NumElementsPtr =
1472 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1473 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001474 if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001475 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001476 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001477 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1478 llvm::FunctionType *FTy =
1479 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1480 llvm::Constant *F =
1481 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1482 CGF.Builder.CreateCall(F, NumElementsPtr);
1483 }
John McCall8ed55a52010-09-02 09:58:18 +00001484
1485 // Finally, compute a pointer to the actual data buffer by skipping
1486 // over the cookie completely.
1487 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1488 CookieSize.getQuantity());
1489}
1490
John McCallb91cd662012-05-01 05:23:51 +00001491llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1492 llvm::Value *allocPtr,
1493 CharUnits cookieSize) {
1494 // The element size is right-justified in the cookie.
1495 llvm::Value *numElementsPtr = allocPtr;
1496 CharUnits numElementsOffset =
1497 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1498 if (!numElementsOffset.isZero())
1499 numElementsPtr =
1500 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1501 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001502
Micah Villmowea2fea22012-10-25 15:39:14 +00001503 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001504 numElementsPtr =
1505 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001506 if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1507 return CGF.Builder.CreateLoad(numElementsPtr);
1508 // In asan mode emit a function call instead of a regular load and let the
1509 // run-time deal with it: if the shadow is properly poisoned return the
1510 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1511 // We can't simply ignore this load using nosanitize metadata because
1512 // the metadata may be lost.
1513 llvm::FunctionType *FTy =
1514 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1515 llvm::Constant *F =
1516 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1517 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001518}
1519
John McCallb91cd662012-05-01 05:23:51 +00001520CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001521 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001522 // struct array_cookie {
1523 // std::size_t element_size; // element_size != 0
1524 // std::size_t element_count;
1525 // };
John McCallc19c7062013-01-25 23:36:19 +00001526 // But the base ABI doesn't give anything an alignment greater than
1527 // 8, so we can dismiss this as typical ABI-author blindness to
1528 // actual language complexity and round up to the element alignment.
1529 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1530 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001531}
1532
1533llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001534 llvm::Value *newPtr,
1535 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001536 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001537 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001538 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001539
John McCallc19c7062013-01-25 23:36:19 +00001540 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1541 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001542
1543 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001544 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001545
1546 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001547 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1548 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1549 getContext().getTypeSizeInChars(elementType).getQuantity());
1550 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001551
1552 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001553 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1554 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001555
1556 // Finally, compute a pointer to the actual data buffer by skipping
1557 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001558 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1559 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1560 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001561}
1562
John McCallb91cd662012-05-01 05:23:51 +00001563llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1564 llvm::Value *allocPtr,
1565 CharUnits cookieSize) {
1566 // The number of elements is at offset sizeof(size_t) relative to
1567 // the allocated pointer.
1568 llvm::Value *numElementsPtr
1569 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001570
Micah Villmowea2fea22012-10-25 15:39:14 +00001571 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001572 numElementsPtr =
1573 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1574 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001575}
1576
John McCall68ff0372010-09-08 01:44:27 +00001577/*********************** Static local initialization **************************/
1578
1579static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001580 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001581 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001582 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001583 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001584 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001585 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001586 llvm::AttributeSet::get(CGM.getLLVMContext(),
1587 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001588 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001589}
1590
1591static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001592 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001593 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001594 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001595 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001596 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001597 llvm::AttributeSet::get(CGM.getLLVMContext(),
1598 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001599 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001600}
1601
1602static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001603 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001604 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001605 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001606 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001607 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001608 llvm::AttributeSet::get(CGM.getLLVMContext(),
1609 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001610 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001611}
1612
1613namespace {
1614 struct CallGuardAbort : EHScopeStack::Cleanup {
1615 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001616 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001617
Craig Topper4f12f102014-03-12 06:41:41 +00001618 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001619 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1620 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001621 }
1622 };
1623}
1624
1625/// The ARM code here follows the Itanium code closely enough that we
1626/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001627void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1628 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001629 llvm::GlobalVariable *var,
1630 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001631 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001632
Richard Smithdbf74ba2013-04-14 23:01:42 +00001633 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001634 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001635 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1636 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001637
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001638 // If we have a global variable with internal linkage and thread-safe statics
1639 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001640 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1641
1642 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001643 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001644 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001645 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001646 // Guard variables are 64 bits in the generic ABI and size width on ARM
1647 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001648 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001649 }
John McCallb88a5662012-03-30 21:00:39 +00001650 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001651
John McCallb88a5662012-03-30 21:00:39 +00001652 // Create the guard variable if we don't already have it (as we
1653 // might if we're double-emitting this function body).
1654 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1655 if (!guard) {
1656 // Mangle the name for the guard.
1657 SmallString<256> guardName;
1658 {
1659 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001660 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001661 out.flush();
1662 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001663
John McCallb88a5662012-03-30 21:00:39 +00001664 // Create the guard variable with a zero-initializer.
1665 // Just absorb linkage and visibility from the guarded variable.
1666 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1667 false, var->getLinkage(),
1668 llvm::ConstantInt::get(guardTy, 0),
1669 guardName.str());
1670 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001671 // If the variable is thread-local, so is its guard variable.
1672 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001673
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001674 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1675 // as the associated data object
Reid Kleckner739aa122014-09-23 16:20:01 +00001676 if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001677 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName());
1678 guard->setComdat(C);
1679 var->setComdat(C);
1680 CGF.CurFn->setComdat(C);
1681 }
1682
John McCallb88a5662012-03-30 21:00:39 +00001683 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1684 }
John McCall87590e62012-03-30 07:09:50 +00001685
John McCall68ff0372010-09-08 01:44:27 +00001686 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001687 //
John McCall68ff0372010-09-08 01:44:27 +00001688 // Itanium C++ ABI 3.3.2:
1689 // The following is pseudo-code showing how these functions can be used:
1690 // if (obj_guard.first_byte == 0) {
1691 // if ( __cxa_guard_acquire (&obj_guard) ) {
1692 // try {
1693 // ... initialize the object ...;
1694 // } catch (...) {
1695 // __cxa_guard_abort (&obj_guard);
1696 // throw;
1697 // }
1698 // ... queue object destructor with __cxa_atexit() ...;
1699 // __cxa_guard_release (&obj_guard);
1700 // }
1701 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001702
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001703 // Load the first byte of the guard variable.
1704 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001705 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001706 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001707
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001708 // Itanium ABI:
1709 // An implementation supporting thread-safety on multiprocessor
1710 // systems must also guarantee that references to the initialized
1711 // object do not occur before the load of the initialization flag.
1712 //
1713 // In LLVM, we do this by marking the load Acquire.
1714 if (threadsafe)
1715 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001716
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001717 // For ARM, we should only check the first bit, rather than the entire byte:
1718 //
1719 // ARM C++ ABI 3.2.3.1:
1720 // To support the potential use of initialization guard variables
1721 // as semaphores that are the target of ARM SWP and LDREX/STREX
1722 // synchronizing instructions we define a static initialization
1723 // guard variable to be a 4-byte aligned, 4-byte word with the
1724 // following inline access protocol.
1725 // #define INITIALIZED 1
1726 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1727 // if (__cxa_guard_acquire(&obj_guard))
1728 // ...
1729 // }
1730 //
1731 // and similarly for ARM64:
1732 //
1733 // ARM64 C++ ABI 3.2.2:
1734 // This ABI instead only specifies the value bit 0 of the static guard
1735 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1736 // variable is not initialized and 1 when it is.
1737 llvm::Value *V =
1738 (UseARMGuardVarABI && !useInt8GuardVariable)
1739 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1740 : LI;
1741 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001742
1743 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1744 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1745
1746 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001747 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001748
1749 CGF.EmitBlock(InitCheckBlock);
1750
1751 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001752 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001753 // Call __cxa_guard_acquire.
1754 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001755 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001756
1757 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1758
1759 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1760 InitBlock, EndBlock);
1761
1762 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001763 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001764
1765 CGF.EmitBlock(InitBlock);
1766 }
1767
1768 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001769 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001770
John McCall5aa52592011-06-17 07:33:57 +00001771 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001772 // Pop the guard-abort cleanup if we pushed one.
1773 CGF.PopCleanupBlock();
1774
1775 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001776 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001777 } else {
John McCallb88a5662012-03-30 21:00:39 +00001778 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001779 }
1780
1781 CGF.EmitBlock(EndBlock);
1782}
John McCallc84ed6a2012-05-01 06:13:13 +00001783
1784/// Register a global destructor using __cxa_atexit.
1785static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1786 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001787 llvm::Constant *addr,
1788 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001789 const char *Name = "__cxa_atexit";
1790 if (TLS) {
1791 const llvm::Triple &T = CGF.getTarget().getTriple();
1792 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1793 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001794
John McCallc84ed6a2012-05-01 06:13:13 +00001795 // We're assuming that the destructor function is something we can
1796 // reasonably call with the default CC. Go ahead and cast it to the
1797 // right prototype.
1798 llvm::Type *dtorTy =
1799 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1800
1801 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1802 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1803 llvm::FunctionType *atexitTy =
1804 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1805
1806 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001807 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001808 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1809 fn->setDoesNotThrow();
1810
1811 // Create a variable that binds the atexit to this shared object.
1812 llvm::Constant *handle =
1813 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1814
1815 llvm::Value *args[] = {
1816 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1817 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1818 handle
1819 };
John McCall882987f2013-02-28 19:01:20 +00001820 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001821}
1822
1823/// Register a global destructor as best as we know how.
1824void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001825 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001826 llvm::Constant *dtor,
1827 llvm::Constant *addr) {
1828 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001829 if (CGM.getCodeGenOpts().CXAAtExit)
1830 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1831
1832 if (D.getTLSKind())
1833 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001834
1835 // In Apple kexts, we want to add a global destructor entry.
1836 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001837 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001838 // Generate a global destructor entry.
1839 return CGM.AddCXXDtorEntry(dtor, addr);
1840 }
1841
David Blaikieebe87e12013-08-27 23:57:18 +00001842 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001843}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001844
David Majnemer9b21c332014-07-11 20:28:10 +00001845static bool isThreadWrapperReplaceable(const VarDecl *VD,
1846 CodeGen::CodeGenModule &CGM) {
1847 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1848 // OS X prefers to have references to thread local variables to go through
1849 // the thread wrapper instead of directly referencing the backing variable.
1850 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1851 CGM.getTarget().getTriple().isMacOSX();
1852}
1853
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001854/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001855/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001856/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001857static llvm::GlobalValue::LinkageTypes
1858getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1859 llvm::GlobalValue::LinkageTypes VarLinkage =
1860 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1861
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001862 // For internal linkage variables, we don't need an external or weak wrapper.
1863 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1864 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001865
David Majnemer9b21c332014-07-11 20:28:10 +00001866 // If the thread wrapper is replaceable, give it appropriate linkage.
1867 if (isThreadWrapperReplaceable(VD, CGM)) {
1868 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1869 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1870 return llvm::GlobalVariable::WeakAnyLinkage;
1871 return VarLinkage;
1872 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001873 return llvm::GlobalValue::WeakODRLinkage;
1874}
1875
1876llvm::Function *
1877ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001878 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001879 // Mangle the name for the thread_local wrapper function.
1880 SmallString<256> WrapperName;
1881 {
1882 llvm::raw_svector_ostream Out(WrapperName);
1883 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1884 Out.flush();
1885 }
1886
Alexander Musmanf94c3182014-09-26 06:28:25 +00001887 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001888 return cast<llvm::Function>(V);
1889
Alexander Musmanf94c3182014-09-26 06:28:25 +00001890 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001891 if (VD->getType()->isReferenceType())
1892 RetTy = RetTy->getPointerElementType();
1893
1894 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001895 llvm::Function *Wrapper =
1896 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1897 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001898 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001899 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001900 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001901 return Wrapper;
1902}
1903
1904void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00001905 CodeGenModule &CGM,
1906 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1907 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
1908 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1909 llvm::Function *InitFunc = nullptr;
1910 if (!CXXThreadLocalInits.empty()) {
1911 // Generate a guarded initialization function.
1912 llvm::FunctionType *FTy =
1913 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1914 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
1915 /*TLS=*/true);
1916 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
1917 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
1918 llvm::GlobalVariable::InternalLinkage,
1919 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
1920 Guard->setThreadLocal(true);
1921 CodeGenFunction(CGM)
1922 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
1923 }
1924 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
1925 const VarDecl *VD = CXXThreadLocals[I].first;
1926 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001927
David Majnemer9b21c332014-07-11 20:28:10 +00001928 // Some targets require that all access to thread local variables go through
1929 // the thread wrapper. This means that we cannot attempt to create a thread
1930 // wrapper or a thread helper.
1931 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1932 continue;
1933
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001934 // Mangle the name for the thread_local initialization function.
1935 SmallString<256> InitFnName;
1936 {
1937 llvm::raw_svector_ostream Out(InitFnName);
1938 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1939 Out.flush();
1940 }
1941
1942 // If we have a definition for the variable, emit the initialization
1943 // function as an alias to the global Init function (if any). Otherwise,
1944 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001945 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001946 bool InitIsInitFunc = false;
1947 if (VD->hasDefinition()) {
1948 InitIsInitFunc = true;
1949 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001950 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1951 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001952 } else {
1953 // Emit a weak global function referring to the initialization function.
1954 // This function will not exist if the TU defining the thread_local
1955 // variable in question does not need any dynamic initialization for
1956 // its thread_local variables.
1957 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1958 Init = llvm::Function::Create(
1959 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1960 &CGM.getModule());
1961 }
1962
1963 if (Init)
1964 Init->setVisibility(Var->getVisibility());
1965
1966 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1967 llvm::LLVMContext &Context = CGM.getModule().getContext();
1968 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1969 CGBuilderTy Builder(Entry);
1970 if (InitIsInitFunc) {
1971 if (Init)
1972 Builder.CreateCall(Init);
1973 } else {
1974 // Don't know whether we have an init function. Call it if it exists.
1975 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1976 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1977 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1978 Builder.CreateCondBr(Have, InitBB, ExitBB);
1979
1980 Builder.SetInsertPoint(InitBB);
1981 Builder.CreateCall(Init);
1982 Builder.CreateBr(ExitBB);
1983
1984 Builder.SetInsertPoint(ExitBB);
1985 }
1986
1987 // For a reference, the result of the wrapper function is a pointer to
1988 // the referenced object.
1989 llvm::Value *Val = Var;
1990 if (VD->getType()->isReferenceType()) {
1991 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1992 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1993 Val = LI;
1994 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00001995 if (Val->getType() != Wrapper->getReturnType())
1996 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
1997 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001998 Builder.CreateRet(Val);
1999 }
2000}
2001
Richard Smith0f383742014-03-26 22:48:22 +00002002LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2003 const VarDecl *VD,
2004 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002005 QualType T = VD->getType();
2006 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2007 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002008 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002009
2010 Val = CGF.Builder.CreateCall(Wrapper);
2011
2012 LValue LV;
2013 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002014 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002015 else
Richard Smith0f383742014-03-26 22:48:22 +00002016 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002017 // FIXME: need setObjCGCLValueClass?
2018 return LV;
2019}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002020
2021/// Return whether the given global decl needs a VTT parameter, which it does
2022/// if it's a base constructor or destructor with virtual bases.
2023bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2024 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2025
2026 // We don't have any virtual bases, just return early.
2027 if (!MD->getParent()->getNumVBases())
2028 return false;
2029
2030 // Check if we have a base constructor.
2031 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2032 return true;
2033
2034 // Check if we have a base destructor.
2035 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2036 return true;
2037
2038 return false;
2039}
David Majnemere2cb8d12014-07-07 06:20:47 +00002040
2041namespace {
2042class ItaniumRTTIBuilder {
2043 CodeGenModule &CGM; // Per-module state.
2044 llvm::LLVMContext &VMContext;
2045 const ItaniumCXXABI &CXXABI; // Per-module state.
2046
2047 /// Fields - The fields of the RTTI descriptor currently being built.
2048 SmallVector<llvm::Constant *, 16> Fields;
2049
2050 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2051 llvm::GlobalVariable *
2052 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2053
2054 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2055 /// descriptor of the given type.
2056 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2057
2058 /// BuildVTablePointer - Build the vtable pointer for the given type.
2059 void BuildVTablePointer(const Type *Ty);
2060
2061 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2062 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2063 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2064
2065 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2066 /// classes with bases that do not satisfy the abi::__si_class_type_info
2067 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2068 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2069
2070 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2071 /// for pointer types.
2072 void BuildPointerTypeInfo(QualType PointeeTy);
2073
2074 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2075 /// type_info for an object type.
2076 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2077
2078 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2079 /// struct, used for member pointer types.
2080 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2081
2082public:
2083 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2084 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2085
2086 // Pointer type info flags.
2087 enum {
2088 /// PTI_Const - Type has const qualifier.
2089 PTI_Const = 0x1,
2090
2091 /// PTI_Volatile - Type has volatile qualifier.
2092 PTI_Volatile = 0x2,
2093
2094 /// PTI_Restrict - Type has restrict qualifier.
2095 PTI_Restrict = 0x4,
2096
2097 /// PTI_Incomplete - Type is incomplete.
2098 PTI_Incomplete = 0x8,
2099
2100 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2101 /// (in pointer to member).
2102 PTI_ContainingClassIncomplete = 0x10
2103 };
2104
2105 // VMI type info flags.
2106 enum {
2107 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2108 VMI_NonDiamondRepeat = 0x1,
2109
2110 /// VMI_DiamondShaped - Class is diamond shaped.
2111 VMI_DiamondShaped = 0x2
2112 };
2113
2114 // Base class type info flags.
2115 enum {
2116 /// BCTI_Virtual - Base class is virtual.
2117 BCTI_Virtual = 0x1,
2118
2119 /// BCTI_Public - Base class is public.
2120 BCTI_Public = 0x2
2121 };
2122
2123 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2124 ///
2125 /// \param Force - true to force the creation of this RTTI value
2126 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2127};
2128}
2129
2130llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2131 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2132 SmallString<256> OutName;
2133 llvm::raw_svector_ostream Out(OutName);
2134 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2135 Out.flush();
2136 StringRef Name = OutName.str();
2137
2138 // We know that the mangled name of the type starts at index 4 of the
2139 // mangled name of the typename, so we can just index into it in order to
2140 // get the mangled name of the type.
2141 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2142 Name.substr(4));
2143
2144 llvm::GlobalVariable *GV =
2145 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2146
2147 GV->setInitializer(Init);
2148
2149 return GV;
2150}
2151
2152llvm::Constant *
2153ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2154 // Mangle the RTTI name.
2155 SmallString<256> OutName;
2156 llvm::raw_svector_ostream Out(OutName);
2157 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2158 Out.flush();
2159 StringRef Name = OutName.str();
2160
2161 // Look for an existing global.
2162 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2163
2164 if (!GV) {
2165 // Create a new global variable.
2166 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2167 /*Constant=*/true,
2168 llvm::GlobalValue::ExternalLinkage, nullptr,
2169 Name);
2170 }
2171
2172 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2173}
2174
2175/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2176/// info for that type is defined in the standard library.
2177static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2178 // Itanium C++ ABI 2.9.2:
2179 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2180 // the run-time support library. Specifically, the run-time support
2181 // library should contain type_info objects for the types X, X* and
2182 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2183 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2184 // long, unsigned long, long long, unsigned long long, float, double,
2185 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2186 // half-precision floating point types.
2187 switch (Ty->getKind()) {
2188 case BuiltinType::Void:
2189 case BuiltinType::NullPtr:
2190 case BuiltinType::Bool:
2191 case BuiltinType::WChar_S:
2192 case BuiltinType::WChar_U:
2193 case BuiltinType::Char_U:
2194 case BuiltinType::Char_S:
2195 case BuiltinType::UChar:
2196 case BuiltinType::SChar:
2197 case BuiltinType::Short:
2198 case BuiltinType::UShort:
2199 case BuiltinType::Int:
2200 case BuiltinType::UInt:
2201 case BuiltinType::Long:
2202 case BuiltinType::ULong:
2203 case BuiltinType::LongLong:
2204 case BuiltinType::ULongLong:
2205 case BuiltinType::Half:
2206 case BuiltinType::Float:
2207 case BuiltinType::Double:
2208 case BuiltinType::LongDouble:
2209 case BuiltinType::Char16:
2210 case BuiltinType::Char32:
2211 case BuiltinType::Int128:
2212 case BuiltinType::UInt128:
2213 case BuiltinType::OCLImage1d:
2214 case BuiltinType::OCLImage1dArray:
2215 case BuiltinType::OCLImage1dBuffer:
2216 case BuiltinType::OCLImage2d:
2217 case BuiltinType::OCLImage2dArray:
2218 case BuiltinType::OCLImage3d:
2219 case BuiltinType::OCLSampler:
2220 case BuiltinType::OCLEvent:
2221 return true;
2222
2223 case BuiltinType::Dependent:
2224#define BUILTIN_TYPE(Id, SingletonId)
2225#define PLACEHOLDER_TYPE(Id, SingletonId) \
2226 case BuiltinType::Id:
2227#include "clang/AST/BuiltinTypes.def"
2228 llvm_unreachable("asking for RRTI for a placeholder type!");
2229
2230 case BuiltinType::ObjCId:
2231 case BuiltinType::ObjCClass:
2232 case BuiltinType::ObjCSel:
2233 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2234 }
2235
2236 llvm_unreachable("Invalid BuiltinType Kind!");
2237}
2238
2239static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2240 QualType PointeeTy = PointerTy->getPointeeType();
2241 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2242 if (!BuiltinTy)
2243 return false;
2244
2245 // Check the qualifiers.
2246 Qualifiers Quals = PointeeTy.getQualifiers();
2247 Quals.removeConst();
2248
2249 if (!Quals.empty())
2250 return false;
2251
2252 return TypeInfoIsInStandardLibrary(BuiltinTy);
2253}
2254
2255/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2256/// information for the given type exists in the standard library.
2257static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2258 // Type info for builtin types is defined in the standard library.
2259 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2260 return TypeInfoIsInStandardLibrary(BuiltinTy);
2261
2262 // Type info for some pointer types to builtin types is defined in the
2263 // standard library.
2264 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2265 return TypeInfoIsInStandardLibrary(PointerTy);
2266
2267 return false;
2268}
2269
2270/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2271/// the given type exists somewhere else, and that we should not emit the type
2272/// information in this translation unit. Assumes that it is not a
2273/// standard-library type.
2274static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2275 QualType Ty) {
2276 ASTContext &Context = CGM.getContext();
2277
2278 // If RTTI is disabled, assume it might be disabled in the
2279 // translation unit that defines any potential key function, too.
2280 if (!Context.getLangOpts().RTTI) return false;
2281
2282 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2283 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2284 if (!RD->hasDefinition())
2285 return false;
2286
2287 if (!RD->isDynamicClass())
2288 return false;
2289
2290 // FIXME: this may need to be reconsidered if the key function
2291 // changes.
2292 return CGM.getVTables().isVTableExternal(RD);
2293 }
2294
2295 return false;
2296}
2297
2298/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2299static bool IsIncompleteClassType(const RecordType *RecordTy) {
2300 return !RecordTy->getDecl()->isCompleteDefinition();
2301}
2302
2303/// ContainsIncompleteClassType - Returns whether the given type contains an
2304/// incomplete class type. This is true if
2305///
2306/// * The given type is an incomplete class type.
2307/// * The given type is a pointer type whose pointee type contains an
2308/// incomplete class type.
2309/// * The given type is a member pointer type whose class is an incomplete
2310/// class type.
2311/// * The given type is a member pointer type whoise pointee type contains an
2312/// incomplete class type.
2313/// is an indirect or direct pointer to an incomplete class type.
2314static bool ContainsIncompleteClassType(QualType Ty) {
2315 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2316 if (IsIncompleteClassType(RecordTy))
2317 return true;
2318 }
2319
2320 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2321 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2322
2323 if (const MemberPointerType *MemberPointerTy =
2324 dyn_cast<MemberPointerType>(Ty)) {
2325 // Check if the class type is incomplete.
2326 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2327 if (IsIncompleteClassType(ClassType))
2328 return true;
2329
2330 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2331 }
2332
2333 return false;
2334}
2335
2336// CanUseSingleInheritance - Return whether the given record decl has a "single,
2337// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2338// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2339static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2340 // Check the number of bases.
2341 if (RD->getNumBases() != 1)
2342 return false;
2343
2344 // Get the base.
2345 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2346
2347 // Check that the base is not virtual.
2348 if (Base->isVirtual())
2349 return false;
2350
2351 // Check that the base is public.
2352 if (Base->getAccessSpecifier() != AS_public)
2353 return false;
2354
2355 // Check that the class is dynamic iff the base is.
2356 const CXXRecordDecl *BaseDecl =
2357 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2358 if (!BaseDecl->isEmpty() &&
2359 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2360 return false;
2361
2362 return true;
2363}
2364
2365void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2366 // abi::__class_type_info.
2367 static const char * const ClassTypeInfo =
2368 "_ZTVN10__cxxabiv117__class_type_infoE";
2369 // abi::__si_class_type_info.
2370 static const char * const SIClassTypeInfo =
2371 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2372 // abi::__vmi_class_type_info.
2373 static const char * const VMIClassTypeInfo =
2374 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2375
2376 const char *VTableName = nullptr;
2377
2378 switch (Ty->getTypeClass()) {
2379#define TYPE(Class, Base)
2380#define ABSTRACT_TYPE(Class, Base)
2381#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2382#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2383#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2384#include "clang/AST/TypeNodes.def"
2385 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2386
2387 case Type::LValueReference:
2388 case Type::RValueReference:
2389 llvm_unreachable("References shouldn't get here");
2390
2391 case Type::Auto:
2392 llvm_unreachable("Undeduced auto type shouldn't get here");
2393
2394 case Type::Builtin:
2395 // GCC treats vector and complex types as fundamental types.
2396 case Type::Vector:
2397 case Type::ExtVector:
2398 case Type::Complex:
2399 case Type::Atomic:
2400 // FIXME: GCC treats block pointers as fundamental types?!
2401 case Type::BlockPointer:
2402 // abi::__fundamental_type_info.
2403 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2404 break;
2405
2406 case Type::ConstantArray:
2407 case Type::IncompleteArray:
2408 case Type::VariableArray:
2409 // abi::__array_type_info.
2410 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2411 break;
2412
2413 case Type::FunctionNoProto:
2414 case Type::FunctionProto:
2415 // abi::__function_type_info.
2416 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2417 break;
2418
2419 case Type::Enum:
2420 // abi::__enum_type_info.
2421 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2422 break;
2423
2424 case Type::Record: {
2425 const CXXRecordDecl *RD =
2426 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2427
2428 if (!RD->hasDefinition() || !RD->getNumBases()) {
2429 VTableName = ClassTypeInfo;
2430 } else if (CanUseSingleInheritance(RD)) {
2431 VTableName = SIClassTypeInfo;
2432 } else {
2433 VTableName = VMIClassTypeInfo;
2434 }
2435
2436 break;
2437 }
2438
2439 case Type::ObjCObject:
2440 // Ignore protocol qualifiers.
2441 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2442
2443 // Handle id and Class.
2444 if (isa<BuiltinType>(Ty)) {
2445 VTableName = ClassTypeInfo;
2446 break;
2447 }
2448
2449 assert(isa<ObjCInterfaceType>(Ty));
2450 // Fall through.
2451
2452 case Type::ObjCInterface:
2453 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2454 VTableName = SIClassTypeInfo;
2455 } else {
2456 VTableName = ClassTypeInfo;
2457 }
2458 break;
2459
2460 case Type::ObjCObjectPointer:
2461 case Type::Pointer:
2462 // abi::__pointer_type_info.
2463 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2464 break;
2465
2466 case Type::MemberPointer:
2467 // abi::__pointer_to_member_type_info.
2468 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2469 break;
2470 }
2471
2472 llvm::Constant *VTable =
2473 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2474
2475 llvm::Type *PtrDiffTy =
2476 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2477
2478 // The vtable address point is 2.
2479 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2480 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2481 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2482
2483 Fields.push_back(VTable);
2484}
2485
2486/// \brief Return the linkage that the type info and type info name constants
2487/// should have for the given type.
2488static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2489 QualType Ty) {
2490 // Itanium C++ ABI 2.9.5p7:
2491 // In addition, it and all of the intermediate abi::__pointer_type_info
2492 // structs in the chain down to the abi::__class_type_info for the
2493 // incomplete class type must be prevented from resolving to the
2494 // corresponding type_info structs for the complete class type, possibly
2495 // by making them local static objects. Finally, a dummy class RTTI is
2496 // generated for the incomplete type that will not resolve to the final
2497 // complete class RTTI (because the latter need not exist), possibly by
2498 // making it a local static object.
2499 if (ContainsIncompleteClassType(Ty))
2500 return llvm::GlobalValue::InternalLinkage;
2501
2502 switch (Ty->getLinkage()) {
2503 case NoLinkage:
2504 case InternalLinkage:
2505 case UniqueExternalLinkage:
2506 return llvm::GlobalValue::InternalLinkage;
2507
2508 case VisibleNoLinkage:
2509 case ExternalLinkage:
2510 if (!CGM.getLangOpts().RTTI) {
2511 // RTTI is not enabled, which means that this type info struct is going
2512 // to be used for exception handling. Give it linkonce_odr linkage.
2513 return llvm::GlobalValue::LinkOnceODRLinkage;
2514 }
2515
2516 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2517 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2518 if (RD->hasAttr<WeakAttr>())
2519 return llvm::GlobalValue::WeakODRLinkage;
2520 if (RD->isDynamicClass())
2521 return CGM.getVTableLinkage(RD);
2522 }
2523
2524 return llvm::GlobalValue::LinkOnceODRLinkage;
2525 }
2526
2527 llvm_unreachable("Invalid linkage!");
2528}
2529
2530llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2531 // We want to operate on the canonical type.
2532 Ty = CGM.getContext().getCanonicalType(Ty);
2533
2534 // Check if we've already emitted an RTTI descriptor for this type.
2535 SmallString<256> OutName;
2536 llvm::raw_svector_ostream Out(OutName);
2537 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2538 Out.flush();
2539 StringRef Name = OutName.str();
2540
2541 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2542 if (OldGV && !OldGV->isDeclaration()) {
2543 assert(!OldGV->hasAvailableExternallyLinkage() &&
2544 "available_externally typeinfos not yet implemented");
2545
2546 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2547 }
2548
2549 // Check if there is already an external RTTI descriptor for this type.
2550 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2551 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2552 return GetAddrOfExternalRTTIDescriptor(Ty);
2553
2554 // Emit the standard library with external linkage.
2555 llvm::GlobalVariable::LinkageTypes Linkage;
2556 if (IsStdLib)
2557 Linkage = llvm::GlobalValue::ExternalLinkage;
2558 else
2559 Linkage = getTypeInfoLinkage(CGM, Ty);
2560
2561 // Add the vtable pointer.
2562 BuildVTablePointer(cast<Type>(Ty));
2563
2564 // And the name.
2565 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2566 llvm::Constant *TypeNameField;
2567
2568 // If we're supposed to demote the visibility, be sure to set a flag
2569 // to use a string comparison for type_info comparisons.
2570 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2571 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2572 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2573 // The flag is the sign bit, which on ARM64 is defined to be clear
2574 // for global pointers. This is very ARM64-specific.
2575 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2576 llvm::Constant *flag =
2577 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2578 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2579 TypeNameField =
2580 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2581 } else {
2582 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2583 }
2584 Fields.push_back(TypeNameField);
2585
2586 switch (Ty->getTypeClass()) {
2587#define TYPE(Class, Base)
2588#define ABSTRACT_TYPE(Class, Base)
2589#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2590#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2591#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2592#include "clang/AST/TypeNodes.def"
2593 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2594
2595 // GCC treats vector types as fundamental types.
2596 case Type::Builtin:
2597 case Type::Vector:
2598 case Type::ExtVector:
2599 case Type::Complex:
2600 case Type::BlockPointer:
2601 // Itanium C++ ABI 2.9.5p4:
2602 // abi::__fundamental_type_info adds no data members to std::type_info.
2603 break;
2604
2605 case Type::LValueReference:
2606 case Type::RValueReference:
2607 llvm_unreachable("References shouldn't get here");
2608
2609 case Type::Auto:
2610 llvm_unreachable("Undeduced auto type shouldn't get here");
2611
2612 case Type::ConstantArray:
2613 case Type::IncompleteArray:
2614 case Type::VariableArray:
2615 // Itanium C++ ABI 2.9.5p5:
2616 // abi::__array_type_info adds no data members to std::type_info.
2617 break;
2618
2619 case Type::FunctionNoProto:
2620 case Type::FunctionProto:
2621 // Itanium C++ ABI 2.9.5p5:
2622 // abi::__function_type_info adds no data members to std::type_info.
2623 break;
2624
2625 case Type::Enum:
2626 // Itanium C++ ABI 2.9.5p5:
2627 // abi::__enum_type_info adds no data members to std::type_info.
2628 break;
2629
2630 case Type::Record: {
2631 const CXXRecordDecl *RD =
2632 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2633 if (!RD->hasDefinition() || !RD->getNumBases()) {
2634 // We don't need to emit any fields.
2635 break;
2636 }
2637
2638 if (CanUseSingleInheritance(RD))
2639 BuildSIClassTypeInfo(RD);
2640 else
2641 BuildVMIClassTypeInfo(RD);
2642
2643 break;
2644 }
2645
2646 case Type::ObjCObject:
2647 case Type::ObjCInterface:
2648 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2649 break;
2650
2651 case Type::ObjCObjectPointer:
2652 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2653 break;
2654
2655 case Type::Pointer:
2656 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2657 break;
2658
2659 case Type::MemberPointer:
2660 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2661 break;
2662
2663 case Type::Atomic:
2664 // No fields, at least for the moment.
2665 break;
2666 }
2667
2668 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2669
2670 llvm::GlobalVariable *GV =
2671 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2672 /*Constant=*/true, Linkage, Init, Name);
2673
2674 // If there's already an old global variable, replace it with the new one.
2675 if (OldGV) {
2676 GV->takeName(OldGV);
2677 llvm::Constant *NewPtr =
2678 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2679 OldGV->replaceAllUsesWith(NewPtr);
2680 OldGV->eraseFromParent();
2681 }
2682
2683 // The Itanium ABI specifies that type_info objects must be globally
2684 // unique, with one exception: if the type is an incomplete class
2685 // type or a (possibly indirect) pointer to one. That exception
2686 // affects the general case of comparing type_info objects produced
2687 // by the typeid operator, which is why the comparison operators on
2688 // std::type_info generally use the type_info name pointers instead
2689 // of the object addresses. However, the language's built-in uses
2690 // of RTTI generally require class types to be complete, even when
2691 // manipulating pointers to those class types. This allows the
2692 // implementation of dynamic_cast to rely on address equality tests,
2693 // which is much faster.
2694
2695 // All of this is to say that it's important that both the type_info
2696 // object and the type_info name be uniqued when weakly emitted.
2697
2698 // Give the type_info object and name the formal visibility of the
2699 // type itself.
2700 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2701 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2702 // If the linkage is local, only default visibility makes sense.
2703 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2704 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2705 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2706 else
2707 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2708 TypeName->setVisibility(llvmVisibility);
2709 GV->setVisibility(llvmVisibility);
2710
2711 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2712}
2713
2714/// ComputeQualifierFlags - Compute the pointer type info flags from the
2715/// given qualifier.
2716static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2717 unsigned Flags = 0;
2718
2719 if (Quals.hasConst())
2720 Flags |= ItaniumRTTIBuilder::PTI_Const;
2721 if (Quals.hasVolatile())
2722 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2723 if (Quals.hasRestrict())
2724 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2725
2726 return Flags;
2727}
2728
2729/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2730/// for the given Objective-C object type.
2731void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2732 // Drop qualifiers.
2733 const Type *T = OT->getBaseType().getTypePtr();
2734 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2735
2736 // The builtin types are abi::__class_type_infos and don't require
2737 // extra fields.
2738 if (isa<BuiltinType>(T)) return;
2739
2740 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2741 ObjCInterfaceDecl *Super = Class->getSuperClass();
2742
2743 // Root classes are also __class_type_info.
2744 if (!Super) return;
2745
2746 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2747
2748 // Everything else is single inheritance.
2749 llvm::Constant *BaseTypeInfo =
2750 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2751 Fields.push_back(BaseTypeInfo);
2752}
2753
2754/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2755/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2756void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2757 // Itanium C++ ABI 2.9.5p6b:
2758 // It adds to abi::__class_type_info a single member pointing to the
2759 // type_info structure for the base type,
2760 llvm::Constant *BaseTypeInfo =
2761 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2762 Fields.push_back(BaseTypeInfo);
2763}
2764
2765namespace {
2766 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2767 /// a class hierarchy.
2768 struct SeenBases {
2769 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2770 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2771 };
2772}
2773
2774/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2775/// abi::__vmi_class_type_info.
2776///
2777static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2778 SeenBases &Bases) {
2779
2780 unsigned Flags = 0;
2781
2782 const CXXRecordDecl *BaseDecl =
2783 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2784
2785 if (Base->isVirtual()) {
2786 // Mark the virtual base as seen.
2787 if (!Bases.VirtualBases.insert(BaseDecl)) {
2788 // If this virtual base has been seen before, then the class is diamond
2789 // shaped.
2790 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2791 } else {
2792 if (Bases.NonVirtualBases.count(BaseDecl))
2793 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2794 }
2795 } else {
2796 // Mark the non-virtual base as seen.
2797 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2798 // If this non-virtual base has been seen before, then the class has non-
2799 // diamond shaped repeated inheritance.
2800 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2801 } else {
2802 if (Bases.VirtualBases.count(BaseDecl))
2803 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2804 }
2805 }
2806
2807 // Walk all bases.
2808 for (const auto &I : BaseDecl->bases())
2809 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2810
2811 return Flags;
2812}
2813
2814static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2815 unsigned Flags = 0;
2816 SeenBases Bases;
2817
2818 // Walk all bases.
2819 for (const auto &I : RD->bases())
2820 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2821
2822 return Flags;
2823}
2824
2825/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2826/// classes with bases that do not satisfy the abi::__si_class_type_info
2827/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2828void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2829 llvm::Type *UnsignedIntLTy =
2830 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2831
2832 // Itanium C++ ABI 2.9.5p6c:
2833 // __flags is a word with flags describing details about the class
2834 // structure, which may be referenced by using the __flags_masks
2835 // enumeration. These flags refer to both direct and indirect bases.
2836 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2837 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2838
2839 // Itanium C++ ABI 2.9.5p6c:
2840 // __base_count is a word with the number of direct proper base class
2841 // descriptions that follow.
2842 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2843
2844 if (!RD->getNumBases())
2845 return;
2846
2847 llvm::Type *LongLTy =
2848 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2849
2850 // Now add the base class descriptions.
2851
2852 // Itanium C++ ABI 2.9.5p6c:
2853 // __base_info[] is an array of base class descriptions -- one for every
2854 // direct proper base. Each description is of the type:
2855 //
2856 // struct abi::__base_class_type_info {
2857 // public:
2858 // const __class_type_info *__base_type;
2859 // long __offset_flags;
2860 //
2861 // enum __offset_flags_masks {
2862 // __virtual_mask = 0x1,
2863 // __public_mask = 0x2,
2864 // __offset_shift = 8
2865 // };
2866 // };
2867 for (const auto &Base : RD->bases()) {
2868 // The __base_type member points to the RTTI for the base type.
2869 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2870
2871 const CXXRecordDecl *BaseDecl =
2872 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2873
2874 int64_t OffsetFlags = 0;
2875
2876 // All but the lower 8 bits of __offset_flags are a signed offset.
2877 // For a non-virtual base, this is the offset in the object of the base
2878 // subobject. For a virtual base, this is the offset in the virtual table of
2879 // the virtual base offset for the virtual base referenced (negative).
2880 CharUnits Offset;
2881 if (Base.isVirtual())
2882 Offset =
2883 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2884 else {
2885 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2886 Offset = Layout.getBaseClassOffset(BaseDecl);
2887 };
2888
2889 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2890
2891 // The low-order byte of __offset_flags contains flags, as given by the
2892 // masks from the enumeration __offset_flags_masks.
2893 if (Base.isVirtual())
2894 OffsetFlags |= BCTI_Virtual;
2895 if (Base.getAccessSpecifier() == AS_public)
2896 OffsetFlags |= BCTI_Public;
2897
2898 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2899 }
2900}
2901
2902/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2903/// used for pointer types.
2904void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2905 Qualifiers Quals;
2906 QualType UnqualifiedPointeeTy =
2907 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2908
2909 // Itanium C++ ABI 2.9.5p7:
2910 // __flags is a flag word describing the cv-qualification and other
2911 // attributes of the type pointed to
2912 unsigned Flags = ComputeQualifierFlags(Quals);
2913
2914 // Itanium C++ ABI 2.9.5p7:
2915 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2916 // incomplete class type, the incomplete target type flag is set.
2917 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2918 Flags |= PTI_Incomplete;
2919
2920 llvm::Type *UnsignedIntLTy =
2921 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2922 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2923
2924 // Itanium C++ ABI 2.9.5p7:
2925 // __pointee is a pointer to the std::type_info derivation for the
2926 // unqualified type being pointed to.
2927 llvm::Constant *PointeeTypeInfo =
2928 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2929 Fields.push_back(PointeeTypeInfo);
2930}
2931
2932/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2933/// struct, used for member pointer types.
2934void
2935ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2936 QualType PointeeTy = Ty->getPointeeType();
2937
2938 Qualifiers Quals;
2939 QualType UnqualifiedPointeeTy =
2940 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2941
2942 // Itanium C++ ABI 2.9.5p7:
2943 // __flags is a flag word describing the cv-qualification and other
2944 // attributes of the type pointed to.
2945 unsigned Flags = ComputeQualifierFlags(Quals);
2946
2947 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2948
2949 // Itanium C++ ABI 2.9.5p7:
2950 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2951 // incomplete class type, the incomplete target type flag is set.
2952 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2953 Flags |= PTI_Incomplete;
2954
2955 if (IsIncompleteClassType(ClassType))
2956 Flags |= PTI_ContainingClassIncomplete;
2957
2958 llvm::Type *UnsignedIntLTy =
2959 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2960 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2961
2962 // Itanium C++ ABI 2.9.5p7:
2963 // __pointee is a pointer to the std::type_info derivation for the
2964 // unqualified type being pointed to.
2965 llvm::Constant *PointeeTypeInfo =
2966 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2967 Fields.push_back(PointeeTypeInfo);
2968
2969 // Itanium C++ ABI 2.9.5p9:
2970 // __context is a pointer to an abi::__class_type_info corresponding to the
2971 // class type containing the member pointed to
2972 // (e.g., the "A" in "int A::*").
2973 Fields.push_back(
2974 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2975}
2976
2977llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2978 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2979}
2980
2981void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2982 QualType PointerType = getContext().getPointerType(Type);
2983 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2984 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2985 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2986 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2987}
2988
2989void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2990 QualType FundamentalTypes[] = {
2991 getContext().VoidTy, getContext().NullPtrTy,
2992 getContext().BoolTy, getContext().WCharTy,
2993 getContext().CharTy, getContext().UnsignedCharTy,
2994 getContext().SignedCharTy, getContext().ShortTy,
2995 getContext().UnsignedShortTy, getContext().IntTy,
2996 getContext().UnsignedIntTy, getContext().LongTy,
2997 getContext().UnsignedLongTy, getContext().LongLongTy,
2998 getContext().UnsignedLongLongTy, getContext().HalfTy,
2999 getContext().FloatTy, getContext().DoubleTy,
3000 getContext().LongDoubleTy, getContext().Char16Ty,
3001 getContext().Char32Ty,
3002 };
3003 for (const QualType &FundamentalType : FundamentalTypes)
3004 EmitFundamentalRTTIDescriptor(FundamentalType);
3005}
3006
3007/// What sort of uniqueness rules should we use for the RTTI for the
3008/// given type?
3009ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3010 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3011 if (shouldRTTIBeUnique())
3012 return RUK_Unique;
3013
3014 // It's only necessary for linkonce_odr or weak_odr linkage.
3015 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3016 Linkage != llvm::GlobalValue::WeakODRLinkage)
3017 return RUK_Unique;
3018
3019 // It's only necessary with default visibility.
3020 if (CanTy->getVisibility() != DefaultVisibility)
3021 return RUK_Unique;
3022
3023 // If we're not required to publish this symbol, hide it.
3024 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3025 return RUK_NonUniqueHidden;
3026
3027 // If we're required to publish this symbol, as we might be under an
3028 // explicit instantiation, leave it with default visibility but
3029 // enable string-comparisons.
3030 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3031 return RUK_NonUniqueVisible;
3032}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003033
Rafael Espindola1e4df922014-09-16 15:18:21 +00003034// Find out how to codegen the complete destructor and constructor
3035namespace {
3036enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3037}
3038static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3039 const CXXMethodDecl *MD) {
3040 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3041 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003042
Rafael Espindola1e4df922014-09-16 15:18:21 +00003043 // The complete and base structors are not equivalent if there are any virtual
3044 // bases, so emit separate functions.
3045 if (MD->getParent()->getNumVBases())
3046 return StructorCodegen::Emit;
3047
3048 GlobalDecl AliasDecl;
3049 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3050 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3051 } else {
3052 const auto *CD = cast<CXXConstructorDecl>(MD);
3053 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3054 }
3055 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3056
3057 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3058 return StructorCodegen::RAUW;
3059
3060 // FIXME: Should we allow available_externally aliases?
3061 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3062 return StructorCodegen::RAUW;
3063
Rafael Espindola0806f982014-09-16 20:19:43 +00003064 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3065 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3066 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3067 return StructorCodegen::COMDAT;
3068 return StructorCodegen::Emit;
3069 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003070
3071 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003072}
3073
Rafael Espindola1e4df922014-09-16 15:18:21 +00003074static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3075 GlobalDecl AliasDecl,
3076 GlobalDecl TargetDecl) {
3077 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3078
3079 StringRef MangledName = CGM.getMangledName(AliasDecl);
3080 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3081 if (Entry && !Entry->isDeclaration())
3082 return;
3083
3084 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3085 llvm::PointerType *AliasType = Aliasee->getType();
3086
3087 // Create the alias with no name.
3088 auto *Alias = llvm::GlobalAlias::create(
3089 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3090
3091 // Switch any previous uses to the alias.
3092 if (Entry) {
3093 assert(Entry->getType() == AliasType &&
3094 "declaration exists with different type");
3095 Alias->takeName(Entry);
3096 Entry->replaceAllUsesWith(Alias);
3097 Entry->eraseFromParent();
3098 } else {
3099 Alias->setName(MangledName);
3100 }
3101
3102 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003103 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003104}
3105
3106void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3107 StructorType Type) {
3108 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3109 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3110
3111 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3112
3113 if (Type == StructorType::Complete) {
3114 GlobalDecl CompleteDecl;
3115 GlobalDecl BaseDecl;
3116 if (CD) {
3117 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3118 BaseDecl = GlobalDecl(CD, Ctor_Base);
3119 } else {
3120 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3121 BaseDecl = GlobalDecl(DD, Dtor_Base);
3122 }
3123
3124 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3125 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3126 return;
3127 }
3128
3129 if (CGType == StructorCodegen::RAUW) {
3130 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3131 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3132 CGM.addReplacement(MangledName, Aliasee);
3133 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003134 }
3135 }
3136
3137 // The base destructor is equivalent to the base destructor of its
3138 // base class if there is exactly one non-virtual base class with a
3139 // non-trivial destructor, there are no fields with a non-trivial
3140 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003141 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3142 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003143 return;
3144
Rafael Espindola1e4df922014-09-16 15:18:21 +00003145 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003146
Rafael Espindola1e4df922014-09-16 15:18:21 +00003147 if (CGType == StructorCodegen::COMDAT) {
3148 SmallString<256> Buffer;
3149 llvm::raw_svector_ostream Out(Buffer);
3150 if (DD)
3151 getMangleContext().mangleCXXDtorComdat(DD, Out);
3152 else
3153 getMangleContext().mangleCXXCtorComdat(CD, Out);
3154 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3155 Fn->setComdat(C);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003156 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003157}