blob: 14a2890b29cfe1365f18248bfb858865d634c8f8 [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
David Majnemer08681372014-11-01 07:37:17 +0000109 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000110 llvm::Value *Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000111 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000112
David Majnemer442d0a22014-11-25 07:20:20 +0000113 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
114
David Majnemere2cb8d12014-07-07 06:20:47 +0000115 void EmitFundamentalRTTIDescriptor(QualType Type);
116 void EmitFundamentalRTTIDescriptors();
117 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
118
David Majnemer1162d252014-06-22 19:05:33 +0000119 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
120 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
121 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
122 llvm::Value *ThisPtr,
123 llvm::Type *StdTypeInfoPtrTy) override;
124
125 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
126 QualType SrcRecordTy) override;
127
128 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
129 QualType SrcRecordTy, QualType DestTy,
130 QualType DestRecordTy,
131 llvm::BasicBlock *CastEnd) override;
132
133 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
134 QualType SrcRecordTy,
135 QualType DestTy) override;
136
137 bool EmitBadCastCall(CodeGenFunction &CGF) override;
138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 llvm::Value *
140 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
141 const CXXRecordDecl *ClassDecl,
142 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000143
Craig Topper4f12f102014-03-12 06:41:41 +0000144 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000145
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000146 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
147 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000148
Reid Klecknere7de47e2013-07-22 13:51:44 +0000149 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000151 // Itanium does not emit any destructor variant as an inline thunk.
152 // Delegating may occur as an optimization, but all variants are either
153 // emitted with external linkage or as linkonce if they are inline and used.
154 return false;
155 }
156
Craig Topper4f12f102014-03-12 06:41:41 +0000157 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000158
Reid Kleckner89077a12013-12-17 19:46:40 +0000159 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000160 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000161
Craig Topper4f12f102014-03-12 06:41:41 +0000162 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000163
Reid Kleckner89077a12013-12-17 19:46:40 +0000164 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
165 const CXXConstructorDecl *D,
166 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000167 bool Delegating,
168 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000169
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000170 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
171 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000172 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000173
Craig Topper4f12f102014-03-12 06:41:41 +0000174 void emitVTableDefinitions(CodeGenVTables &CGVT,
175 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000176
177 llvm::Value *getVTableAddressPointInStructor(
178 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
179 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000180 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000181
182 llvm::Constant *
183 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000184 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000185
186 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000188
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000189 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000190 llvm::Value *This,
191 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000192
David Majnemer0c0b6d92014-10-31 20:09:12 +0000193 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
194 const CXXDestructorDecl *Dtor,
195 CXXDtorType DtorType,
196 llvm::Value *This,
197 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000198
Craig Topper4f12f102014-03-12 06:41:41 +0000199 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000200
Hans Wennborgc94391d2014-06-06 20:04:01 +0000201 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
202 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000203 // Allow inlining of thunks by emitting them with available_externally
204 // linkage together with vtables when needed.
205 if (ForVTable)
206 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
207 }
208
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000209 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000211
212 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000213 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000214
David Majnemer196ac332014-09-11 23:05:02 +0000215 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
216 FunctionArgList &Args) const override {
217 assert(!Args.empty() && "expected the arglist to not be empty!");
218 return Args.size() - 1;
219 }
220
Craig Topper4f12f102014-03-12 06:41:41 +0000221 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
222 StringRef GetDeletedVirtualCallName() override
223 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000226 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
227 llvm::Value *NewPtr,
228 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000229 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000231 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
232 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000233 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000234
John McCallcdf7ef52010-11-06 09:44:32 +0000235 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000236 llvm::GlobalVariable *DeclPtr,
237 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000238 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000239 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000240
241 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000242 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000243 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000244 CodeGenModule &CGM,
245 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
246 CXXThreadLocals,
247 ArrayRef<llvm::Function *> CXXThreadLocalInits,
248 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
249
250 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000251 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
252 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000253
Craig Topper4f12f102014-03-12 06:41:41 +0000254 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000255
256 /**************************** RTTI Uniqueness ******************************/
257
258protected:
259 /// Returns true if the ABI requires RTTI type_info objects to be unique
260 /// across a program.
261 virtual bool shouldRTTIBeUnique() const { return true; }
262
263public:
264 /// What sort of unique-RTTI behavior should we use?
265 enum RTTIUniquenessKind {
266 /// We are guaranteeing, or need to guarantee, that the RTTI string
267 /// is unique.
268 RUK_Unique,
269
270 /// We are not guaranteeing uniqueness for the RTTI string, so we
271 /// can demote to hidden visibility but must use string comparisons.
272 RUK_NonUniqueHidden,
273
274 /// We are not guaranteeing uniqueness for the RTTI string, so we
275 /// have to use string comparisons, but we also have to emit it with
276 /// non-hidden visibility.
277 RUK_NonUniqueVisible
278 };
279
280 /// Return the required visibility status for the given type and linkage in
281 /// the current ABI.
282 RTTIUniquenessKind
283 classifyRTTIUniqueness(QualType CanTy,
284 llvm::GlobalValue::LinkageTypes Linkage) const;
285 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000286
287 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000288};
John McCall86353412010-08-21 22:46:04 +0000289
290class ARMCXXABI : public ItaniumCXXABI {
291public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000292 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
293 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
294 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000295
Craig Topper4f12f102014-03-12 06:41:41 +0000296 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000297 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
298 isa<CXXDestructorDecl>(GD.getDecl()) &&
299 GD.getDtorType() != Dtor_Deleting));
300 }
John McCall5d865c322010-08-31 07:33:07 +0000301
Craig Topper4f12f102014-03-12 06:41:41 +0000302 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
303 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000304
Craig Topper4f12f102014-03-12 06:41:41 +0000305 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000306 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
307 llvm::Value *NewPtr,
308 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000309 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000310 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000311 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000313};
Tim Northovera2ee4332014-03-29 15:09:45 +0000314
315class iOS64CXXABI : public ARMCXXABI {
316public:
317 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000318
319 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000320 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000321};
Charles Davis4e786dd2010-05-25 19:52:27 +0000322}
323
Charles Davis53c59df2010-08-16 03:33:14 +0000324CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000325 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000326 // For IR-generation purposes, there's no significant difference
327 // between the ARM and iOS ABIs.
328 case TargetCXXABI::GenericARM:
329 case TargetCXXABI::iOS:
330 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000331
Tim Northovera2ee4332014-03-29 15:09:45 +0000332 case TargetCXXABI::iOS64:
333 return new iOS64CXXABI(CGM);
334
Tim Northover9bb857a2013-01-31 12:13:10 +0000335 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
336 // include the other 32-bit ARM oddities: constructor/destructor return values
337 // and array cookies.
338 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000339 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
340 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000341
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000342 case TargetCXXABI::GenericMIPS:
343 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
344
John McCall57625922013-01-25 23:36:14 +0000345 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000346 if (CGM.getContext().getTargetInfo().getTriple().getArch()
347 == llvm::Triple::le32) {
348 // For PNaCl, use ARM-style method pointers so that PNaCl code
349 // does not assume anything about the alignment of function
350 // pointers.
351 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
352 /* UseARMGuardVarABI = */ false);
353 }
John McCall57625922013-01-25 23:36:14 +0000354 return new ItaniumCXXABI(CGM);
355
356 case TargetCXXABI::Microsoft:
357 llvm_unreachable("Microsoft ABI is not Itanium-based");
358 }
359 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000360}
361
Chris Lattnera5f58b02011-07-09 17:41:47 +0000362llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000363ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
364 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000365 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000366 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000367}
368
John McCalld9c6c0b2010-08-22 00:59:17 +0000369/// In the Itanium and ARM ABIs, method pointers have the form:
370/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
371///
372/// In the Itanium ABI:
373/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
374/// - the this-adjustment is (memptr.adj)
375/// - the virtual offset is (memptr.ptr - 1)
376///
377/// In the ARM ABI:
378/// - method pointers are virtual if (memptr.adj & 1) is nonzero
379/// - the this-adjustment is (memptr.adj >> 1)
380/// - the virtual offset is (memptr.ptr)
381/// ARM uses 'adj' for the virtual flag because Thumb functions
382/// may be only single-byte aligned.
383///
384/// If the member is virtual, the adjusted 'this' pointer points
385/// to a vtable pointer from which the virtual offset is applied.
386///
387/// If the member is non-virtual, memptr.ptr is the address of
388/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000389llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
390 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
391 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000392 CGBuilderTy &Builder = CGF.Builder;
393
394 const FunctionProtoType *FPT =
395 MPT->getPointeeType()->getAs<FunctionProtoType>();
396 const CXXRecordDecl *RD =
397 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
398
Chris Lattner2192fe52011-07-18 04:24:23 +0000399 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000400 CGM.getTypes().GetFunctionType(
401 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000402
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000403 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000404
John McCalld9c6c0b2010-08-22 00:59:17 +0000405 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
406 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
407 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
408
John McCalla1dee5302010-08-22 10:59:02 +0000409 // Extract memptr.adj, which is in the second field.
410 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000411
412 // Compute the true adjustment.
413 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000414 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000415 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000416
417 // Apply the adjustment and cast back to the original struct type
418 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000419 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
420 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
421 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000422
423 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000424 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000425
426 // If the LSB in the function pointer is 1, the function pointer points to
427 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000428 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000429 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000430 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
431 else
432 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
433 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000434 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
435
436 // In the virtual path, the adjustment left 'This' pointing to the
437 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000438 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000439 CGF.EmitBlock(FnVirtual);
440
441 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000442 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000443 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000444
445 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000446 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000447 if (!UseARMMethodPtrABI)
448 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000449 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000450
451 // Load the virtual function to call.
452 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000453 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000454 CGF.EmitBranch(FnEnd);
455
456 // In the non-virtual path, the function pointer is actually a
457 // function pointer.
458 CGF.EmitBlock(FnNonVirtual);
459 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000460 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000461
462 // We're done.
463 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000464 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000465 Callee->addIncoming(VirtualFn, FnVirtual);
466 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
467 return Callee;
468}
John McCalla8bbb822010-08-22 03:04:22 +0000469
John McCallc134eb52010-08-31 21:07:20 +0000470/// Compute an l-value by applying the given pointer-to-member to a
471/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000472llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
473 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
474 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000475 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000476
477 CGBuilderTy &Builder = CGF.Builder;
478
Micah Villmowea2fea22012-10-25 15:39:14 +0000479 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000480
481 // Cast to char*.
482 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
483
484 // Apply the offset, which we assume is non-null.
485 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
486
487 // Cast the address to the appropriate pointer type, adopting the
488 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000489 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000490 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000491 return Builder.CreateBitCast(Addr, PType);
492}
493
John McCallc62bb392012-02-15 01:22:51 +0000494/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
495/// conversion.
496///
497/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000498///
499/// Obligatory offset/adjustment diagram:
500/// <-- offset --> <-- adjustment -->
501/// |--------------------------|----------------------|--------------------|
502/// ^Derived address point ^Base address point ^Member address point
503///
504/// So when converting a base member pointer to a derived member pointer,
505/// we add the offset to the adjustment because the address point has
506/// decreased; and conversely, when converting a derived MP to a base MP
507/// we subtract the offset from the adjustment because the address point
508/// has increased.
509///
510/// The standard forbids (at compile time) conversion to and from
511/// virtual bases, which is why we don't have to consider them here.
512///
513/// The standard forbids (at run time) casting a derived MP to a base
514/// MP when the derived MP does not point to a member of the base.
515/// This is why -1 is a reasonable choice for null data member
516/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000517llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000518ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
519 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000520 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000521 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000522 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
523 E->getCastKind() == CK_ReinterpretMemberPointer);
524
525 // Under Itanium, reinterprets don't require any additional processing.
526 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
527
528 // Use constant emission if we can.
529 if (isa<llvm::Constant>(src))
530 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
531
532 llvm::Constant *adj = getMemberPointerAdjustment(E);
533 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000534
535 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000536 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000537
John McCallc62bb392012-02-15 01:22:51 +0000538 const MemberPointerType *destTy =
539 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000540
John McCall7a9aac22010-08-23 01:21:21 +0000541 // For member data pointers, this is just a matter of adding the
542 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000543 if (destTy->isMemberDataPointer()) {
544 llvm::Value *dst;
545 if (isDerivedToBase)
546 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000547 else
John McCallc62bb392012-02-15 01:22:51 +0000548 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000549
550 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000551 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
552 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
553 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000554 }
555
John McCalla1dee5302010-08-22 10:59:02 +0000556 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000557 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000558 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
559 offset <<= 1;
560 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000561 }
562
John McCallc62bb392012-02-15 01:22:51 +0000563 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
564 llvm::Value *dstAdj;
565 if (isDerivedToBase)
566 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000567 else
John McCallc62bb392012-02-15 01:22:51 +0000568 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000569
John McCallc62bb392012-02-15 01:22:51 +0000570 return Builder.CreateInsertValue(src, dstAdj, 1);
571}
572
573llvm::Constant *
574ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
575 llvm::Constant *src) {
576 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
577 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
578 E->getCastKind() == CK_ReinterpretMemberPointer);
579
580 // Under Itanium, reinterprets don't require any additional processing.
581 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
582
583 // If the adjustment is trivial, we don't need to do anything.
584 llvm::Constant *adj = getMemberPointerAdjustment(E);
585 if (!adj) return src;
586
587 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
588
589 const MemberPointerType *destTy =
590 E->getType()->castAs<MemberPointerType>();
591
592 // For member data pointers, this is just a matter of adding the
593 // offset if the source is non-null.
594 if (destTy->isMemberDataPointer()) {
595 // null maps to null.
596 if (src->isAllOnesValue()) return src;
597
598 if (isDerivedToBase)
599 return llvm::ConstantExpr::getNSWSub(src, adj);
600 else
601 return llvm::ConstantExpr::getNSWAdd(src, adj);
602 }
603
604 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000605 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000606 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
607 offset <<= 1;
608 adj = llvm::ConstantInt::get(adj->getType(), offset);
609 }
610
611 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
612 llvm::Constant *dstAdj;
613 if (isDerivedToBase)
614 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
615 else
616 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
617
618 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000619}
John McCall84fa5102010-08-22 04:16:24 +0000620
621llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000622ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000623 // Itanium C++ ABI 2.3:
624 // A NULL pointer is represented as -1.
625 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000626 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000627
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000628 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000629 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000630 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000631}
632
John McCallf3a88602011-02-03 08:15:49 +0000633llvm::Constant *
634ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
635 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000636 // Itanium C++ ABI 2.3:
637 // A pointer to data member is an offset from the base address of
638 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000639 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000640}
641
John McCall2979fe02011-04-12 00:42:48 +0000642llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000643 return BuildMemberPointer(MD, CharUnits::Zero());
644}
645
646llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
647 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000648 assert(MD->isInstance() && "Member function must not be static!");
649 MD = MD->getCanonicalDecl();
650
651 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000652
653 // Get the function pointer (or index if this is a virtual function).
654 llvm::Constant *MemPtr[2];
655 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000656 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000657
Ken Dyckdf016282011-04-09 01:30:02 +0000658 const ASTContext &Context = getContext();
659 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000660 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000661 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000662
Mark Seabornedf0d382013-07-24 16:25:13 +0000663 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000664 // ARM C++ ABI 3.2.1:
665 // This ABI specifies that adj contains twice the this
666 // adjustment, plus 1 if the member function is virtual. The
667 // least significant bit of adj then makes exactly the same
668 // discrimination as the least significant bit of ptr does for
669 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000670 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
671 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000672 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000673 } else {
674 // Itanium C++ ABI 2.3:
675 // For a virtual function, [the pointer field] is 1 plus the
676 // virtual table offset (in bytes) of the function,
677 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000678 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
679 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000680 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000681 }
682 } else {
John McCall2979fe02011-04-12 00:42:48 +0000683 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000684 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000685 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000686 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000687 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000688 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000689 } else {
John McCall2979fe02011-04-12 00:42:48 +0000690 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
691 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000692 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000693 }
John McCall2979fe02011-04-12 00:42:48 +0000694 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000695
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000696 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000697 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
698 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000699 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000700 }
John McCall1c456c82010-08-22 06:43:33 +0000701
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000702 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000703}
704
Richard Smithdafff942012-01-14 04:30:29 +0000705llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
706 QualType MPType) {
707 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
708 const ValueDecl *MPD = MP.getMemberPointerDecl();
709 if (!MPD)
710 return EmitNullMemberPointer(MPT);
711
Reid Kleckner452abac2013-05-09 21:01:17 +0000712 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000713
714 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
715 return BuildMemberPointer(MD, ThisAdjustment);
716
717 CharUnits FieldOffset =
718 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
719 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
720}
721
John McCall131d97d2010-08-22 08:30:07 +0000722/// The comparison algorithm is pretty easy: the member pointers are
723/// the same if they're either bitwise identical *or* both null.
724///
725/// ARM is different here only because null-ness is more complicated.
726llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000727ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
728 llvm::Value *L,
729 llvm::Value *R,
730 const MemberPointerType *MPT,
731 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000732 CGBuilderTy &Builder = CGF.Builder;
733
John McCall131d97d2010-08-22 08:30:07 +0000734 llvm::ICmpInst::Predicate Eq;
735 llvm::Instruction::BinaryOps And, Or;
736 if (Inequality) {
737 Eq = llvm::ICmpInst::ICMP_NE;
738 And = llvm::Instruction::Or;
739 Or = llvm::Instruction::And;
740 } else {
741 Eq = llvm::ICmpInst::ICMP_EQ;
742 And = llvm::Instruction::And;
743 Or = llvm::Instruction::Or;
744 }
745
John McCall7a9aac22010-08-23 01:21:21 +0000746 // Member data pointers are easy because there's a unique null
747 // value, so it just comes down to bitwise equality.
748 if (MPT->isMemberDataPointer())
749 return Builder.CreateICmp(Eq, L, R);
750
751 // For member function pointers, the tautologies are more complex.
752 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000753 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000754 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000755 // (L == R) <==> (L.ptr == R.ptr &&
756 // (L.adj == R.adj ||
757 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000758 // The inequality tautologies have exactly the same structure, except
759 // applying De Morgan's laws.
760
761 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
762 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
763
John McCall131d97d2010-08-22 08:30:07 +0000764 // This condition tests whether L.ptr == R.ptr. This must always be
765 // true for equality to hold.
766 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
767
768 // This condition, together with the assumption that L.ptr == R.ptr,
769 // tests whether the pointers are both null. ARM imposes an extra
770 // condition.
771 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
772 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
773
774 // This condition tests whether L.adj == R.adj. If this isn't
775 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000776 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
777 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000778 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
779
780 // Null member function pointers on ARM clear the low bit of Adj,
781 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000782 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000783 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
784
785 // Compute (l.adj | r.adj) & 1 and test it against zero.
786 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
787 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
788 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
789 "cmp.or.adj");
790 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
791 }
792
793 // Tie together all our conditions.
794 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
795 Result = Builder.CreateBinOp(And, PtrEq, Result,
796 Inequality ? "memptr.ne" : "memptr.eq");
797 return Result;
798}
799
800llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000801ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
802 llvm::Value *MemPtr,
803 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000804 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000805
806 /// For member data pointers, this is just a check against -1.
807 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000808 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000809 llvm::Value *NegativeOne =
810 llvm::Constant::getAllOnesValue(MemPtr->getType());
811 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
812 }
John McCall131d97d2010-08-22 08:30:07 +0000813
Daniel Dunbar914bc412011-04-19 23:10:47 +0000814 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000815 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000816
817 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
818 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
819
Daniel Dunbar914bc412011-04-19 23:10:47 +0000820 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
821 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000822 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000823 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000824 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000825 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000826 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
827 "memptr.isvirtual");
828 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000829 }
830
831 return Result;
832}
John McCall1c456c82010-08-22 06:43:33 +0000833
Reid Kleckner40ca9132014-05-13 22:05:45 +0000834bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
835 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
836 if (!RD)
837 return false;
838
Reid Klecknerd355ca72014-05-15 01:26:32 +0000839 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
840 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
841 // special members.
842 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000843 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
844 return true;
845 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000846 return false;
847}
848
John McCall614dbdc2010-08-22 21:01:12 +0000849/// The Itanium ABI requires non-zero initialization only for data
850/// member pointers, for which '0' is a valid offset.
851bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
852 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000853}
John McCall5d865c322010-08-31 07:33:07 +0000854
John McCall82fb8922012-09-25 10:10:39 +0000855/// The Itanium ABI always places an offset to the complete object
856/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000857void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
858 const CXXDeleteExpr *DE,
859 llvm::Value *Ptr,
860 QualType ElementType,
861 const CXXDestructorDecl *Dtor) {
862 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000863 if (UseGlobalDelete) {
864 // Derive the complete-object pointer, which is what we need
865 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000866
David Majnemer0c0b6d92014-10-31 20:09:12 +0000867 // Grab the vtable pointer as an intptr_t*.
868 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000869
David Majnemer0c0b6d92014-10-31 20:09:12 +0000870 // Track back to entry -2 and pull out the offset there.
871 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
872 VTable, -2, "complete-offset.ptr");
873 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
874 Offset->setAlignment(CGF.PointerAlignInBytes);
875
876 // Apply the offset.
877 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
878 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
879
880 // If we're supposed to call the global delete, make sure we do so
881 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000882 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
883 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000884 }
885
886 // FIXME: Provide a source location here even though there's no
887 // CXXMemberCallExpr for dtor call.
888 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
889 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
890
891 if (UseGlobalDelete)
892 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000893}
894
David Majnemer442d0a22014-11-25 07:20:20 +0000895void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
896 // void __cxa_rethrow();
897
898 llvm::FunctionType *FTy =
899 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
900
901 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
902
903 if (isNoReturn)
904 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
905 else
906 CGF.EmitRuntimeCallOrInvoke(Fn);
907}
908
David Majnemer1162d252014-06-22 19:05:33 +0000909static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
910 // void *__dynamic_cast(const void *sub,
911 // const abi::__class_type_info *src,
912 // const abi::__class_type_info *dst,
913 // std::ptrdiff_t src2dst_offset);
914
915 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
916 llvm::Type *PtrDiffTy =
917 CGF.ConvertType(CGF.getContext().getPointerDiffType());
918
919 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
920
921 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
922
923 // Mark the function as nounwind readonly.
924 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
925 llvm::Attribute::ReadOnly };
926 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
927 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
928
929 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
930}
931
932static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
933 // void __cxa_bad_cast();
934 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
935 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
936}
937
938/// \brief Compute the src2dst_offset hint as described in the
939/// Itanium C++ ABI [2.9.7]
940static CharUnits computeOffsetHint(ASTContext &Context,
941 const CXXRecordDecl *Src,
942 const CXXRecordDecl *Dst) {
943 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
944 /*DetectVirtual=*/false);
945
946 // If Dst is not derived from Src we can skip the whole computation below and
947 // return that Src is not a public base of Dst. Record all inheritance paths.
948 if (!Dst->isDerivedFrom(Src, Paths))
949 return CharUnits::fromQuantity(-2ULL);
950
951 unsigned NumPublicPaths = 0;
952 CharUnits Offset;
953
954 // Now walk all possible inheritance paths.
955 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
956 ++I) {
957 if (I->Access != AS_public) // Ignore non-public inheritance.
958 continue;
959
960 ++NumPublicPaths;
961
962 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
963 // If the path contains a virtual base class we can't give any hint.
964 // -1: no hint.
965 if (J->Base->isVirtual())
966 return CharUnits::fromQuantity(-1ULL);
967
968 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
969 continue;
970
971 // Accumulate the base class offsets.
972 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
973 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
974 }
975 }
976
977 // -2: Src is not a public base of Dst.
978 if (NumPublicPaths == 0)
979 return CharUnits::fromQuantity(-2ULL);
980
981 // -3: Src is a multiple public base type but never a virtual base type.
982 if (NumPublicPaths > 1)
983 return CharUnits::fromQuantity(-3ULL);
984
985 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
986 // Return the offset of Src from the origin of Dst.
987 return Offset;
988}
989
990static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
991 // void __cxa_bad_typeid();
992 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
993
994 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
995}
996
997bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
998 QualType SrcRecordTy) {
999 return IsDeref;
1000}
1001
1002void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1003 llvm::Value *Fn = getBadTypeidFn(CGF);
1004 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1005 CGF.Builder.CreateUnreachable();
1006}
1007
1008llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1009 QualType SrcRecordTy,
1010 llvm::Value *ThisPtr,
1011 llvm::Type *StdTypeInfoPtrTy) {
1012 llvm::Value *Value =
1013 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1014
1015 // Load the type info.
1016 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1017 return CGF.Builder.CreateLoad(Value);
1018}
1019
1020bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1021 QualType SrcRecordTy) {
1022 return SrcIsPtr;
1023}
1024
1025llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1026 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1027 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1028 llvm::Type *PtrDiffLTy =
1029 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1030 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1031
1032 llvm::Value *SrcRTTI =
1033 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1034 llvm::Value *DestRTTI =
1035 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1036
1037 // Compute the offset hint.
1038 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1039 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1040 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1041 PtrDiffLTy,
1042 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1043
1044 // Emit the call to __dynamic_cast.
1045 Value = CGF.EmitCastToVoidPtr(Value);
1046
1047 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1048 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1049 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1050
1051 /// C++ [expr.dynamic.cast]p9:
1052 /// A failed cast to reference type throws std::bad_cast
1053 if (DestTy->isReferenceType()) {
1054 llvm::BasicBlock *BadCastBlock =
1055 CGF.createBasicBlock("dynamic_cast.bad_cast");
1056
1057 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1058 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1059
1060 CGF.EmitBlock(BadCastBlock);
1061 EmitBadCastCall(CGF);
1062 }
1063
1064 return Value;
1065}
1066
1067llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1068 llvm::Value *Value,
1069 QualType SrcRecordTy,
1070 QualType DestTy) {
1071 llvm::Type *PtrDiffLTy =
1072 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1073 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1074
1075 // Get the vtable pointer.
1076 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1077
1078 // Get the offset-to-top from the vtable.
1079 llvm::Value *OffsetToTop =
1080 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1081 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1082
1083 // Finally, add the offset to the pointer.
1084 Value = CGF.EmitCastToVoidPtr(Value);
1085 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1086
1087 return CGF.Builder.CreateBitCast(Value, DestLTy);
1088}
1089
1090bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1091 llvm::Value *Fn = getBadCastFn(CGF);
1092 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1093 CGF.Builder.CreateUnreachable();
1094 return true;
1095}
1096
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001097llvm::Value *
1098ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1099 llvm::Value *This,
1100 const CXXRecordDecl *ClassDecl,
1101 const CXXRecordDecl *BaseClassDecl) {
1102 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1103 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001104 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1105 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001106
1107 llvm::Value *VBaseOffsetPtr =
1108 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1109 "vbase.offset.ptr");
1110 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1111 CGM.PtrDiffTy->getPointerTo());
1112
1113 llvm::Value *VBaseOffset =
1114 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1115
1116 return VBaseOffset;
1117}
1118
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001119void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1120 // Just make sure we're in sync with TargetCXXABI.
1121 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1122
Rafael Espindolac3cde362013-12-09 14:51:17 +00001123 // The constructor used for constructing this as a base class;
1124 // ignores virtual bases.
1125 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1126
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001127 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001128 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001129 if (!D->getParent()->isAbstract()) {
1130 // We don't need to emit the complete ctor if the class is abstract.
1131 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1132 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001133}
1134
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001135void
1136ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1137 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001138 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001139
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001140 // All parameters are already in place except VTT, which goes after 'this'.
1141 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001142
1143 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001144 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1145 ArgTys.insert(ArgTys.begin() + 1,
1146 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001147}
1148
Reid Klecknere7de47e2013-07-22 13:51:44 +00001149void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001150 // The destructor used for destructing this as a base class; ignores
1151 // virtual bases.
1152 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001153
1154 // The destructor used for destructing this as a most-derived class;
1155 // call the base destructor and then destructs any virtual bases.
1156 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1157
Rafael Espindolac3cde362013-12-09 14:51:17 +00001158 // The destructor in a virtual table is always a 'deleting'
1159 // destructor, which calls the complete destructor and then uses the
1160 // appropriate operator delete.
1161 if (D->isVirtual())
1162 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001163}
1164
Reid Kleckner89077a12013-12-17 19:46:40 +00001165void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1166 QualType &ResTy,
1167 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001168 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001169 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001170
1171 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001172 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001173 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001174
1175 // FIXME: avoid the fake decl
1176 QualType T = Context.getPointerType(Context.VoidPtrTy);
1177 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001178 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001179 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001180 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001181 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001182 }
1183}
1184
John McCall5d865c322010-08-31 07:33:07 +00001185void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1186 /// Initialize the 'this' slot.
1187 EmitThisParam(CGF);
1188
1189 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001190 if (getStructorImplicitParamDecl(CGF)) {
1191 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1192 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001193 }
John McCall5d865c322010-08-31 07:33:07 +00001194
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001195 /// If this is a function that the ABI specifies returns 'this', initialize
1196 /// the return slot to 'this' at the start of the function.
1197 ///
1198 /// Unlike the setting of return types, this is done within the ABI
1199 /// implementation instead of by clients of CGCXXABI because:
1200 /// 1) getThisValue is currently protected
1201 /// 2) in theory, an ABI could implement 'this' returns some other way;
1202 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001203 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001204 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001205}
1206
Reid Kleckner89077a12013-12-17 19:46:40 +00001207unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1208 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1209 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1210 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1211 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001212
Reid Kleckner89077a12013-12-17 19:46:40 +00001213 // Insert the implicit 'vtt' argument as the second argument.
1214 llvm::Value *VTT =
1215 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1216 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1217 Args.insert(Args.begin() + 1,
1218 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1219 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001220}
1221
1222void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1223 const CXXDestructorDecl *DD,
1224 CXXDtorType Type, bool ForVirtualBase,
1225 bool Delegating, llvm::Value *This) {
1226 GlobalDecl GD(DD, Type);
1227 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1228 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1229
Craig Topper8a13c412014-05-21 05:09:00 +00001230 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001231 if (getContext().getLangOpts().AppleKext)
1232 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1233
1234 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001235 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001236
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001237 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1238 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001239}
1240
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001241void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1242 const CXXRecordDecl *RD) {
1243 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1244 if (VTable->hasInitializer())
1245 return;
1246
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001247 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001248 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1249 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001250 llvm::Constant *RTTI =
1251 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001252
1253 // Create and set the initializer.
1254 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1255 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001256 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001257 VTable->setInitializer(Init);
1258
1259 // Set the correct linkage.
1260 VTable->setLinkage(Linkage);
1261
Rafael Espindolacb92c192015-01-15 23:18:01 +00001262 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1263 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1264
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001265 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001266 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001267
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001268 // Use pointer alignment for the vtable. Otherwise we would align them based
1269 // on the size of the initializer which doesn't make sense as only single
1270 // values are read.
1271 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1272 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1273
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001274 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1275 // we will emit the typeinfo for the fundamental types. This is the
1276 // same behaviour as GCC.
1277 const DeclContext *DC = RD->getDeclContext();
1278 if (RD->getIdentifier() &&
1279 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1280 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1281 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1282 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001283 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001284}
1285
1286llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1287 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1288 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1289 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1290 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1291
1292 llvm::Value *VTableAddressPoint;
1293 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1294 // Get the secondary vpointer index.
1295 uint64_t VirtualPointerIndex =
1296 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1297
1298 /// Load the VTT.
1299 llvm::Value *VTT = CGF.LoadCXXVTT();
1300 if (VirtualPointerIndex)
1301 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1302
1303 // And load the address point from the VTT.
1304 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1305 } else {
1306 llvm::Constant *VTable =
1307 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001308 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1309 .getVTableLayout(VTableClass)
1310 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001311 VTableAddressPoint =
1312 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1313 }
1314
1315 return VTableAddressPoint;
1316}
1317
1318llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1319 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1320 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1321
1322 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001323 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1324 .getVTableLayout(VTableClass)
1325 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001326 llvm::Value *Indices[] = {
1327 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1328 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1329 };
1330
1331 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1332}
1333
1334llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1335 CharUnits VPtrOffset) {
1336 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1337
1338 llvm::GlobalVariable *&VTable = VTables[RD];
1339 if (VTable)
1340 return VTable;
1341
1342 // Queue up this v-table for possible deferred emission.
1343 CGM.addDeferredVTable(RD);
1344
1345 SmallString<256> OutName;
1346 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001347 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001348 Out.flush();
1349 StringRef Name = OutName.str();
1350
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001351 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001352 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1353 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1354
1355 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1356 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1357 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001358
1359 if (RD->hasAttr<DLLImportAttr>())
1360 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1361 else if (RD->hasAttr<DLLExportAttr>())
1362 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1363
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001364 return VTable;
1365}
1366
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001367llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1368 GlobalDecl GD,
1369 llvm::Value *This,
1370 llvm::Type *Ty) {
1371 GD = GD.getCanonicalDecl();
1372 Ty = Ty->getPointerTo()->getPointerTo();
1373 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1374
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001375 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001376 llvm::Value *VFuncPtr =
1377 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1378 return CGF.Builder.CreateLoad(VFuncPtr);
1379}
1380
David Majnemer0c0b6d92014-10-31 20:09:12 +00001381llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1382 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1383 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001384 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001385 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1386
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001387 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1388 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001389 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001390 llvm::Value *Callee =
1391 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001392
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001393 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1394 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001395 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001396}
1397
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001398void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001399 CodeGenVTables &VTables = CGM.getVTables();
1400 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001401 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001402}
1403
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001404static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1405 llvm::Value *Ptr,
1406 int64_t NonVirtualAdjustment,
1407 int64_t VirtualAdjustment,
1408 bool IsReturnAdjustment) {
1409 if (!NonVirtualAdjustment && !VirtualAdjustment)
1410 return Ptr;
1411
1412 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1413 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1414
1415 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1416 // Perform the non-virtual adjustment for a base-to-derived cast.
1417 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1418 }
1419
1420 if (VirtualAdjustment) {
1421 llvm::Type *PtrDiffTy =
1422 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1423
1424 // Perform the virtual adjustment.
1425 llvm::Value *VTablePtrPtr =
1426 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1427
1428 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1429
1430 llvm::Value *OffsetPtr =
1431 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1432
1433 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1434
1435 // Load the adjustment offset from the vtable.
1436 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1437
1438 // Adjust our pointer.
1439 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1440 }
1441
1442 if (NonVirtualAdjustment && IsReturnAdjustment) {
1443 // Perform the non-virtual adjustment for a derived-to-base cast.
1444 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1445 }
1446
1447 // Cast back to the original type.
1448 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1449}
1450
1451llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1452 llvm::Value *This,
1453 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001454 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1455 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001456 /*IsReturnAdjustment=*/false);
1457}
1458
1459llvm::Value *
1460ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1461 const ReturnAdjustment &RA) {
1462 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1463 RA.Virtual.Itanium.VBaseOffsetOffset,
1464 /*IsReturnAdjustment=*/true);
1465}
1466
John McCall5d865c322010-08-31 07:33:07 +00001467void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1468 RValue RV, QualType ResultType) {
1469 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1470 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1471
1472 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001473 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001474 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1475 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1476 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1477}
John McCall8ed55a52010-09-02 09:58:18 +00001478
1479/************************** Array allocation cookies **************************/
1480
John McCallb91cd662012-05-01 05:23:51 +00001481CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1482 // The array cookie is a size_t; pad that up to the element alignment.
1483 // The cookie is actually right-justified in that space.
1484 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1485 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001486}
1487
1488llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1489 llvm::Value *NewPtr,
1490 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001491 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001492 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001493 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001494
Micah Villmowea2fea22012-10-25 15:39:14 +00001495 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001496
John McCall9bca9232010-09-02 10:25:57 +00001497 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001498 QualType SizeTy = Ctx.getSizeType();
1499 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1500
1501 // The size of the cookie.
1502 CharUnits CookieSize =
1503 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001504 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001505
1506 // Compute an offset to the cookie.
1507 llvm::Value *CookiePtr = NewPtr;
1508 CharUnits CookieOffset = CookieSize - SizeSize;
1509 if (!CookieOffset.isZero())
1510 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1511 CookieOffset.getQuantity());
1512
1513 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001514 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1515 llvm::Value *NumElementsPtr =
1516 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1517 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001518 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001519 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001520 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001521 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1522 llvm::FunctionType *FTy =
1523 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1524 llvm::Constant *F =
1525 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1526 CGF.Builder.CreateCall(F, NumElementsPtr);
1527 }
John McCall8ed55a52010-09-02 09:58:18 +00001528
1529 // Finally, compute a pointer to the actual data buffer by skipping
1530 // over the cookie completely.
1531 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1532 CookieSize.getQuantity());
1533}
1534
John McCallb91cd662012-05-01 05:23:51 +00001535llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1536 llvm::Value *allocPtr,
1537 CharUnits cookieSize) {
1538 // The element size is right-justified in the cookie.
1539 llvm::Value *numElementsPtr = allocPtr;
1540 CharUnits numElementsOffset =
1541 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1542 if (!numElementsOffset.isZero())
1543 numElementsPtr =
1544 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1545 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001546
Micah Villmowea2fea22012-10-25 15:39:14 +00001547 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001548 numElementsPtr =
1549 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001550 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001551 return CGF.Builder.CreateLoad(numElementsPtr);
1552 // In asan mode emit a function call instead of a regular load and let the
1553 // run-time deal with it: if the shadow is properly poisoned return the
1554 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1555 // We can't simply ignore this load using nosanitize metadata because
1556 // the metadata may be lost.
1557 llvm::FunctionType *FTy =
1558 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1559 llvm::Constant *F =
1560 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1561 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001562}
1563
John McCallb91cd662012-05-01 05:23:51 +00001564CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001565 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001566 // struct array_cookie {
1567 // std::size_t element_size; // element_size != 0
1568 // std::size_t element_count;
1569 // };
John McCallc19c7062013-01-25 23:36:19 +00001570 // But the base ABI doesn't give anything an alignment greater than
1571 // 8, so we can dismiss this as typical ABI-author blindness to
1572 // actual language complexity and round up to the element alignment.
1573 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1574 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001575}
1576
1577llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001578 llvm::Value *newPtr,
1579 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001580 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001581 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001582 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001583
John McCallc19c7062013-01-25 23:36:19 +00001584 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1585 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001586
1587 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001588 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001589
1590 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001591 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1592 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1593 getContext().getTypeSizeInChars(elementType).getQuantity());
1594 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001595
1596 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001597 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1598 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001599
1600 // Finally, compute a pointer to the actual data buffer by skipping
1601 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001602 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1603 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1604 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001605}
1606
John McCallb91cd662012-05-01 05:23:51 +00001607llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1608 llvm::Value *allocPtr,
1609 CharUnits cookieSize) {
1610 // The number of elements is at offset sizeof(size_t) relative to
1611 // the allocated pointer.
1612 llvm::Value *numElementsPtr
1613 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001614
Micah Villmowea2fea22012-10-25 15:39:14 +00001615 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001616 numElementsPtr =
1617 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1618 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001619}
1620
John McCall68ff0372010-09-08 01:44:27 +00001621/*********************** Static local initialization **************************/
1622
1623static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001624 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001625 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001626 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001627 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001628 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001629 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001630 llvm::AttributeSet::get(CGM.getLLVMContext(),
1631 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001632 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001633}
1634
1635static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001636 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001637 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001638 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001639 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001640 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001641 llvm::AttributeSet::get(CGM.getLLVMContext(),
1642 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001643 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001644}
1645
1646static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001647 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001648 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001649 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001650 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001651 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001652 llvm::AttributeSet::get(CGM.getLLVMContext(),
1653 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001654 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001655}
1656
1657namespace {
1658 struct CallGuardAbort : EHScopeStack::Cleanup {
1659 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001660 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001661
Craig Topper4f12f102014-03-12 06:41:41 +00001662 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001663 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1664 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001665 }
1666 };
1667}
1668
1669/// The ARM code here follows the Itanium code closely enough that we
1670/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001671void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1672 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001673 llvm::GlobalVariable *var,
1674 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001675 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001676
Richard Smithdbf74ba2013-04-14 23:01:42 +00001677 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001678 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001679 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1680 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001681
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001682 // If we have a global variable with internal linkage and thread-safe statics
1683 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001684 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1685
1686 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001687 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001688 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001689 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001690 // Guard variables are 64 bits in the generic ABI and size width on ARM
1691 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001692 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001693 }
John McCallb88a5662012-03-30 21:00:39 +00001694 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001695
John McCallb88a5662012-03-30 21:00:39 +00001696 // Create the guard variable if we don't already have it (as we
1697 // might if we're double-emitting this function body).
1698 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1699 if (!guard) {
1700 // Mangle the name for the guard.
1701 SmallString<256> guardName;
1702 {
1703 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001704 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001705 out.flush();
1706 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001707
John McCallb88a5662012-03-30 21:00:39 +00001708 // Create the guard variable with a zero-initializer.
1709 // Just absorb linkage and visibility from the guarded variable.
1710 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1711 false, var->getLinkage(),
1712 llvm::ConstantInt::get(guardTy, 0),
1713 guardName.str());
1714 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001715 // If the variable is thread-local, so is its guard variable.
1716 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001717
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001718 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1719 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001720 llvm::Comdat *C = var->getComdat();
1721 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001722 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001723 CGF.CurFn->setComdat(C);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001724 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1725 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001726 }
1727
John McCallb88a5662012-03-30 21:00:39 +00001728 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1729 }
John McCall87590e62012-03-30 07:09:50 +00001730
John McCall68ff0372010-09-08 01:44:27 +00001731 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001732 //
John McCall68ff0372010-09-08 01:44:27 +00001733 // Itanium C++ ABI 3.3.2:
1734 // The following is pseudo-code showing how these functions can be used:
1735 // if (obj_guard.first_byte == 0) {
1736 // if ( __cxa_guard_acquire (&obj_guard) ) {
1737 // try {
1738 // ... initialize the object ...;
1739 // } catch (...) {
1740 // __cxa_guard_abort (&obj_guard);
1741 // throw;
1742 // }
1743 // ... queue object destructor with __cxa_atexit() ...;
1744 // __cxa_guard_release (&obj_guard);
1745 // }
1746 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001747
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001748 // Load the first byte of the guard variable.
1749 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001750 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001751 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001752
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001753 // Itanium ABI:
1754 // An implementation supporting thread-safety on multiprocessor
1755 // systems must also guarantee that references to the initialized
1756 // object do not occur before the load of the initialization flag.
1757 //
1758 // In LLVM, we do this by marking the load Acquire.
1759 if (threadsafe)
1760 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001761
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001762 // For ARM, we should only check the first bit, rather than the entire byte:
1763 //
1764 // ARM C++ ABI 3.2.3.1:
1765 // To support the potential use of initialization guard variables
1766 // as semaphores that are the target of ARM SWP and LDREX/STREX
1767 // synchronizing instructions we define a static initialization
1768 // guard variable to be a 4-byte aligned, 4-byte word with the
1769 // following inline access protocol.
1770 // #define INITIALIZED 1
1771 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1772 // if (__cxa_guard_acquire(&obj_guard))
1773 // ...
1774 // }
1775 //
1776 // and similarly for ARM64:
1777 //
1778 // ARM64 C++ ABI 3.2.2:
1779 // This ABI instead only specifies the value bit 0 of the static guard
1780 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1781 // variable is not initialized and 1 when it is.
1782 llvm::Value *V =
1783 (UseARMGuardVarABI && !useInt8GuardVariable)
1784 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1785 : LI;
1786 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001787
1788 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1789 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1790
1791 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001792 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001793
1794 CGF.EmitBlock(InitCheckBlock);
1795
1796 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001797 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001798 // Call __cxa_guard_acquire.
1799 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001800 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001801
1802 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1803
1804 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1805 InitBlock, EndBlock);
1806
1807 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001808 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001809
1810 CGF.EmitBlock(InitBlock);
1811 }
1812
1813 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001814 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001815
John McCall5aa52592011-06-17 07:33:57 +00001816 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001817 // Pop the guard-abort cleanup if we pushed one.
1818 CGF.PopCleanupBlock();
1819
1820 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001821 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001822 } else {
John McCallb88a5662012-03-30 21:00:39 +00001823 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001824 }
1825
1826 CGF.EmitBlock(EndBlock);
1827}
John McCallc84ed6a2012-05-01 06:13:13 +00001828
1829/// Register a global destructor using __cxa_atexit.
1830static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1831 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001832 llvm::Constant *addr,
1833 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001834 const char *Name = "__cxa_atexit";
1835 if (TLS) {
1836 const llvm::Triple &T = CGF.getTarget().getTriple();
1837 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1838 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001839
John McCallc84ed6a2012-05-01 06:13:13 +00001840 // We're assuming that the destructor function is something we can
1841 // reasonably call with the default CC. Go ahead and cast it to the
1842 // right prototype.
1843 llvm::Type *dtorTy =
1844 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1845
1846 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1847 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1848 llvm::FunctionType *atexitTy =
1849 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1850
1851 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001852 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001853 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1854 fn->setDoesNotThrow();
1855
1856 // Create a variable that binds the atexit to this shared object.
1857 llvm::Constant *handle =
1858 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1859
1860 llvm::Value *args[] = {
1861 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1862 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1863 handle
1864 };
John McCall882987f2013-02-28 19:01:20 +00001865 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001866}
1867
1868/// Register a global destructor as best as we know how.
1869void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001870 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001871 llvm::Constant *dtor,
1872 llvm::Constant *addr) {
1873 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001874 if (CGM.getCodeGenOpts().CXAAtExit)
1875 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1876
1877 if (D.getTLSKind())
1878 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001879
1880 // In Apple kexts, we want to add a global destructor entry.
1881 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001882 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001883 // Generate a global destructor entry.
1884 return CGM.AddCXXDtorEntry(dtor, addr);
1885 }
1886
David Blaikieebe87e12013-08-27 23:57:18 +00001887 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001888}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001889
David Majnemer9b21c332014-07-11 20:28:10 +00001890static bool isThreadWrapperReplaceable(const VarDecl *VD,
1891 CodeGen::CodeGenModule &CGM) {
1892 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1893 // OS X prefers to have references to thread local variables to go through
1894 // the thread wrapper instead of directly referencing the backing variable.
1895 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1896 CGM.getTarget().getTriple().isMacOSX();
1897}
1898
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001899/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001900/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001901/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001902static llvm::GlobalValue::LinkageTypes
1903getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1904 llvm::GlobalValue::LinkageTypes VarLinkage =
1905 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1906
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001907 // For internal linkage variables, we don't need an external or weak wrapper.
1908 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1909 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001910
David Majnemer9b21c332014-07-11 20:28:10 +00001911 // If the thread wrapper is replaceable, give it appropriate linkage.
1912 if (isThreadWrapperReplaceable(VD, CGM)) {
1913 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1914 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1915 return llvm::GlobalVariable::WeakAnyLinkage;
1916 return VarLinkage;
1917 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001918 return llvm::GlobalValue::WeakODRLinkage;
1919}
1920
1921llvm::Function *
1922ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001923 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001924 // Mangle the name for the thread_local wrapper function.
1925 SmallString<256> WrapperName;
1926 {
1927 llvm::raw_svector_ostream Out(WrapperName);
1928 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1929 Out.flush();
1930 }
1931
Alexander Musmanf94c3182014-09-26 06:28:25 +00001932 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001933 return cast<llvm::Function>(V);
1934
Alexander Musmanf94c3182014-09-26 06:28:25 +00001935 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001936 if (VD->getType()->isReferenceType())
1937 RetTy = RetTy->getPointerElementType();
1938
1939 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001940 llvm::Function *Wrapper =
1941 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1942 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001943 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001944 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001945 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001946 return Wrapper;
1947}
1948
1949void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00001950 CodeGenModule &CGM,
1951 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1952 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
1953 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1954 llvm::Function *InitFunc = nullptr;
1955 if (!CXXThreadLocalInits.empty()) {
1956 // Generate a guarded initialization function.
1957 llvm::FunctionType *FTy =
1958 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1959 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001960 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00001961 /*TLS=*/true);
1962 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
1963 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
1964 llvm::GlobalVariable::InternalLinkage,
1965 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
1966 Guard->setThreadLocal(true);
1967 CodeGenFunction(CGM)
1968 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
1969 }
1970 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
1971 const VarDecl *VD = CXXThreadLocals[I].first;
1972 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001973
David Majnemer9b21c332014-07-11 20:28:10 +00001974 // Some targets require that all access to thread local variables go through
1975 // the thread wrapper. This means that we cannot attempt to create a thread
1976 // wrapper or a thread helper.
1977 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1978 continue;
1979
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001980 // Mangle the name for the thread_local initialization function.
1981 SmallString<256> InitFnName;
1982 {
1983 llvm::raw_svector_ostream Out(InitFnName);
1984 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1985 Out.flush();
1986 }
1987
1988 // If we have a definition for the variable, emit the initialization
1989 // function as an alias to the global Init function (if any). Otherwise,
1990 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001991 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001992 bool InitIsInitFunc = false;
1993 if (VD->hasDefinition()) {
1994 InitIsInitFunc = true;
1995 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001996 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1997 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001998 } else {
1999 // Emit a weak global function referring to the initialization function.
2000 // This function will not exist if the TU defining the thread_local
2001 // variable in question does not need any dynamic initialization for
2002 // its thread_local variables.
2003 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2004 Init = llvm::Function::Create(
2005 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2006 &CGM.getModule());
2007 }
2008
2009 if (Init)
2010 Init->setVisibility(Var->getVisibility());
2011
2012 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2013 llvm::LLVMContext &Context = CGM.getModule().getContext();
2014 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2015 CGBuilderTy Builder(Entry);
2016 if (InitIsInitFunc) {
2017 if (Init)
2018 Builder.CreateCall(Init);
2019 } else {
2020 // Don't know whether we have an init function. Call it if it exists.
2021 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2022 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2023 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2024 Builder.CreateCondBr(Have, InitBB, ExitBB);
2025
2026 Builder.SetInsertPoint(InitBB);
2027 Builder.CreateCall(Init);
2028 Builder.CreateBr(ExitBB);
2029
2030 Builder.SetInsertPoint(ExitBB);
2031 }
2032
2033 // For a reference, the result of the wrapper function is a pointer to
2034 // the referenced object.
2035 llvm::Value *Val = Var;
2036 if (VD->getType()->isReferenceType()) {
2037 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2038 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2039 Val = LI;
2040 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002041 if (Val->getType() != Wrapper->getReturnType())
2042 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2043 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002044 Builder.CreateRet(Val);
2045 }
2046}
2047
Richard Smith0f383742014-03-26 22:48:22 +00002048LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2049 const VarDecl *VD,
2050 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002051 QualType T = VD->getType();
2052 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2053 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002054 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002055
2056 Val = CGF.Builder.CreateCall(Wrapper);
2057
2058 LValue LV;
2059 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002060 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002061 else
Richard Smith0f383742014-03-26 22:48:22 +00002062 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002063 // FIXME: need setObjCGCLValueClass?
2064 return LV;
2065}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002066
2067/// Return whether the given global decl needs a VTT parameter, which it does
2068/// if it's a base constructor or destructor with virtual bases.
2069bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2070 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2071
2072 // We don't have any virtual bases, just return early.
2073 if (!MD->getParent()->getNumVBases())
2074 return false;
2075
2076 // Check if we have a base constructor.
2077 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2078 return true;
2079
2080 // Check if we have a base destructor.
2081 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2082 return true;
2083
2084 return false;
2085}
David Majnemere2cb8d12014-07-07 06:20:47 +00002086
2087namespace {
2088class ItaniumRTTIBuilder {
2089 CodeGenModule &CGM; // Per-module state.
2090 llvm::LLVMContext &VMContext;
2091 const ItaniumCXXABI &CXXABI; // Per-module state.
2092
2093 /// Fields - The fields of the RTTI descriptor currently being built.
2094 SmallVector<llvm::Constant *, 16> Fields;
2095
2096 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2097 llvm::GlobalVariable *
2098 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2099
2100 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2101 /// descriptor of the given type.
2102 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2103
2104 /// BuildVTablePointer - Build the vtable pointer for the given type.
2105 void BuildVTablePointer(const Type *Ty);
2106
2107 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2108 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2109 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2110
2111 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2112 /// classes with bases that do not satisfy the abi::__si_class_type_info
2113 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2114 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2115
2116 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2117 /// for pointer types.
2118 void BuildPointerTypeInfo(QualType PointeeTy);
2119
2120 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2121 /// type_info for an object type.
2122 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2123
2124 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2125 /// struct, used for member pointer types.
2126 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2127
2128public:
2129 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2130 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2131
2132 // Pointer type info flags.
2133 enum {
2134 /// PTI_Const - Type has const qualifier.
2135 PTI_Const = 0x1,
2136
2137 /// PTI_Volatile - Type has volatile qualifier.
2138 PTI_Volatile = 0x2,
2139
2140 /// PTI_Restrict - Type has restrict qualifier.
2141 PTI_Restrict = 0x4,
2142
2143 /// PTI_Incomplete - Type is incomplete.
2144 PTI_Incomplete = 0x8,
2145
2146 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2147 /// (in pointer to member).
2148 PTI_ContainingClassIncomplete = 0x10
2149 };
2150
2151 // VMI type info flags.
2152 enum {
2153 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2154 VMI_NonDiamondRepeat = 0x1,
2155
2156 /// VMI_DiamondShaped - Class is diamond shaped.
2157 VMI_DiamondShaped = 0x2
2158 };
2159
2160 // Base class type info flags.
2161 enum {
2162 /// BCTI_Virtual - Base class is virtual.
2163 BCTI_Virtual = 0x1,
2164
2165 /// BCTI_Public - Base class is public.
2166 BCTI_Public = 0x2
2167 };
2168
2169 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2170 ///
2171 /// \param Force - true to force the creation of this RTTI value
2172 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2173};
2174}
2175
2176llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2177 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2178 SmallString<256> OutName;
2179 llvm::raw_svector_ostream Out(OutName);
2180 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2181 Out.flush();
2182 StringRef Name = OutName.str();
2183
2184 // We know that the mangled name of the type starts at index 4 of the
2185 // mangled name of the typename, so we can just index into it in order to
2186 // get the mangled name of the type.
2187 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2188 Name.substr(4));
2189
2190 llvm::GlobalVariable *GV =
2191 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2192
2193 GV->setInitializer(Init);
2194
2195 return GV;
2196}
2197
2198llvm::Constant *
2199ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2200 // Mangle the RTTI name.
2201 SmallString<256> OutName;
2202 llvm::raw_svector_ostream Out(OutName);
2203 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2204 Out.flush();
2205 StringRef Name = OutName.str();
2206
2207 // Look for an existing global.
2208 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2209
2210 if (!GV) {
2211 // Create a new global variable.
2212 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2213 /*Constant=*/true,
2214 llvm::GlobalValue::ExternalLinkage, nullptr,
2215 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002216 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2217 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2218 if (RD->hasAttr<DLLImportAttr>())
2219 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2220 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002221 }
2222
2223 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2224}
2225
2226/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2227/// info for that type is defined in the standard library.
2228static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2229 // Itanium C++ ABI 2.9.2:
2230 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2231 // the run-time support library. Specifically, the run-time support
2232 // library should contain type_info objects for the types X, X* and
2233 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2234 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2235 // long, unsigned long, long long, unsigned long long, float, double,
2236 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2237 // half-precision floating point types.
2238 switch (Ty->getKind()) {
2239 case BuiltinType::Void:
2240 case BuiltinType::NullPtr:
2241 case BuiltinType::Bool:
2242 case BuiltinType::WChar_S:
2243 case BuiltinType::WChar_U:
2244 case BuiltinType::Char_U:
2245 case BuiltinType::Char_S:
2246 case BuiltinType::UChar:
2247 case BuiltinType::SChar:
2248 case BuiltinType::Short:
2249 case BuiltinType::UShort:
2250 case BuiltinType::Int:
2251 case BuiltinType::UInt:
2252 case BuiltinType::Long:
2253 case BuiltinType::ULong:
2254 case BuiltinType::LongLong:
2255 case BuiltinType::ULongLong:
2256 case BuiltinType::Half:
2257 case BuiltinType::Float:
2258 case BuiltinType::Double:
2259 case BuiltinType::LongDouble:
2260 case BuiltinType::Char16:
2261 case BuiltinType::Char32:
2262 case BuiltinType::Int128:
2263 case BuiltinType::UInt128:
2264 case BuiltinType::OCLImage1d:
2265 case BuiltinType::OCLImage1dArray:
2266 case BuiltinType::OCLImage1dBuffer:
2267 case BuiltinType::OCLImage2d:
2268 case BuiltinType::OCLImage2dArray:
2269 case BuiltinType::OCLImage3d:
2270 case BuiltinType::OCLSampler:
2271 case BuiltinType::OCLEvent:
2272 return true;
2273
2274 case BuiltinType::Dependent:
2275#define BUILTIN_TYPE(Id, SingletonId)
2276#define PLACEHOLDER_TYPE(Id, SingletonId) \
2277 case BuiltinType::Id:
2278#include "clang/AST/BuiltinTypes.def"
2279 llvm_unreachable("asking for RRTI for a placeholder type!");
2280
2281 case BuiltinType::ObjCId:
2282 case BuiltinType::ObjCClass:
2283 case BuiltinType::ObjCSel:
2284 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2285 }
2286
2287 llvm_unreachable("Invalid BuiltinType Kind!");
2288}
2289
2290static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2291 QualType PointeeTy = PointerTy->getPointeeType();
2292 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2293 if (!BuiltinTy)
2294 return false;
2295
2296 // Check the qualifiers.
2297 Qualifiers Quals = PointeeTy.getQualifiers();
2298 Quals.removeConst();
2299
2300 if (!Quals.empty())
2301 return false;
2302
2303 return TypeInfoIsInStandardLibrary(BuiltinTy);
2304}
2305
2306/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2307/// information for the given type exists in the standard library.
2308static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2309 // Type info for builtin types is defined in the standard library.
2310 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2311 return TypeInfoIsInStandardLibrary(BuiltinTy);
2312
2313 // Type info for some pointer types to builtin types is defined in the
2314 // standard library.
2315 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2316 return TypeInfoIsInStandardLibrary(PointerTy);
2317
2318 return false;
2319}
2320
2321/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2322/// the given type exists somewhere else, and that we should not emit the type
2323/// information in this translation unit. Assumes that it is not a
2324/// standard-library type.
2325static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2326 QualType Ty) {
2327 ASTContext &Context = CGM.getContext();
2328
2329 // If RTTI is disabled, assume it might be disabled in the
2330 // translation unit that defines any potential key function, too.
2331 if (!Context.getLangOpts().RTTI) return false;
2332
2333 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2334 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2335 if (!RD->hasDefinition())
2336 return false;
2337
2338 if (!RD->isDynamicClass())
2339 return false;
2340
2341 // FIXME: this may need to be reconsidered if the key function
2342 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002343 if (CGM.getVTables().isVTableExternal(RD))
2344 return true;
2345
2346 if (RD->hasAttr<DLLImportAttr>())
2347 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002348 }
2349
2350 return false;
2351}
2352
2353/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2354static bool IsIncompleteClassType(const RecordType *RecordTy) {
2355 return !RecordTy->getDecl()->isCompleteDefinition();
2356}
2357
2358/// ContainsIncompleteClassType - Returns whether the given type contains an
2359/// incomplete class type. This is true if
2360///
2361/// * The given type is an incomplete class type.
2362/// * The given type is a pointer type whose pointee type contains an
2363/// incomplete class type.
2364/// * The given type is a member pointer type whose class is an incomplete
2365/// class type.
2366/// * The given type is a member pointer type whoise pointee type contains an
2367/// incomplete class type.
2368/// is an indirect or direct pointer to an incomplete class type.
2369static bool ContainsIncompleteClassType(QualType Ty) {
2370 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2371 if (IsIncompleteClassType(RecordTy))
2372 return true;
2373 }
2374
2375 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2376 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2377
2378 if (const MemberPointerType *MemberPointerTy =
2379 dyn_cast<MemberPointerType>(Ty)) {
2380 // Check if the class type is incomplete.
2381 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2382 if (IsIncompleteClassType(ClassType))
2383 return true;
2384
2385 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2386 }
2387
2388 return false;
2389}
2390
2391// CanUseSingleInheritance - Return whether the given record decl has a "single,
2392// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2393// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2394static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2395 // Check the number of bases.
2396 if (RD->getNumBases() != 1)
2397 return false;
2398
2399 // Get the base.
2400 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2401
2402 // Check that the base is not virtual.
2403 if (Base->isVirtual())
2404 return false;
2405
2406 // Check that the base is public.
2407 if (Base->getAccessSpecifier() != AS_public)
2408 return false;
2409
2410 // Check that the class is dynamic iff the base is.
2411 const CXXRecordDecl *BaseDecl =
2412 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2413 if (!BaseDecl->isEmpty() &&
2414 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2415 return false;
2416
2417 return true;
2418}
2419
2420void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2421 // abi::__class_type_info.
2422 static const char * const ClassTypeInfo =
2423 "_ZTVN10__cxxabiv117__class_type_infoE";
2424 // abi::__si_class_type_info.
2425 static const char * const SIClassTypeInfo =
2426 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2427 // abi::__vmi_class_type_info.
2428 static const char * const VMIClassTypeInfo =
2429 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2430
2431 const char *VTableName = nullptr;
2432
2433 switch (Ty->getTypeClass()) {
2434#define TYPE(Class, Base)
2435#define ABSTRACT_TYPE(Class, Base)
2436#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2437#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2438#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2439#include "clang/AST/TypeNodes.def"
2440 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2441
2442 case Type::LValueReference:
2443 case Type::RValueReference:
2444 llvm_unreachable("References shouldn't get here");
2445
2446 case Type::Auto:
2447 llvm_unreachable("Undeduced auto type shouldn't get here");
2448
2449 case Type::Builtin:
2450 // GCC treats vector and complex types as fundamental types.
2451 case Type::Vector:
2452 case Type::ExtVector:
2453 case Type::Complex:
2454 case Type::Atomic:
2455 // FIXME: GCC treats block pointers as fundamental types?!
2456 case Type::BlockPointer:
2457 // abi::__fundamental_type_info.
2458 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2459 break;
2460
2461 case Type::ConstantArray:
2462 case Type::IncompleteArray:
2463 case Type::VariableArray:
2464 // abi::__array_type_info.
2465 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2466 break;
2467
2468 case Type::FunctionNoProto:
2469 case Type::FunctionProto:
2470 // abi::__function_type_info.
2471 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2472 break;
2473
2474 case Type::Enum:
2475 // abi::__enum_type_info.
2476 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2477 break;
2478
2479 case Type::Record: {
2480 const CXXRecordDecl *RD =
2481 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2482
2483 if (!RD->hasDefinition() || !RD->getNumBases()) {
2484 VTableName = ClassTypeInfo;
2485 } else if (CanUseSingleInheritance(RD)) {
2486 VTableName = SIClassTypeInfo;
2487 } else {
2488 VTableName = VMIClassTypeInfo;
2489 }
2490
2491 break;
2492 }
2493
2494 case Type::ObjCObject:
2495 // Ignore protocol qualifiers.
2496 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2497
2498 // Handle id and Class.
2499 if (isa<BuiltinType>(Ty)) {
2500 VTableName = ClassTypeInfo;
2501 break;
2502 }
2503
2504 assert(isa<ObjCInterfaceType>(Ty));
2505 // Fall through.
2506
2507 case Type::ObjCInterface:
2508 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2509 VTableName = SIClassTypeInfo;
2510 } else {
2511 VTableName = ClassTypeInfo;
2512 }
2513 break;
2514
2515 case Type::ObjCObjectPointer:
2516 case Type::Pointer:
2517 // abi::__pointer_type_info.
2518 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2519 break;
2520
2521 case Type::MemberPointer:
2522 // abi::__pointer_to_member_type_info.
2523 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2524 break;
2525 }
2526
2527 llvm::Constant *VTable =
2528 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2529
2530 llvm::Type *PtrDiffTy =
2531 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2532
2533 // The vtable address point is 2.
2534 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2535 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2536 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2537
2538 Fields.push_back(VTable);
2539}
2540
2541/// \brief Return the linkage that the type info and type info name constants
2542/// should have for the given type.
2543static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2544 QualType Ty) {
2545 // Itanium C++ ABI 2.9.5p7:
2546 // In addition, it and all of the intermediate abi::__pointer_type_info
2547 // structs in the chain down to the abi::__class_type_info for the
2548 // incomplete class type must be prevented from resolving to the
2549 // corresponding type_info structs for the complete class type, possibly
2550 // by making them local static objects. Finally, a dummy class RTTI is
2551 // generated for the incomplete type that will not resolve to the final
2552 // complete class RTTI (because the latter need not exist), possibly by
2553 // making it a local static object.
2554 if (ContainsIncompleteClassType(Ty))
2555 return llvm::GlobalValue::InternalLinkage;
2556
2557 switch (Ty->getLinkage()) {
2558 case NoLinkage:
2559 case InternalLinkage:
2560 case UniqueExternalLinkage:
2561 return llvm::GlobalValue::InternalLinkage;
2562
2563 case VisibleNoLinkage:
2564 case ExternalLinkage:
2565 if (!CGM.getLangOpts().RTTI) {
2566 // RTTI is not enabled, which means that this type info struct is going
2567 // to be used for exception handling. Give it linkonce_odr linkage.
2568 return llvm::GlobalValue::LinkOnceODRLinkage;
2569 }
2570
2571 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2572 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2573 if (RD->hasAttr<WeakAttr>())
2574 return llvm::GlobalValue::WeakODRLinkage;
2575 if (RD->isDynamicClass())
2576 return CGM.getVTableLinkage(RD);
2577 }
2578
2579 return llvm::GlobalValue::LinkOnceODRLinkage;
2580 }
2581
2582 llvm_unreachable("Invalid linkage!");
2583}
2584
2585llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2586 // We want to operate on the canonical type.
2587 Ty = CGM.getContext().getCanonicalType(Ty);
2588
2589 // Check if we've already emitted an RTTI descriptor for this type.
2590 SmallString<256> OutName;
2591 llvm::raw_svector_ostream Out(OutName);
2592 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2593 Out.flush();
2594 StringRef Name = OutName.str();
2595
2596 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2597 if (OldGV && !OldGV->isDeclaration()) {
2598 assert(!OldGV->hasAvailableExternallyLinkage() &&
2599 "available_externally typeinfos not yet implemented");
2600
2601 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2602 }
2603
2604 // Check if there is already an external RTTI descriptor for this type.
2605 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2606 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2607 return GetAddrOfExternalRTTIDescriptor(Ty);
2608
2609 // Emit the standard library with external linkage.
2610 llvm::GlobalVariable::LinkageTypes Linkage;
2611 if (IsStdLib)
2612 Linkage = llvm::GlobalValue::ExternalLinkage;
2613 else
2614 Linkage = getTypeInfoLinkage(CGM, Ty);
2615
2616 // Add the vtable pointer.
2617 BuildVTablePointer(cast<Type>(Ty));
2618
2619 // And the name.
2620 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2621 llvm::Constant *TypeNameField;
2622
2623 // If we're supposed to demote the visibility, be sure to set a flag
2624 // to use a string comparison for type_info comparisons.
2625 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2626 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2627 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2628 // The flag is the sign bit, which on ARM64 is defined to be clear
2629 // for global pointers. This is very ARM64-specific.
2630 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2631 llvm::Constant *flag =
2632 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2633 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2634 TypeNameField =
2635 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2636 } else {
2637 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2638 }
2639 Fields.push_back(TypeNameField);
2640
2641 switch (Ty->getTypeClass()) {
2642#define TYPE(Class, Base)
2643#define ABSTRACT_TYPE(Class, Base)
2644#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2645#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2646#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2647#include "clang/AST/TypeNodes.def"
2648 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2649
2650 // GCC treats vector types as fundamental types.
2651 case Type::Builtin:
2652 case Type::Vector:
2653 case Type::ExtVector:
2654 case Type::Complex:
2655 case Type::BlockPointer:
2656 // Itanium C++ ABI 2.9.5p4:
2657 // abi::__fundamental_type_info adds no data members to std::type_info.
2658 break;
2659
2660 case Type::LValueReference:
2661 case Type::RValueReference:
2662 llvm_unreachable("References shouldn't get here");
2663
2664 case Type::Auto:
2665 llvm_unreachable("Undeduced auto type shouldn't get here");
2666
2667 case Type::ConstantArray:
2668 case Type::IncompleteArray:
2669 case Type::VariableArray:
2670 // Itanium C++ ABI 2.9.5p5:
2671 // abi::__array_type_info adds no data members to std::type_info.
2672 break;
2673
2674 case Type::FunctionNoProto:
2675 case Type::FunctionProto:
2676 // Itanium C++ ABI 2.9.5p5:
2677 // abi::__function_type_info adds no data members to std::type_info.
2678 break;
2679
2680 case Type::Enum:
2681 // Itanium C++ ABI 2.9.5p5:
2682 // abi::__enum_type_info adds no data members to std::type_info.
2683 break;
2684
2685 case Type::Record: {
2686 const CXXRecordDecl *RD =
2687 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2688 if (!RD->hasDefinition() || !RD->getNumBases()) {
2689 // We don't need to emit any fields.
2690 break;
2691 }
2692
2693 if (CanUseSingleInheritance(RD))
2694 BuildSIClassTypeInfo(RD);
2695 else
2696 BuildVMIClassTypeInfo(RD);
2697
2698 break;
2699 }
2700
2701 case Type::ObjCObject:
2702 case Type::ObjCInterface:
2703 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2704 break;
2705
2706 case Type::ObjCObjectPointer:
2707 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2708 break;
2709
2710 case Type::Pointer:
2711 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2712 break;
2713
2714 case Type::MemberPointer:
2715 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2716 break;
2717
2718 case Type::Atomic:
2719 // No fields, at least for the moment.
2720 break;
2721 }
2722
2723 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2724
Rafael Espindolacb92c192015-01-15 23:18:01 +00002725 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002726 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002727 new llvm::GlobalVariable(M, Init->getType(),
2728 /*Constant=*/true, Linkage, Init, Name);
2729
2730 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2731 GV->setComdat(M.getOrInsertComdat(GV->getName()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002732
2733 // If there's already an old global variable, replace it with the new one.
2734 if (OldGV) {
2735 GV->takeName(OldGV);
2736 llvm::Constant *NewPtr =
2737 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2738 OldGV->replaceAllUsesWith(NewPtr);
2739 OldGV->eraseFromParent();
2740 }
2741
2742 // The Itanium ABI specifies that type_info objects must be globally
2743 // unique, with one exception: if the type is an incomplete class
2744 // type or a (possibly indirect) pointer to one. That exception
2745 // affects the general case of comparing type_info objects produced
2746 // by the typeid operator, which is why the comparison operators on
2747 // std::type_info generally use the type_info name pointers instead
2748 // of the object addresses. However, the language's built-in uses
2749 // of RTTI generally require class types to be complete, even when
2750 // manipulating pointers to those class types. This allows the
2751 // implementation of dynamic_cast to rely on address equality tests,
2752 // which is much faster.
2753
2754 // All of this is to say that it's important that both the type_info
2755 // object and the type_info name be uniqued when weakly emitted.
2756
2757 // Give the type_info object and name the formal visibility of the
2758 // type itself.
2759 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2760 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2761 // If the linkage is local, only default visibility makes sense.
2762 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2763 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2764 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2765 else
2766 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2767 TypeName->setVisibility(llvmVisibility);
2768 GV->setVisibility(llvmVisibility);
2769
2770 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2771}
2772
2773/// ComputeQualifierFlags - Compute the pointer type info flags from the
2774/// given qualifier.
2775static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2776 unsigned Flags = 0;
2777
2778 if (Quals.hasConst())
2779 Flags |= ItaniumRTTIBuilder::PTI_Const;
2780 if (Quals.hasVolatile())
2781 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2782 if (Quals.hasRestrict())
2783 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2784
2785 return Flags;
2786}
2787
2788/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2789/// for the given Objective-C object type.
2790void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2791 // Drop qualifiers.
2792 const Type *T = OT->getBaseType().getTypePtr();
2793 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2794
2795 // The builtin types are abi::__class_type_infos and don't require
2796 // extra fields.
2797 if (isa<BuiltinType>(T)) return;
2798
2799 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2800 ObjCInterfaceDecl *Super = Class->getSuperClass();
2801
2802 // Root classes are also __class_type_info.
2803 if (!Super) return;
2804
2805 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2806
2807 // Everything else is single inheritance.
2808 llvm::Constant *BaseTypeInfo =
2809 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2810 Fields.push_back(BaseTypeInfo);
2811}
2812
2813/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2814/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2815void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2816 // Itanium C++ ABI 2.9.5p6b:
2817 // It adds to abi::__class_type_info a single member pointing to the
2818 // type_info structure for the base type,
2819 llvm::Constant *BaseTypeInfo =
2820 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2821 Fields.push_back(BaseTypeInfo);
2822}
2823
2824namespace {
2825 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2826 /// a class hierarchy.
2827 struct SeenBases {
2828 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2829 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2830 };
2831}
2832
2833/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2834/// abi::__vmi_class_type_info.
2835///
2836static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2837 SeenBases &Bases) {
2838
2839 unsigned Flags = 0;
2840
2841 const CXXRecordDecl *BaseDecl =
2842 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2843
2844 if (Base->isVirtual()) {
2845 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002846 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002847 // If this virtual base has been seen before, then the class is diamond
2848 // shaped.
2849 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2850 } else {
2851 if (Bases.NonVirtualBases.count(BaseDecl))
2852 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2853 }
2854 } else {
2855 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002856 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002857 // If this non-virtual base has been seen before, then the class has non-
2858 // diamond shaped repeated inheritance.
2859 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2860 } else {
2861 if (Bases.VirtualBases.count(BaseDecl))
2862 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2863 }
2864 }
2865
2866 // Walk all bases.
2867 for (const auto &I : BaseDecl->bases())
2868 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2869
2870 return Flags;
2871}
2872
2873static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2874 unsigned Flags = 0;
2875 SeenBases Bases;
2876
2877 // Walk all bases.
2878 for (const auto &I : RD->bases())
2879 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2880
2881 return Flags;
2882}
2883
2884/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2885/// classes with bases that do not satisfy the abi::__si_class_type_info
2886/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2887void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2888 llvm::Type *UnsignedIntLTy =
2889 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2890
2891 // Itanium C++ ABI 2.9.5p6c:
2892 // __flags is a word with flags describing details about the class
2893 // structure, which may be referenced by using the __flags_masks
2894 // enumeration. These flags refer to both direct and indirect bases.
2895 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2896 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2897
2898 // Itanium C++ ABI 2.9.5p6c:
2899 // __base_count is a word with the number of direct proper base class
2900 // descriptions that follow.
2901 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2902
2903 if (!RD->getNumBases())
2904 return;
2905
2906 llvm::Type *LongLTy =
2907 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2908
2909 // Now add the base class descriptions.
2910
2911 // Itanium C++ ABI 2.9.5p6c:
2912 // __base_info[] is an array of base class descriptions -- one for every
2913 // direct proper base. Each description is of the type:
2914 //
2915 // struct abi::__base_class_type_info {
2916 // public:
2917 // const __class_type_info *__base_type;
2918 // long __offset_flags;
2919 //
2920 // enum __offset_flags_masks {
2921 // __virtual_mask = 0x1,
2922 // __public_mask = 0x2,
2923 // __offset_shift = 8
2924 // };
2925 // };
2926 for (const auto &Base : RD->bases()) {
2927 // The __base_type member points to the RTTI for the base type.
2928 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2929
2930 const CXXRecordDecl *BaseDecl =
2931 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2932
2933 int64_t OffsetFlags = 0;
2934
2935 // All but the lower 8 bits of __offset_flags are a signed offset.
2936 // For a non-virtual base, this is the offset in the object of the base
2937 // subobject. For a virtual base, this is the offset in the virtual table of
2938 // the virtual base offset for the virtual base referenced (negative).
2939 CharUnits Offset;
2940 if (Base.isVirtual())
2941 Offset =
2942 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2943 else {
2944 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2945 Offset = Layout.getBaseClassOffset(BaseDecl);
2946 };
2947
2948 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2949
2950 // The low-order byte of __offset_flags contains flags, as given by the
2951 // masks from the enumeration __offset_flags_masks.
2952 if (Base.isVirtual())
2953 OffsetFlags |= BCTI_Virtual;
2954 if (Base.getAccessSpecifier() == AS_public)
2955 OffsetFlags |= BCTI_Public;
2956
2957 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2958 }
2959}
2960
2961/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2962/// used for pointer types.
2963void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2964 Qualifiers Quals;
2965 QualType UnqualifiedPointeeTy =
2966 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2967
2968 // Itanium C++ ABI 2.9.5p7:
2969 // __flags is a flag word describing the cv-qualification and other
2970 // attributes of the type pointed to
2971 unsigned Flags = ComputeQualifierFlags(Quals);
2972
2973 // Itanium C++ ABI 2.9.5p7:
2974 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2975 // incomplete class type, the incomplete target type flag is set.
2976 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2977 Flags |= PTI_Incomplete;
2978
2979 llvm::Type *UnsignedIntLTy =
2980 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2981 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2982
2983 // Itanium C++ ABI 2.9.5p7:
2984 // __pointee is a pointer to the std::type_info derivation for the
2985 // unqualified type being pointed to.
2986 llvm::Constant *PointeeTypeInfo =
2987 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2988 Fields.push_back(PointeeTypeInfo);
2989}
2990
2991/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2992/// struct, used for member pointer types.
2993void
2994ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2995 QualType PointeeTy = Ty->getPointeeType();
2996
2997 Qualifiers Quals;
2998 QualType UnqualifiedPointeeTy =
2999 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3000
3001 // Itanium C++ ABI 2.9.5p7:
3002 // __flags is a flag word describing the cv-qualification and other
3003 // attributes of the type pointed to.
3004 unsigned Flags = ComputeQualifierFlags(Quals);
3005
3006 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3007
3008 // Itanium C++ ABI 2.9.5p7:
3009 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3010 // incomplete class type, the incomplete target type flag is set.
3011 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3012 Flags |= PTI_Incomplete;
3013
3014 if (IsIncompleteClassType(ClassType))
3015 Flags |= PTI_ContainingClassIncomplete;
3016
3017 llvm::Type *UnsignedIntLTy =
3018 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3019 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3020
3021 // Itanium C++ ABI 2.9.5p7:
3022 // __pointee is a pointer to the std::type_info derivation for the
3023 // unqualified type being pointed to.
3024 llvm::Constant *PointeeTypeInfo =
3025 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3026 Fields.push_back(PointeeTypeInfo);
3027
3028 // Itanium C++ ABI 2.9.5p9:
3029 // __context is a pointer to an abi::__class_type_info corresponding to the
3030 // class type containing the member pointed to
3031 // (e.g., the "A" in "int A::*").
3032 Fields.push_back(
3033 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3034}
3035
3036llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
3037 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3038}
3039
3040void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3041 QualType PointerType = getContext().getPointerType(Type);
3042 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3043 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3044 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3045 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3046}
3047
3048void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3049 QualType FundamentalTypes[] = {
3050 getContext().VoidTy, getContext().NullPtrTy,
3051 getContext().BoolTy, getContext().WCharTy,
3052 getContext().CharTy, getContext().UnsignedCharTy,
3053 getContext().SignedCharTy, getContext().ShortTy,
3054 getContext().UnsignedShortTy, getContext().IntTy,
3055 getContext().UnsignedIntTy, getContext().LongTy,
3056 getContext().UnsignedLongTy, getContext().LongLongTy,
3057 getContext().UnsignedLongLongTy, getContext().HalfTy,
3058 getContext().FloatTy, getContext().DoubleTy,
3059 getContext().LongDoubleTy, getContext().Char16Ty,
3060 getContext().Char32Ty,
3061 };
3062 for (const QualType &FundamentalType : FundamentalTypes)
3063 EmitFundamentalRTTIDescriptor(FundamentalType);
3064}
3065
3066/// What sort of uniqueness rules should we use for the RTTI for the
3067/// given type?
3068ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3069 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3070 if (shouldRTTIBeUnique())
3071 return RUK_Unique;
3072
3073 // It's only necessary for linkonce_odr or weak_odr linkage.
3074 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3075 Linkage != llvm::GlobalValue::WeakODRLinkage)
3076 return RUK_Unique;
3077
3078 // It's only necessary with default visibility.
3079 if (CanTy->getVisibility() != DefaultVisibility)
3080 return RUK_Unique;
3081
3082 // If we're not required to publish this symbol, hide it.
3083 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3084 return RUK_NonUniqueHidden;
3085
3086 // If we're required to publish this symbol, as we might be under an
3087 // explicit instantiation, leave it with default visibility but
3088 // enable string-comparisons.
3089 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3090 return RUK_NonUniqueVisible;
3091}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003092
Rafael Espindola1e4df922014-09-16 15:18:21 +00003093// Find out how to codegen the complete destructor and constructor
3094namespace {
3095enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3096}
3097static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3098 const CXXMethodDecl *MD) {
3099 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3100 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003101
Rafael Espindola1e4df922014-09-16 15:18:21 +00003102 // The complete and base structors are not equivalent if there are any virtual
3103 // bases, so emit separate functions.
3104 if (MD->getParent()->getNumVBases())
3105 return StructorCodegen::Emit;
3106
3107 GlobalDecl AliasDecl;
3108 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3109 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3110 } else {
3111 const auto *CD = cast<CXXConstructorDecl>(MD);
3112 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3113 }
3114 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3115
3116 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3117 return StructorCodegen::RAUW;
3118
3119 // FIXME: Should we allow available_externally aliases?
3120 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3121 return StructorCodegen::RAUW;
3122
Rafael Espindola0806f982014-09-16 20:19:43 +00003123 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3124 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3125 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3126 return StructorCodegen::COMDAT;
3127 return StructorCodegen::Emit;
3128 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003129
3130 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003131}
3132
Rafael Espindola1e4df922014-09-16 15:18:21 +00003133static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3134 GlobalDecl AliasDecl,
3135 GlobalDecl TargetDecl) {
3136 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3137
3138 StringRef MangledName = CGM.getMangledName(AliasDecl);
3139 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3140 if (Entry && !Entry->isDeclaration())
3141 return;
3142
3143 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3144 llvm::PointerType *AliasType = Aliasee->getType();
3145
3146 // Create the alias with no name.
3147 auto *Alias = llvm::GlobalAlias::create(
3148 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3149
3150 // Switch any previous uses to the alias.
3151 if (Entry) {
3152 assert(Entry->getType() == AliasType &&
3153 "declaration exists with different type");
3154 Alias->takeName(Entry);
3155 Entry->replaceAllUsesWith(Alias);
3156 Entry->eraseFromParent();
3157 } else {
3158 Alias->setName(MangledName);
3159 }
3160
3161 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003162 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003163}
3164
3165void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3166 StructorType Type) {
3167 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3168 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3169
3170 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3171
3172 if (Type == StructorType::Complete) {
3173 GlobalDecl CompleteDecl;
3174 GlobalDecl BaseDecl;
3175 if (CD) {
3176 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3177 BaseDecl = GlobalDecl(CD, Ctor_Base);
3178 } else {
3179 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3180 BaseDecl = GlobalDecl(DD, Dtor_Base);
3181 }
3182
3183 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3184 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3185 return;
3186 }
3187
3188 if (CGType == StructorCodegen::RAUW) {
3189 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3190 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3191 CGM.addReplacement(MangledName, Aliasee);
3192 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003193 }
3194 }
3195
3196 // The base destructor is equivalent to the base destructor of its
3197 // base class if there is exactly one non-virtual base class with a
3198 // non-trivial destructor, there are no fields with a non-trivial
3199 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003200 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3201 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003202 return;
3203
Rafael Espindola1e4df922014-09-16 15:18:21 +00003204 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003205
Rafael Espindola1e4df922014-09-16 15:18:21 +00003206 if (CGType == StructorCodegen::COMDAT) {
3207 SmallString<256> Buffer;
3208 llvm::raw_svector_ostream Out(Buffer);
3209 if (DD)
3210 getMangleContext().mangleCXXDtorComdat(DD, Out);
3211 else
3212 getMangleContext().mangleCXXCtorComdat(CD, Out);
3213 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3214 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003215 } else {
3216 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003217 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003218}