blob: bcc0f166203a12daaec0d7a1645d9d1642c7ba4a [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall7a9aac22010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
David Majnemer1162d252014-06-22 19:05:33 +000028#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000032
33using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000034using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000035
36namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000037class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000038 /// VTables - All the vtables which have been defined.
39 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
40
John McCall475999d2010-08-22 00:05:51 +000041protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000042 bool UseARMMethodPtrABI;
43 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000044
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000045 ItaniumMangleContext &getMangleContext() {
46 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
47 }
48
Charles Davis4e786dd2010-05-25 19:52:27 +000049public:
Mark Seabornedf0d382013-07-24 16:25:13 +000050 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
51 bool UseARMMethodPtrABI = false,
52 bool UseARMGuardVarABI = false) :
53 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
54 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000055
Reid Kleckner40ca9132014-05-13 22:05:45 +000056 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000057
Craig Topper4f12f102014-03-12 06:41:41 +000058 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000059 // Structures with either a non-trivial destructor or a non-trivial
60 // copy constructor are always indirect.
61 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
62 // special members.
63 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064 return RAA_Indirect;
65 return RAA_Default;
66 }
67
Craig Topper4f12f102014-03-12 06:41:41 +000068 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000069
Craig Topper4f12f102014-03-12 06:41:41 +000070 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000071
Craig Topper4f12f102014-03-12 06:41:41 +000072 llvm::Value *
73 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74 const Expr *E,
75 llvm::Value *&This,
76 llvm::Value *MemFnPtr,
77 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000078
Craig Topper4f12f102014-03-12 06:41:41 +000079 llvm::Value *
80 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
81 llvm::Value *Base,
82 llvm::Value *MemPtr,
83 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000084
John McCall7a9aac22010-08-23 01:21:21 +000085 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
86 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000087 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000088 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000089 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000090
Craig Topper4f12f102014-03-12 06:41:41 +000091 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000092
Craig Topper4f12f102014-03-12 06:41:41 +000093 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000094 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000095 CharUnits offset) override;
96 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +000097 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
98 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +000099
John McCall7a9aac22010-08-23 01:21:21 +0000100 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000101 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000102 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000103 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000104
John McCall7a9aac22010-08-23 01:21:21 +0000105 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000106 llvm::Value *Addr,
107 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000108
Craig Topper4f12f102014-03-12 06:41:41 +0000109 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
110 QualType type) override;
John McCall82fb8922012-09-25 10:10:39 +0000111
David Majnemere2cb8d12014-07-07 06:20:47 +0000112 void EmitFundamentalRTTIDescriptor(QualType Type);
113 void EmitFundamentalRTTIDescriptors();
114 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
115
David Majnemer1162d252014-06-22 19:05:33 +0000116 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
117 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
118 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
119 llvm::Value *ThisPtr,
120 llvm::Type *StdTypeInfoPtrTy) override;
121
122 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
123 QualType SrcRecordTy) override;
124
125 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
126 QualType SrcRecordTy, QualType DestTy,
127 QualType DestRecordTy,
128 llvm::BasicBlock *CastEnd) override;
129
130 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
131 QualType SrcRecordTy,
132 QualType DestTy) override;
133
134 bool EmitBadCastCall(CodeGenFunction &CGF) override;
135
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Value *
137 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
138 const CXXRecordDecl *ClassDecl,
139 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000140
Craig Topper4f12f102014-03-12 06:41:41 +0000141 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000142
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000143 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
144 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000145
Reid Klecknere7de47e2013-07-22 13:51:44 +0000146 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000148 // Itanium does not emit any destructor variant as an inline thunk.
149 // Delegating may occur as an optimization, but all variants are either
150 // emitted with external linkage or as linkonce if they are inline and used.
151 return false;
152 }
153
Craig Topper4f12f102014-03-12 06:41:41 +0000154 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000155
Reid Kleckner89077a12013-12-17 19:46:40 +0000156 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000157 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000158
Craig Topper4f12f102014-03-12 06:41:41 +0000159 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000160
Reid Kleckner89077a12013-12-17 19:46:40 +0000161 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
162 const CXXConstructorDecl *D,
163 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000164 bool Delegating,
165 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000166
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
168 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000169 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000170
Craig Topper4f12f102014-03-12 06:41:41 +0000171 void emitVTableDefinitions(CodeGenVTables &CGVT,
172 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000173
174 llvm::Value *getVTableAddressPointInStructor(
175 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
176 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000177 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000178
179 llvm::Constant *
180 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000181 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000182
183 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000184 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000185
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000186 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 llvm::Value *This,
188 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000189
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000190 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
191 const CXXDestructorDecl *Dtor,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000192 CXXDtorType DtorType, llvm::Value *This,
193 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000194
Craig Topper4f12f102014-03-12 06:41:41 +0000195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000196
Hans Wennborgc94391d2014-06-06 20:04:01 +0000197 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
198 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000199 // Allow inlining of thunks by emitting them with available_externally
200 // linkage together with vtables when needed.
201 if (ForVTable)
202 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
203 }
204
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000205 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000207
208 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000209 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000210
David Majnemer196ac332014-09-11 23:05:02 +0000211 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
212 FunctionArgList &Args) const override {
213 assert(!Args.empty() && "expected the arglist to not be empty!");
214 return Args.size() - 1;
215 }
216
Craig Topper4f12f102014-03-12 06:41:41 +0000217 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
218 StringRef GetDeletedVirtualCallName() override
219 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000220
Craig Topper4f12f102014-03-12 06:41:41 +0000221 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000222 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
223 llvm::Value *NewPtr,
224 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000225 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000226 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000227 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
228 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000230
John McCallcdf7ef52010-11-06 09:44:32 +0000231 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000232 llvm::GlobalVariable *DeclPtr,
233 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000234 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000235 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000236
237 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
238 llvm::GlobalVariable *Var);
239 void EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +0000240 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000241 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000242 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
243 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000244
Craig Topper4f12f102014-03-12 06:41:41 +0000245 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000246
247 /**************************** RTTI Uniqueness ******************************/
248
249protected:
250 /// Returns true if the ABI requires RTTI type_info objects to be unique
251 /// across a program.
252 virtual bool shouldRTTIBeUnique() const { return true; }
253
254public:
255 /// What sort of unique-RTTI behavior should we use?
256 enum RTTIUniquenessKind {
257 /// We are guaranteeing, or need to guarantee, that the RTTI string
258 /// is unique.
259 RUK_Unique,
260
261 /// We are not guaranteeing uniqueness for the RTTI string, so we
262 /// can demote to hidden visibility but must use string comparisons.
263 RUK_NonUniqueHidden,
264
265 /// We are not guaranteeing uniqueness for the RTTI string, so we
266 /// have to use string comparisons, but we also have to emit it with
267 /// non-hidden visibility.
268 RUK_NonUniqueVisible
269 };
270
271 /// Return the required visibility status for the given type and linkage in
272 /// the current ABI.
273 RTTIUniquenessKind
274 classifyRTTIUniqueness(QualType CanTy,
275 llvm::GlobalValue::LinkageTypes Linkage) const;
276 friend class ItaniumRTTIBuilder;
Charles Davis4e786dd2010-05-25 19:52:27 +0000277};
John McCall86353412010-08-21 22:46:04 +0000278
279class ARMCXXABI : public ItaniumCXXABI {
280public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000281 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
282 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
283 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000284
Craig Topper4f12f102014-03-12 06:41:41 +0000285 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000286 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
287 isa<CXXDestructorDecl>(GD.getDecl()) &&
288 GD.getDtorType() != Dtor_Deleting));
289 }
John McCall5d865c322010-08-31 07:33:07 +0000290
Craig Topper4f12f102014-03-12 06:41:41 +0000291 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
292 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000293
Craig Topper4f12f102014-03-12 06:41:41 +0000294 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000295 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
296 llvm::Value *NewPtr,
297 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000298 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000299 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000300 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000301 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000302};
Tim Northovera2ee4332014-03-29 15:09:45 +0000303
304class iOS64CXXABI : public ARMCXXABI {
305public:
306 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000307
308 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000309 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000310};
Charles Davis4e786dd2010-05-25 19:52:27 +0000311}
312
Charles Davis53c59df2010-08-16 03:33:14 +0000313CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000314 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000315 // For IR-generation purposes, there's no significant difference
316 // between the ARM and iOS ABIs.
317 case TargetCXXABI::GenericARM:
318 case TargetCXXABI::iOS:
319 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000320
Tim Northovera2ee4332014-03-29 15:09:45 +0000321 case TargetCXXABI::iOS64:
322 return new iOS64CXXABI(CGM);
323
Tim Northover9bb857a2013-01-31 12:13:10 +0000324 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
325 // include the other 32-bit ARM oddities: constructor/destructor return values
326 // and array cookies.
327 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000328 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
329 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000330
John McCall57625922013-01-25 23:36:14 +0000331 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000332 if (CGM.getContext().getTargetInfo().getTriple().getArch()
333 == llvm::Triple::le32) {
334 // For PNaCl, use ARM-style method pointers so that PNaCl code
335 // does not assume anything about the alignment of function
336 // pointers.
337 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
338 /* UseARMGuardVarABI = */ false);
339 }
John McCall57625922013-01-25 23:36:14 +0000340 return new ItaniumCXXABI(CGM);
341
342 case TargetCXXABI::Microsoft:
343 llvm_unreachable("Microsoft ABI is not Itanium-based");
344 }
345 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000346}
347
Chris Lattnera5f58b02011-07-09 17:41:47 +0000348llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000349ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
350 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000351 return CGM.PtrDiffTy;
352 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000353}
354
John McCalld9c6c0b2010-08-22 00:59:17 +0000355/// In the Itanium and ARM ABIs, method pointers have the form:
356/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
357///
358/// In the Itanium ABI:
359/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
360/// - the this-adjustment is (memptr.adj)
361/// - the virtual offset is (memptr.ptr - 1)
362///
363/// In the ARM ABI:
364/// - method pointers are virtual if (memptr.adj & 1) is nonzero
365/// - the this-adjustment is (memptr.adj >> 1)
366/// - the virtual offset is (memptr.ptr)
367/// ARM uses 'adj' for the virtual flag because Thumb functions
368/// may be only single-byte aligned.
369///
370/// If the member is virtual, the adjusted 'this' pointer points
371/// to a vtable pointer from which the virtual offset is applied.
372///
373/// If the member is non-virtual, memptr.ptr is the address of
374/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000375llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
376 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
377 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000378 CGBuilderTy &Builder = CGF.Builder;
379
380 const FunctionProtoType *FPT =
381 MPT->getPointeeType()->getAs<FunctionProtoType>();
382 const CXXRecordDecl *RD =
383 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
384
Chris Lattner2192fe52011-07-18 04:24:23 +0000385 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000386 CGM.getTypes().GetFunctionType(
387 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000388
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000389 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000390
John McCalld9c6c0b2010-08-22 00:59:17 +0000391 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
392 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
393 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
394
John McCalla1dee5302010-08-22 10:59:02 +0000395 // Extract memptr.adj, which is in the second field.
396 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000397
398 // Compute the true adjustment.
399 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000400 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000401 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000402
403 // Apply the adjustment and cast back to the original struct type
404 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000405 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
406 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
407 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000408
409 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000410 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000411
412 // If the LSB in the function pointer is 1, the function pointer points to
413 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000414 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000415 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000416 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
417 else
418 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
419 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000420 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
421
422 // In the virtual path, the adjustment left 'This' pointing to the
423 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000424 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000425 CGF.EmitBlock(FnVirtual);
426
427 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000428 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000429 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000430
431 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000432 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000433 if (!UseARMMethodPtrABI)
434 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000435 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000436
437 // Load the virtual function to call.
438 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000439 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000440 CGF.EmitBranch(FnEnd);
441
442 // In the non-virtual path, the function pointer is actually a
443 // function pointer.
444 CGF.EmitBlock(FnNonVirtual);
445 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000446 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000447
448 // We're done.
449 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000450 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000451 Callee->addIncoming(VirtualFn, FnVirtual);
452 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
453 return Callee;
454}
John McCalla8bbb822010-08-22 03:04:22 +0000455
John McCallc134eb52010-08-31 21:07:20 +0000456/// Compute an l-value by applying the given pointer-to-member to a
457/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000458llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
459 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
460 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000461 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000462
463 CGBuilderTy &Builder = CGF.Builder;
464
Micah Villmowea2fea22012-10-25 15:39:14 +0000465 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000466
467 // Cast to char*.
468 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
469
470 // Apply the offset, which we assume is non-null.
471 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
472
473 // Cast the address to the appropriate pointer type, adopting the
474 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000475 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000476 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000477 return Builder.CreateBitCast(Addr, PType);
478}
479
John McCallc62bb392012-02-15 01:22:51 +0000480/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
481/// conversion.
482///
483/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000484///
485/// Obligatory offset/adjustment diagram:
486/// <-- offset --> <-- adjustment -->
487/// |--------------------------|----------------------|--------------------|
488/// ^Derived address point ^Base address point ^Member address point
489///
490/// So when converting a base member pointer to a derived member pointer,
491/// we add the offset to the adjustment because the address point has
492/// decreased; and conversely, when converting a derived MP to a base MP
493/// we subtract the offset from the adjustment because the address point
494/// has increased.
495///
496/// The standard forbids (at compile time) conversion to and from
497/// virtual bases, which is why we don't have to consider them here.
498///
499/// The standard forbids (at run time) casting a derived MP to a base
500/// MP when the derived MP does not point to a member of the base.
501/// This is why -1 is a reasonable choice for null data member
502/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000503llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000504ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
505 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000506 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000507 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000508 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
509 E->getCastKind() == CK_ReinterpretMemberPointer);
510
511 // Under Itanium, reinterprets don't require any additional processing.
512 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
513
514 // Use constant emission if we can.
515 if (isa<llvm::Constant>(src))
516 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
517
518 llvm::Constant *adj = getMemberPointerAdjustment(E);
519 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000520
521 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000522 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000523
John McCallc62bb392012-02-15 01:22:51 +0000524 const MemberPointerType *destTy =
525 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000526
John McCall7a9aac22010-08-23 01:21:21 +0000527 // For member data pointers, this is just a matter of adding the
528 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000529 if (destTy->isMemberDataPointer()) {
530 llvm::Value *dst;
531 if (isDerivedToBase)
532 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000533 else
John McCallc62bb392012-02-15 01:22:51 +0000534 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000535
536 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000537 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
538 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
539 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000540 }
541
John McCalla1dee5302010-08-22 10:59:02 +0000542 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000543 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000544 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
545 offset <<= 1;
546 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000547 }
548
John McCallc62bb392012-02-15 01:22:51 +0000549 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
550 llvm::Value *dstAdj;
551 if (isDerivedToBase)
552 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000553 else
John McCallc62bb392012-02-15 01:22:51 +0000554 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000555
John McCallc62bb392012-02-15 01:22:51 +0000556 return Builder.CreateInsertValue(src, dstAdj, 1);
557}
558
559llvm::Constant *
560ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
561 llvm::Constant *src) {
562 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
563 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
564 E->getCastKind() == CK_ReinterpretMemberPointer);
565
566 // Under Itanium, reinterprets don't require any additional processing.
567 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
568
569 // If the adjustment is trivial, we don't need to do anything.
570 llvm::Constant *adj = getMemberPointerAdjustment(E);
571 if (!adj) return src;
572
573 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
574
575 const MemberPointerType *destTy =
576 E->getType()->castAs<MemberPointerType>();
577
578 // For member data pointers, this is just a matter of adding the
579 // offset if the source is non-null.
580 if (destTy->isMemberDataPointer()) {
581 // null maps to null.
582 if (src->isAllOnesValue()) return src;
583
584 if (isDerivedToBase)
585 return llvm::ConstantExpr::getNSWSub(src, adj);
586 else
587 return llvm::ConstantExpr::getNSWAdd(src, adj);
588 }
589
590 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000591 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000592 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
593 offset <<= 1;
594 adj = llvm::ConstantInt::get(adj->getType(), offset);
595 }
596
597 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
598 llvm::Constant *dstAdj;
599 if (isDerivedToBase)
600 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
601 else
602 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
603
604 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000605}
John McCall84fa5102010-08-22 04:16:24 +0000606
607llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000608ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000609 // Itanium C++ ABI 2.3:
610 // A NULL pointer is represented as -1.
611 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000612 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000613
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000614 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000615 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000616 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000617}
618
John McCallf3a88602011-02-03 08:15:49 +0000619llvm::Constant *
620ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
621 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000622 // Itanium C++ ABI 2.3:
623 // A pointer to data member is an offset from the base address of
624 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000625 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000626}
627
John McCall2979fe02011-04-12 00:42:48 +0000628llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000629 return BuildMemberPointer(MD, CharUnits::Zero());
630}
631
632llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
633 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000634 assert(MD->isInstance() && "Member function must not be static!");
635 MD = MD->getCanonicalDecl();
636
637 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000638
639 // Get the function pointer (or index if this is a virtual function).
640 llvm::Constant *MemPtr[2];
641 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000642 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000643
Ken Dyckdf016282011-04-09 01:30:02 +0000644 const ASTContext &Context = getContext();
645 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000646 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000647 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000648
Mark Seabornedf0d382013-07-24 16:25:13 +0000649 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000650 // ARM C++ ABI 3.2.1:
651 // This ABI specifies that adj contains twice the this
652 // adjustment, plus 1 if the member function is virtual. The
653 // least significant bit of adj then makes exactly the same
654 // discrimination as the least significant bit of ptr does for
655 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000656 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
657 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000658 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000659 } else {
660 // Itanium C++ ABI 2.3:
661 // For a virtual function, [the pointer field] is 1 plus the
662 // virtual table offset (in bytes) of the function,
663 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000664 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
665 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000666 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000667 }
668 } else {
John McCall2979fe02011-04-12 00:42:48 +0000669 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000670 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000671 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000672 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000673 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000674 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000675 } else {
John McCall2979fe02011-04-12 00:42:48 +0000676 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
677 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000678 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000679 }
John McCall2979fe02011-04-12 00:42:48 +0000680 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000681
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000682 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000683 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
684 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000685 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000686 }
John McCall1c456c82010-08-22 06:43:33 +0000687
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000688 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000689}
690
Richard Smithdafff942012-01-14 04:30:29 +0000691llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
692 QualType MPType) {
693 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
694 const ValueDecl *MPD = MP.getMemberPointerDecl();
695 if (!MPD)
696 return EmitNullMemberPointer(MPT);
697
Reid Kleckner452abac2013-05-09 21:01:17 +0000698 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000699
700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
701 return BuildMemberPointer(MD, ThisAdjustment);
702
703 CharUnits FieldOffset =
704 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
705 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
706}
707
John McCall131d97d2010-08-22 08:30:07 +0000708/// The comparison algorithm is pretty easy: the member pointers are
709/// the same if they're either bitwise identical *or* both null.
710///
711/// ARM is different here only because null-ness is more complicated.
712llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000713ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
714 llvm::Value *L,
715 llvm::Value *R,
716 const MemberPointerType *MPT,
717 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000718 CGBuilderTy &Builder = CGF.Builder;
719
John McCall131d97d2010-08-22 08:30:07 +0000720 llvm::ICmpInst::Predicate Eq;
721 llvm::Instruction::BinaryOps And, Or;
722 if (Inequality) {
723 Eq = llvm::ICmpInst::ICMP_NE;
724 And = llvm::Instruction::Or;
725 Or = llvm::Instruction::And;
726 } else {
727 Eq = llvm::ICmpInst::ICMP_EQ;
728 And = llvm::Instruction::And;
729 Or = llvm::Instruction::Or;
730 }
731
John McCall7a9aac22010-08-23 01:21:21 +0000732 // Member data pointers are easy because there's a unique null
733 // value, so it just comes down to bitwise equality.
734 if (MPT->isMemberDataPointer())
735 return Builder.CreateICmp(Eq, L, R);
736
737 // For member function pointers, the tautologies are more complex.
738 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000739 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000740 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000741 // (L == R) <==> (L.ptr == R.ptr &&
742 // (L.adj == R.adj ||
743 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000744 // The inequality tautologies have exactly the same structure, except
745 // applying De Morgan's laws.
746
747 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
748 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
749
John McCall131d97d2010-08-22 08:30:07 +0000750 // This condition tests whether L.ptr == R.ptr. This must always be
751 // true for equality to hold.
752 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
753
754 // This condition, together with the assumption that L.ptr == R.ptr,
755 // tests whether the pointers are both null. ARM imposes an extra
756 // condition.
757 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
758 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
759
760 // This condition tests whether L.adj == R.adj. If this isn't
761 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000762 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
763 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000764 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
765
766 // Null member function pointers on ARM clear the low bit of Adj,
767 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000768 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000769 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
770
771 // Compute (l.adj | r.adj) & 1 and test it against zero.
772 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
773 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
774 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
775 "cmp.or.adj");
776 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
777 }
778
779 // Tie together all our conditions.
780 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
781 Result = Builder.CreateBinOp(And, PtrEq, Result,
782 Inequality ? "memptr.ne" : "memptr.eq");
783 return Result;
784}
785
786llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000787ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
788 llvm::Value *MemPtr,
789 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000790 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000791
792 /// For member data pointers, this is just a check against -1.
793 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000794 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000795 llvm::Value *NegativeOne =
796 llvm::Constant::getAllOnesValue(MemPtr->getType());
797 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
798 }
John McCall131d97d2010-08-22 08:30:07 +0000799
Daniel Dunbar914bc412011-04-19 23:10:47 +0000800 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000801 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000802
803 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
804 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
805
Daniel Dunbar914bc412011-04-19 23:10:47 +0000806 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
807 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000808 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000809 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000810 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000811 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000812 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
813 "memptr.isvirtual");
814 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000815 }
816
817 return Result;
818}
John McCall1c456c82010-08-22 06:43:33 +0000819
Reid Kleckner40ca9132014-05-13 22:05:45 +0000820bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
821 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
822 if (!RD)
823 return false;
824
Reid Klecknerd355ca72014-05-15 01:26:32 +0000825 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
826 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
827 // special members.
828 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000829 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
830 return true;
831 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000832 return false;
833}
834
John McCall614dbdc2010-08-22 21:01:12 +0000835/// The Itanium ABI requires non-zero initialization only for data
836/// member pointers, for which '0' is a valid offset.
837bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
838 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000839}
John McCall5d865c322010-08-31 07:33:07 +0000840
John McCall82fb8922012-09-25 10:10:39 +0000841/// The Itanium ABI always places an offset to the complete object
842/// at entry -2 in the vtable.
843llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
844 llvm::Value *ptr,
845 QualType type) {
846 // Grab the vtable pointer as an intptr_t*.
847 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
848
849 // Track back to entry -2 and pull out the offset there.
850 llvm::Value *offsetPtr =
851 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
852 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
853 offset->setAlignment(CGF.PointerAlignInBytes);
854
855 // Apply the offset.
856 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
857 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
858}
859
David Majnemer1162d252014-06-22 19:05:33 +0000860static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
861 // void *__dynamic_cast(const void *sub,
862 // const abi::__class_type_info *src,
863 // const abi::__class_type_info *dst,
864 // std::ptrdiff_t src2dst_offset);
865
866 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
867 llvm::Type *PtrDiffTy =
868 CGF.ConvertType(CGF.getContext().getPointerDiffType());
869
870 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
871
872 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
873
874 // Mark the function as nounwind readonly.
875 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
876 llvm::Attribute::ReadOnly };
877 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
878 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
879
880 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
881}
882
883static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
884 // void __cxa_bad_cast();
885 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
886 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
887}
888
889/// \brief Compute the src2dst_offset hint as described in the
890/// Itanium C++ ABI [2.9.7]
891static CharUnits computeOffsetHint(ASTContext &Context,
892 const CXXRecordDecl *Src,
893 const CXXRecordDecl *Dst) {
894 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
895 /*DetectVirtual=*/false);
896
897 // If Dst is not derived from Src we can skip the whole computation below and
898 // return that Src is not a public base of Dst. Record all inheritance paths.
899 if (!Dst->isDerivedFrom(Src, Paths))
900 return CharUnits::fromQuantity(-2ULL);
901
902 unsigned NumPublicPaths = 0;
903 CharUnits Offset;
904
905 // Now walk all possible inheritance paths.
906 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
907 ++I) {
908 if (I->Access != AS_public) // Ignore non-public inheritance.
909 continue;
910
911 ++NumPublicPaths;
912
913 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
914 // If the path contains a virtual base class we can't give any hint.
915 // -1: no hint.
916 if (J->Base->isVirtual())
917 return CharUnits::fromQuantity(-1ULL);
918
919 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
920 continue;
921
922 // Accumulate the base class offsets.
923 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
924 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
925 }
926 }
927
928 // -2: Src is not a public base of Dst.
929 if (NumPublicPaths == 0)
930 return CharUnits::fromQuantity(-2ULL);
931
932 // -3: Src is a multiple public base type but never a virtual base type.
933 if (NumPublicPaths > 1)
934 return CharUnits::fromQuantity(-3ULL);
935
936 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
937 // Return the offset of Src from the origin of Dst.
938 return Offset;
939}
940
941static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
942 // void __cxa_bad_typeid();
943 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
944
945 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
946}
947
948bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
949 QualType SrcRecordTy) {
950 return IsDeref;
951}
952
953void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
954 llvm::Value *Fn = getBadTypeidFn(CGF);
955 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
956 CGF.Builder.CreateUnreachable();
957}
958
959llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
960 QualType SrcRecordTy,
961 llvm::Value *ThisPtr,
962 llvm::Type *StdTypeInfoPtrTy) {
963 llvm::Value *Value =
964 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
965
966 // Load the type info.
967 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
968 return CGF.Builder.CreateLoad(Value);
969}
970
971bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
972 QualType SrcRecordTy) {
973 return SrcIsPtr;
974}
975
976llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
977 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
978 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
979 llvm::Type *PtrDiffLTy =
980 CGF.ConvertType(CGF.getContext().getPointerDiffType());
981 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
982
983 llvm::Value *SrcRTTI =
984 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
985 llvm::Value *DestRTTI =
986 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
987
988 // Compute the offset hint.
989 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
990 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
991 llvm::Value *OffsetHint = llvm::ConstantInt::get(
992 PtrDiffLTy,
993 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
994
995 // Emit the call to __dynamic_cast.
996 Value = CGF.EmitCastToVoidPtr(Value);
997
998 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
999 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1000 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1001
1002 /// C++ [expr.dynamic.cast]p9:
1003 /// A failed cast to reference type throws std::bad_cast
1004 if (DestTy->isReferenceType()) {
1005 llvm::BasicBlock *BadCastBlock =
1006 CGF.createBasicBlock("dynamic_cast.bad_cast");
1007
1008 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1009 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1010
1011 CGF.EmitBlock(BadCastBlock);
1012 EmitBadCastCall(CGF);
1013 }
1014
1015 return Value;
1016}
1017
1018llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1019 llvm::Value *Value,
1020 QualType SrcRecordTy,
1021 QualType DestTy) {
1022 llvm::Type *PtrDiffLTy =
1023 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1024 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1025
1026 // Get the vtable pointer.
1027 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1028
1029 // Get the offset-to-top from the vtable.
1030 llvm::Value *OffsetToTop =
1031 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1032 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1033
1034 // Finally, add the offset to the pointer.
1035 Value = CGF.EmitCastToVoidPtr(Value);
1036 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1037
1038 return CGF.Builder.CreateBitCast(Value, DestLTy);
1039}
1040
1041bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1042 llvm::Value *Fn = getBadCastFn(CGF);
1043 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1044 CGF.Builder.CreateUnreachable();
1045 return true;
1046}
1047
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001048llvm::Value *
1049ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1050 llvm::Value *This,
1051 const CXXRecordDecl *ClassDecl,
1052 const CXXRecordDecl *BaseClassDecl) {
1053 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1054 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001055 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1056 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001057
1058 llvm::Value *VBaseOffsetPtr =
1059 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1060 "vbase.offset.ptr");
1061 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1062 CGM.PtrDiffTy->getPointerTo());
1063
1064 llvm::Value *VBaseOffset =
1065 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1066
1067 return VBaseOffset;
1068}
1069
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001070void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1071 // Just make sure we're in sync with TargetCXXABI.
1072 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1073
Rafael Espindolac3cde362013-12-09 14:51:17 +00001074 // The constructor used for constructing this as a base class;
1075 // ignores virtual bases.
1076 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1077
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001078 // The constructor used for constructing this as a complete class;
1079 // constucts the virtual bases, then calls the base constructor.
1080 if (!D->getParent()->isAbstract()) {
1081 // We don't need to emit the complete ctor if the class is abstract.
1082 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1083 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001084}
1085
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001086void
1087ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1088 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001089 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001090
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001091 // All parameters are already in place except VTT, which goes after 'this'.
1092 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001093
1094 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001095 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1096 ArgTys.insert(ArgTys.begin() + 1,
1097 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001098}
1099
Reid Klecknere7de47e2013-07-22 13:51:44 +00001100void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001101 // The destructor used for destructing this as a base class; ignores
1102 // virtual bases.
1103 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001104
1105 // The destructor used for destructing this as a most-derived class;
1106 // call the base destructor and then destructs any virtual bases.
1107 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1108
Rafael Espindolac3cde362013-12-09 14:51:17 +00001109 // The destructor in a virtual table is always a 'deleting'
1110 // destructor, which calls the complete destructor and then uses the
1111 // appropriate operator delete.
1112 if (D->isVirtual())
1113 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001114}
1115
Reid Kleckner89077a12013-12-17 19:46:40 +00001116void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1117 QualType &ResTy,
1118 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001119 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001120 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001121
1122 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001123 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001124 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001125
1126 // FIXME: avoid the fake decl
1127 QualType T = Context.getPointerType(Context.VoidPtrTy);
1128 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001129 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001130 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001131 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001132 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001133 }
1134}
1135
John McCall5d865c322010-08-31 07:33:07 +00001136void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1137 /// Initialize the 'this' slot.
1138 EmitThisParam(CGF);
1139
1140 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001141 if (getStructorImplicitParamDecl(CGF)) {
1142 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1143 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001144 }
John McCall5d865c322010-08-31 07:33:07 +00001145
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001146 /// If this is a function that the ABI specifies returns 'this', initialize
1147 /// the return slot to 'this' at the start of the function.
1148 ///
1149 /// Unlike the setting of return types, this is done within the ABI
1150 /// implementation instead of by clients of CGCXXABI because:
1151 /// 1) getThisValue is currently protected
1152 /// 2) in theory, an ABI could implement 'this' returns some other way;
1153 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001154 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001155 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001156}
1157
Reid Kleckner89077a12013-12-17 19:46:40 +00001158unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1159 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1160 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1161 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1162 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001163
Reid Kleckner89077a12013-12-17 19:46:40 +00001164 // Insert the implicit 'vtt' argument as the second argument.
1165 llvm::Value *VTT =
1166 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1167 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1168 Args.insert(Args.begin() + 1,
1169 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1170 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001171}
1172
1173void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1174 const CXXDestructorDecl *DD,
1175 CXXDtorType Type, bool ForVirtualBase,
1176 bool Delegating, llvm::Value *This) {
1177 GlobalDecl GD(DD, Type);
1178 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1179 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1180
Craig Topper8a13c412014-05-21 05:09:00 +00001181 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001182 if (getContext().getLangOpts().AppleKext)
1183 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1184
1185 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001186 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001187
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001188 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1189 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001190}
1191
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001192void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1193 const CXXRecordDecl *RD) {
1194 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1195 if (VTable->hasInitializer())
1196 return;
1197
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001198 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001199 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1200 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001201 llvm::Constant *RTTI =
1202 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001203
1204 // Create and set the initializer.
1205 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1206 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001207 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001208 VTable->setInitializer(Init);
1209
1210 // Set the correct linkage.
1211 VTable->setLinkage(Linkage);
1212
1213 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001214 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001215
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001216 // Use pointer alignment for the vtable. Otherwise we would align them based
1217 // on the size of the initializer which doesn't make sense as only single
1218 // values are read.
1219 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1220 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1221
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001222 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1223 // we will emit the typeinfo for the fundamental types. This is the
1224 // same behaviour as GCC.
1225 const DeclContext *DC = RD->getDeclContext();
1226 if (RD->getIdentifier() &&
1227 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1228 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1229 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1230 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001231 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001232}
1233
1234llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1235 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1236 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1237 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1238 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1239
1240 llvm::Value *VTableAddressPoint;
1241 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1242 // Get the secondary vpointer index.
1243 uint64_t VirtualPointerIndex =
1244 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1245
1246 /// Load the VTT.
1247 llvm::Value *VTT = CGF.LoadCXXVTT();
1248 if (VirtualPointerIndex)
1249 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1250
1251 // And load the address point from the VTT.
1252 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1253 } else {
1254 llvm::Constant *VTable =
1255 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001256 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1257 .getVTableLayout(VTableClass)
1258 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001259 VTableAddressPoint =
1260 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1261 }
1262
1263 return VTableAddressPoint;
1264}
1265
1266llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1267 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1268 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1269
1270 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001271 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1272 .getVTableLayout(VTableClass)
1273 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001274 llvm::Value *Indices[] = {
1275 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1276 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1277 };
1278
1279 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1280}
1281
1282llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1283 CharUnits VPtrOffset) {
1284 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1285
1286 llvm::GlobalVariable *&VTable = VTables[RD];
1287 if (VTable)
1288 return VTable;
1289
1290 // Queue up this v-table for possible deferred emission.
1291 CGM.addDeferredVTable(RD);
1292
1293 SmallString<256> OutName;
1294 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001295 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001296 Out.flush();
1297 StringRef Name = OutName.str();
1298
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001299 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001300 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1301 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1302
1303 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1304 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1305 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001306
1307 if (RD->hasAttr<DLLImportAttr>())
1308 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1309 else if (RD->hasAttr<DLLExportAttr>())
1310 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1311
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001312 return VTable;
1313}
1314
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001315llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1316 GlobalDecl GD,
1317 llvm::Value *This,
1318 llvm::Type *Ty) {
1319 GD = GD.getCanonicalDecl();
1320 Ty = Ty->getPointerTo()->getPointerTo();
1321 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1322
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001323 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001324 llvm::Value *VFuncPtr =
1325 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1326 return CGF.Builder.CreateLoad(VFuncPtr);
1327}
1328
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001329void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1330 const CXXDestructorDecl *Dtor,
1331 CXXDtorType DtorType,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001332 llvm::Value *This,
1333 const CXXMemberCallExpr *CE) {
1334 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001335 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1336
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001337 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1338 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001339 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001340 llvm::Value *Callee =
1341 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001342
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001343 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1344 /*ImplicitParam=*/nullptr, QualType(), CE);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001345}
1346
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001347void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001348 CodeGenVTables &VTables = CGM.getVTables();
1349 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001350 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001351}
1352
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001353static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1354 llvm::Value *Ptr,
1355 int64_t NonVirtualAdjustment,
1356 int64_t VirtualAdjustment,
1357 bool IsReturnAdjustment) {
1358 if (!NonVirtualAdjustment && !VirtualAdjustment)
1359 return Ptr;
1360
1361 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1362 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1363
1364 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1365 // Perform the non-virtual adjustment for a base-to-derived cast.
1366 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1367 }
1368
1369 if (VirtualAdjustment) {
1370 llvm::Type *PtrDiffTy =
1371 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1372
1373 // Perform the virtual adjustment.
1374 llvm::Value *VTablePtrPtr =
1375 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1376
1377 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1378
1379 llvm::Value *OffsetPtr =
1380 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1381
1382 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1383
1384 // Load the adjustment offset from the vtable.
1385 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1386
1387 // Adjust our pointer.
1388 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1389 }
1390
1391 if (NonVirtualAdjustment && IsReturnAdjustment) {
1392 // Perform the non-virtual adjustment for a derived-to-base cast.
1393 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1394 }
1395
1396 // Cast back to the original type.
1397 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1398}
1399
1400llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1401 llvm::Value *This,
1402 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001403 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1404 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001405 /*IsReturnAdjustment=*/false);
1406}
1407
1408llvm::Value *
1409ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1410 const ReturnAdjustment &RA) {
1411 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1412 RA.Virtual.Itanium.VBaseOffsetOffset,
1413 /*IsReturnAdjustment=*/true);
1414}
1415
John McCall5d865c322010-08-31 07:33:07 +00001416void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1417 RValue RV, QualType ResultType) {
1418 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1419 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1420
1421 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001422 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001423 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1424 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1425 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1426}
John McCall8ed55a52010-09-02 09:58:18 +00001427
1428/************************** Array allocation cookies **************************/
1429
John McCallb91cd662012-05-01 05:23:51 +00001430CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1431 // The array cookie is a size_t; pad that up to the element alignment.
1432 // The cookie is actually right-justified in that space.
1433 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1434 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001435}
1436
1437llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1438 llvm::Value *NewPtr,
1439 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001440 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001441 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001442 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001443
Micah Villmowea2fea22012-10-25 15:39:14 +00001444 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001445
John McCall9bca9232010-09-02 10:25:57 +00001446 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001447 QualType SizeTy = Ctx.getSizeType();
1448 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1449
1450 // The size of the cookie.
1451 CharUnits CookieSize =
1452 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001453 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001454
1455 // Compute an offset to the cookie.
1456 llvm::Value *CookiePtr = NewPtr;
1457 CharUnits CookieOffset = CookieSize - SizeSize;
1458 if (!CookieOffset.isZero())
1459 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1460 CookieOffset.getQuantity());
1461
1462 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001463 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1464 llvm::Value *NumElementsPtr =
1465 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1466 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001467 if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001468 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001469 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001470 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1471 llvm::FunctionType *FTy =
1472 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1473 llvm::Constant *F =
1474 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1475 CGF.Builder.CreateCall(F, NumElementsPtr);
1476 }
John McCall8ed55a52010-09-02 09:58:18 +00001477
1478 // Finally, compute a pointer to the actual data buffer by skipping
1479 // over the cookie completely.
1480 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1481 CookieSize.getQuantity());
1482}
1483
John McCallb91cd662012-05-01 05:23:51 +00001484llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1485 llvm::Value *allocPtr,
1486 CharUnits cookieSize) {
1487 // The element size is right-justified in the cookie.
1488 llvm::Value *numElementsPtr = allocPtr;
1489 CharUnits numElementsOffset =
1490 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1491 if (!numElementsOffset.isZero())
1492 numElementsPtr =
1493 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1494 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001495
Micah Villmowea2fea22012-10-25 15:39:14 +00001496 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001497 numElementsPtr =
1498 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001499 if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1500 return CGF.Builder.CreateLoad(numElementsPtr);
1501 // In asan mode emit a function call instead of a regular load and let the
1502 // run-time deal with it: if the shadow is properly poisoned return the
1503 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1504 // We can't simply ignore this load using nosanitize metadata because
1505 // the metadata may be lost.
1506 llvm::FunctionType *FTy =
1507 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1508 llvm::Constant *F =
1509 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1510 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001511}
1512
John McCallb91cd662012-05-01 05:23:51 +00001513CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001514 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001515 // struct array_cookie {
1516 // std::size_t element_size; // element_size != 0
1517 // std::size_t element_count;
1518 // };
John McCallc19c7062013-01-25 23:36:19 +00001519 // But the base ABI doesn't give anything an alignment greater than
1520 // 8, so we can dismiss this as typical ABI-author blindness to
1521 // actual language complexity and round up to the element alignment.
1522 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1523 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001524}
1525
1526llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001527 llvm::Value *newPtr,
1528 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001529 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001530 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001531 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001532
John McCallc19c7062013-01-25 23:36:19 +00001533 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1534 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001535
1536 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001537 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001538
1539 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001540 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1541 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1542 getContext().getTypeSizeInChars(elementType).getQuantity());
1543 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001544
1545 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001546 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1547 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001548
1549 // Finally, compute a pointer to the actual data buffer by skipping
1550 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001551 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1552 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1553 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001554}
1555
John McCallb91cd662012-05-01 05:23:51 +00001556llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1557 llvm::Value *allocPtr,
1558 CharUnits cookieSize) {
1559 // The number of elements is at offset sizeof(size_t) relative to
1560 // the allocated pointer.
1561 llvm::Value *numElementsPtr
1562 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001563
Micah Villmowea2fea22012-10-25 15:39:14 +00001564 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001565 numElementsPtr =
1566 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1567 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001568}
1569
John McCall68ff0372010-09-08 01:44:27 +00001570/*********************** Static local initialization **************************/
1571
1572static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001573 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001574 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001575 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001576 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001577 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001578 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001579 llvm::AttributeSet::get(CGM.getLLVMContext(),
1580 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001581 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001582}
1583
1584static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001585 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001586 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001587 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001588 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001589 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001590 llvm::AttributeSet::get(CGM.getLLVMContext(),
1591 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001592 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001593}
1594
1595static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001596 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001597 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001598 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001599 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001600 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001601 llvm::AttributeSet::get(CGM.getLLVMContext(),
1602 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001603 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001604}
1605
1606namespace {
1607 struct CallGuardAbort : EHScopeStack::Cleanup {
1608 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001609 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001610
Craig Topper4f12f102014-03-12 06:41:41 +00001611 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001612 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1613 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001614 }
1615 };
1616}
1617
1618/// The ARM code here follows the Itanium code closely enough that we
1619/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001620void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1621 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001622 llvm::GlobalVariable *var,
1623 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001624 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001625
Richard Smithdbf74ba2013-04-14 23:01:42 +00001626 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001627 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001628 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1629 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001630
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001631 // If we have a global variable with internal linkage and thread-safe statics
1632 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001633 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1634
1635 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001636 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001637 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001638 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001639 // Guard variables are 64 bits in the generic ABI and size width on ARM
1640 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001641 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001642 }
John McCallb88a5662012-03-30 21:00:39 +00001643 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001644
John McCallb88a5662012-03-30 21:00:39 +00001645 // Create the guard variable if we don't already have it (as we
1646 // might if we're double-emitting this function body).
1647 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1648 if (!guard) {
1649 // Mangle the name for the guard.
1650 SmallString<256> guardName;
1651 {
1652 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001653 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001654 out.flush();
1655 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001656
John McCallb88a5662012-03-30 21:00:39 +00001657 // Create the guard variable with a zero-initializer.
1658 // Just absorb linkage and visibility from the guarded variable.
1659 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1660 false, var->getLinkage(),
1661 llvm::ConstantInt::get(guardTy, 0),
1662 guardName.str());
1663 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001664 // If the variable is thread-local, so is its guard variable.
1665 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001666
1667 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1668 }
John McCall87590e62012-03-30 07:09:50 +00001669
John McCall68ff0372010-09-08 01:44:27 +00001670 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001671 //
John McCall68ff0372010-09-08 01:44:27 +00001672 // Itanium C++ ABI 3.3.2:
1673 // The following is pseudo-code showing how these functions can be used:
1674 // if (obj_guard.first_byte == 0) {
1675 // if ( __cxa_guard_acquire (&obj_guard) ) {
1676 // try {
1677 // ... initialize the object ...;
1678 // } catch (...) {
1679 // __cxa_guard_abort (&obj_guard);
1680 // throw;
1681 // }
1682 // ... queue object destructor with __cxa_atexit() ...;
1683 // __cxa_guard_release (&obj_guard);
1684 // }
1685 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001686
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001687 // Load the first byte of the guard variable.
1688 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001689 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001690 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001691
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001692 // Itanium ABI:
1693 // An implementation supporting thread-safety on multiprocessor
1694 // systems must also guarantee that references to the initialized
1695 // object do not occur before the load of the initialization flag.
1696 //
1697 // In LLVM, we do this by marking the load Acquire.
1698 if (threadsafe)
1699 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001700
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001701 // For ARM, we should only check the first bit, rather than the entire byte:
1702 //
1703 // ARM C++ ABI 3.2.3.1:
1704 // To support the potential use of initialization guard variables
1705 // as semaphores that are the target of ARM SWP and LDREX/STREX
1706 // synchronizing instructions we define a static initialization
1707 // guard variable to be a 4-byte aligned, 4-byte word with the
1708 // following inline access protocol.
1709 // #define INITIALIZED 1
1710 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1711 // if (__cxa_guard_acquire(&obj_guard))
1712 // ...
1713 // }
1714 //
1715 // and similarly for ARM64:
1716 //
1717 // ARM64 C++ ABI 3.2.2:
1718 // This ABI instead only specifies the value bit 0 of the static guard
1719 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1720 // variable is not initialized and 1 when it is.
1721 llvm::Value *V =
1722 (UseARMGuardVarABI && !useInt8GuardVariable)
1723 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1724 : LI;
1725 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001726
1727 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1728 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1729
1730 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001731 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001732
1733 CGF.EmitBlock(InitCheckBlock);
1734
1735 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001736 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001737 // Call __cxa_guard_acquire.
1738 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001739 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001740
1741 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1742
1743 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1744 InitBlock, EndBlock);
1745
1746 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001747 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001748
1749 CGF.EmitBlock(InitBlock);
1750 }
1751
1752 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001753 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001754
John McCall5aa52592011-06-17 07:33:57 +00001755 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001756 // Pop the guard-abort cleanup if we pushed one.
1757 CGF.PopCleanupBlock();
1758
1759 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001760 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001761 } else {
John McCallb88a5662012-03-30 21:00:39 +00001762 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001763 }
1764
1765 CGF.EmitBlock(EndBlock);
1766}
John McCallc84ed6a2012-05-01 06:13:13 +00001767
1768/// Register a global destructor using __cxa_atexit.
1769static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1770 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001771 llvm::Constant *addr,
1772 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001773 const char *Name = "__cxa_atexit";
1774 if (TLS) {
1775 const llvm::Triple &T = CGF.getTarget().getTriple();
1776 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1777 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001778
John McCallc84ed6a2012-05-01 06:13:13 +00001779 // We're assuming that the destructor function is something we can
1780 // reasonably call with the default CC. Go ahead and cast it to the
1781 // right prototype.
1782 llvm::Type *dtorTy =
1783 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1784
1785 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1786 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1787 llvm::FunctionType *atexitTy =
1788 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1789
1790 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001791 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001792 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1793 fn->setDoesNotThrow();
1794
1795 // Create a variable that binds the atexit to this shared object.
1796 llvm::Constant *handle =
1797 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1798
1799 llvm::Value *args[] = {
1800 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1801 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1802 handle
1803 };
John McCall882987f2013-02-28 19:01:20 +00001804 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001805}
1806
1807/// Register a global destructor as best as we know how.
1808void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001809 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001810 llvm::Constant *dtor,
1811 llvm::Constant *addr) {
1812 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001813 if (CGM.getCodeGenOpts().CXAAtExit)
1814 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1815
1816 if (D.getTLSKind())
1817 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001818
1819 // In Apple kexts, we want to add a global destructor entry.
1820 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001821 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001822 // Generate a global destructor entry.
1823 return CGM.AddCXXDtorEntry(dtor, addr);
1824 }
1825
David Blaikieebe87e12013-08-27 23:57:18 +00001826 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001827}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001828
David Majnemer9b21c332014-07-11 20:28:10 +00001829static bool isThreadWrapperReplaceable(const VarDecl *VD,
1830 CodeGen::CodeGenModule &CGM) {
1831 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1832 // OS X prefers to have references to thread local variables to go through
1833 // the thread wrapper instead of directly referencing the backing variable.
1834 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1835 CGM.getTarget().getTriple().isMacOSX();
1836}
1837
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001838/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001839/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001840/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001841static llvm::GlobalValue::LinkageTypes
1842getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1843 llvm::GlobalValue::LinkageTypes VarLinkage =
1844 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1845
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001846 // For internal linkage variables, we don't need an external or weak wrapper.
1847 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1848 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001849
David Majnemer9b21c332014-07-11 20:28:10 +00001850 // If the thread wrapper is replaceable, give it appropriate linkage.
1851 if (isThreadWrapperReplaceable(VD, CGM)) {
1852 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1853 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1854 return llvm::GlobalVariable::WeakAnyLinkage;
1855 return VarLinkage;
1856 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001857 return llvm::GlobalValue::WeakODRLinkage;
1858}
1859
1860llvm::Function *
1861ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1862 llvm::GlobalVariable *Var) {
1863 // Mangle the name for the thread_local wrapper function.
1864 SmallString<256> WrapperName;
1865 {
1866 llvm::raw_svector_ostream Out(WrapperName);
1867 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1868 Out.flush();
1869 }
1870
1871 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1872 return cast<llvm::Function>(V);
1873
1874 llvm::Type *RetTy = Var->getType();
1875 if (VD->getType()->isReferenceType())
1876 RetTy = RetTy->getPointerElementType();
1877
1878 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001879 llvm::Function *Wrapper =
1880 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1881 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001882 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001883 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001884 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001885 return Wrapper;
1886}
1887
1888void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +00001889 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001890 llvm::Function *InitFunc) {
1891 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1892 const VarDecl *VD = Decls[I].first;
1893 llvm::GlobalVariable *Var = Decls[I].second;
1894
David Majnemer9b21c332014-07-11 20:28:10 +00001895 // Some targets require that all access to thread local variables go through
1896 // the thread wrapper. This means that we cannot attempt to create a thread
1897 // wrapper or a thread helper.
1898 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1899 continue;
1900
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001901 // Mangle the name for the thread_local initialization function.
1902 SmallString<256> InitFnName;
1903 {
1904 llvm::raw_svector_ostream Out(InitFnName);
1905 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1906 Out.flush();
1907 }
1908
1909 // If we have a definition for the variable, emit the initialization
1910 // function as an alias to the global Init function (if any). Otherwise,
1911 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001912 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001913 bool InitIsInitFunc = false;
1914 if (VD->hasDefinition()) {
1915 InitIsInitFunc = true;
1916 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001917 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1918 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001919 } else {
1920 // Emit a weak global function referring to the initialization function.
1921 // This function will not exist if the TU defining the thread_local
1922 // variable in question does not need any dynamic initialization for
1923 // its thread_local variables.
1924 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1925 Init = llvm::Function::Create(
1926 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1927 &CGM.getModule());
1928 }
1929
1930 if (Init)
1931 Init->setVisibility(Var->getVisibility());
1932
1933 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1934 llvm::LLVMContext &Context = CGM.getModule().getContext();
1935 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1936 CGBuilderTy Builder(Entry);
1937 if (InitIsInitFunc) {
1938 if (Init)
1939 Builder.CreateCall(Init);
1940 } else {
1941 // Don't know whether we have an init function. Call it if it exists.
1942 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1943 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1944 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1945 Builder.CreateCondBr(Have, InitBB, ExitBB);
1946
1947 Builder.SetInsertPoint(InitBB);
1948 Builder.CreateCall(Init);
1949 Builder.CreateBr(ExitBB);
1950
1951 Builder.SetInsertPoint(ExitBB);
1952 }
1953
1954 // For a reference, the result of the wrapper function is a pointer to
1955 // the referenced object.
1956 llvm::Value *Val = Var;
1957 if (VD->getType()->isReferenceType()) {
1958 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1959 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1960 Val = LI;
1961 }
1962
1963 Builder.CreateRet(Val);
1964 }
1965}
1966
Richard Smith0f383742014-03-26 22:48:22 +00001967LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1968 const VarDecl *VD,
1969 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001970 QualType T = VD->getType();
1971 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1972 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1973 llvm::Function *Wrapper =
1974 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1975
1976 Val = CGF.Builder.CreateCall(Wrapper);
1977
1978 LValue LV;
1979 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001980 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001981 else
Richard Smith0f383742014-03-26 22:48:22 +00001982 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001983 // FIXME: need setObjCGCLValueClass?
1984 return LV;
1985}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001986
1987/// Return whether the given global decl needs a VTT parameter, which it does
1988/// if it's a base constructor or destructor with virtual bases.
1989bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1990 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1991
1992 // We don't have any virtual bases, just return early.
1993 if (!MD->getParent()->getNumVBases())
1994 return false;
1995
1996 // Check if we have a base constructor.
1997 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1998 return true;
1999
2000 // Check if we have a base destructor.
2001 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2002 return true;
2003
2004 return false;
2005}
David Majnemere2cb8d12014-07-07 06:20:47 +00002006
2007namespace {
2008class ItaniumRTTIBuilder {
2009 CodeGenModule &CGM; // Per-module state.
2010 llvm::LLVMContext &VMContext;
2011 const ItaniumCXXABI &CXXABI; // Per-module state.
2012
2013 /// Fields - The fields of the RTTI descriptor currently being built.
2014 SmallVector<llvm::Constant *, 16> Fields;
2015
2016 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2017 llvm::GlobalVariable *
2018 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2019
2020 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2021 /// descriptor of the given type.
2022 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2023
2024 /// BuildVTablePointer - Build the vtable pointer for the given type.
2025 void BuildVTablePointer(const Type *Ty);
2026
2027 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2028 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2029 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2030
2031 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2032 /// classes with bases that do not satisfy the abi::__si_class_type_info
2033 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2034 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2035
2036 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2037 /// for pointer types.
2038 void BuildPointerTypeInfo(QualType PointeeTy);
2039
2040 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2041 /// type_info for an object type.
2042 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2043
2044 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2045 /// struct, used for member pointer types.
2046 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2047
2048public:
2049 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2050 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2051
2052 // Pointer type info flags.
2053 enum {
2054 /// PTI_Const - Type has const qualifier.
2055 PTI_Const = 0x1,
2056
2057 /// PTI_Volatile - Type has volatile qualifier.
2058 PTI_Volatile = 0x2,
2059
2060 /// PTI_Restrict - Type has restrict qualifier.
2061 PTI_Restrict = 0x4,
2062
2063 /// PTI_Incomplete - Type is incomplete.
2064 PTI_Incomplete = 0x8,
2065
2066 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2067 /// (in pointer to member).
2068 PTI_ContainingClassIncomplete = 0x10
2069 };
2070
2071 // VMI type info flags.
2072 enum {
2073 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2074 VMI_NonDiamondRepeat = 0x1,
2075
2076 /// VMI_DiamondShaped - Class is diamond shaped.
2077 VMI_DiamondShaped = 0x2
2078 };
2079
2080 // Base class type info flags.
2081 enum {
2082 /// BCTI_Virtual - Base class is virtual.
2083 BCTI_Virtual = 0x1,
2084
2085 /// BCTI_Public - Base class is public.
2086 BCTI_Public = 0x2
2087 };
2088
2089 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2090 ///
2091 /// \param Force - true to force the creation of this RTTI value
2092 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2093};
2094}
2095
2096llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2097 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2098 SmallString<256> OutName;
2099 llvm::raw_svector_ostream Out(OutName);
2100 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2101 Out.flush();
2102 StringRef Name = OutName.str();
2103
2104 // We know that the mangled name of the type starts at index 4 of the
2105 // mangled name of the typename, so we can just index into it in order to
2106 // get the mangled name of the type.
2107 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2108 Name.substr(4));
2109
2110 llvm::GlobalVariable *GV =
2111 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2112
2113 GV->setInitializer(Init);
2114
2115 return GV;
2116}
2117
2118llvm::Constant *
2119ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2120 // Mangle the RTTI name.
2121 SmallString<256> OutName;
2122 llvm::raw_svector_ostream Out(OutName);
2123 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2124 Out.flush();
2125 StringRef Name = OutName.str();
2126
2127 // Look for an existing global.
2128 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2129
2130 if (!GV) {
2131 // Create a new global variable.
2132 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2133 /*Constant=*/true,
2134 llvm::GlobalValue::ExternalLinkage, nullptr,
2135 Name);
2136 }
2137
2138 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2139}
2140
2141/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2142/// info for that type is defined in the standard library.
2143static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2144 // Itanium C++ ABI 2.9.2:
2145 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2146 // the run-time support library. Specifically, the run-time support
2147 // library should contain type_info objects for the types X, X* and
2148 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2149 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2150 // long, unsigned long, long long, unsigned long long, float, double,
2151 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2152 // half-precision floating point types.
2153 switch (Ty->getKind()) {
2154 case BuiltinType::Void:
2155 case BuiltinType::NullPtr:
2156 case BuiltinType::Bool:
2157 case BuiltinType::WChar_S:
2158 case BuiltinType::WChar_U:
2159 case BuiltinType::Char_U:
2160 case BuiltinType::Char_S:
2161 case BuiltinType::UChar:
2162 case BuiltinType::SChar:
2163 case BuiltinType::Short:
2164 case BuiltinType::UShort:
2165 case BuiltinType::Int:
2166 case BuiltinType::UInt:
2167 case BuiltinType::Long:
2168 case BuiltinType::ULong:
2169 case BuiltinType::LongLong:
2170 case BuiltinType::ULongLong:
2171 case BuiltinType::Half:
2172 case BuiltinType::Float:
2173 case BuiltinType::Double:
2174 case BuiltinType::LongDouble:
2175 case BuiltinType::Char16:
2176 case BuiltinType::Char32:
2177 case BuiltinType::Int128:
2178 case BuiltinType::UInt128:
2179 case BuiltinType::OCLImage1d:
2180 case BuiltinType::OCLImage1dArray:
2181 case BuiltinType::OCLImage1dBuffer:
2182 case BuiltinType::OCLImage2d:
2183 case BuiltinType::OCLImage2dArray:
2184 case BuiltinType::OCLImage3d:
2185 case BuiltinType::OCLSampler:
2186 case BuiltinType::OCLEvent:
2187 return true;
2188
2189 case BuiltinType::Dependent:
2190#define BUILTIN_TYPE(Id, SingletonId)
2191#define PLACEHOLDER_TYPE(Id, SingletonId) \
2192 case BuiltinType::Id:
2193#include "clang/AST/BuiltinTypes.def"
2194 llvm_unreachable("asking for RRTI for a placeholder type!");
2195
2196 case BuiltinType::ObjCId:
2197 case BuiltinType::ObjCClass:
2198 case BuiltinType::ObjCSel:
2199 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2200 }
2201
2202 llvm_unreachable("Invalid BuiltinType Kind!");
2203}
2204
2205static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2206 QualType PointeeTy = PointerTy->getPointeeType();
2207 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2208 if (!BuiltinTy)
2209 return false;
2210
2211 // Check the qualifiers.
2212 Qualifiers Quals = PointeeTy.getQualifiers();
2213 Quals.removeConst();
2214
2215 if (!Quals.empty())
2216 return false;
2217
2218 return TypeInfoIsInStandardLibrary(BuiltinTy);
2219}
2220
2221/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2222/// information for the given type exists in the standard library.
2223static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2224 // Type info for builtin types is defined in the standard library.
2225 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2226 return TypeInfoIsInStandardLibrary(BuiltinTy);
2227
2228 // Type info for some pointer types to builtin types is defined in the
2229 // standard library.
2230 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2231 return TypeInfoIsInStandardLibrary(PointerTy);
2232
2233 return false;
2234}
2235
2236/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2237/// the given type exists somewhere else, and that we should not emit the type
2238/// information in this translation unit. Assumes that it is not a
2239/// standard-library type.
2240static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2241 QualType Ty) {
2242 ASTContext &Context = CGM.getContext();
2243
2244 // If RTTI is disabled, assume it might be disabled in the
2245 // translation unit that defines any potential key function, too.
2246 if (!Context.getLangOpts().RTTI) return false;
2247
2248 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2249 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2250 if (!RD->hasDefinition())
2251 return false;
2252
2253 if (!RD->isDynamicClass())
2254 return false;
2255
2256 // FIXME: this may need to be reconsidered if the key function
2257 // changes.
2258 return CGM.getVTables().isVTableExternal(RD);
2259 }
2260
2261 return false;
2262}
2263
2264/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2265static bool IsIncompleteClassType(const RecordType *RecordTy) {
2266 return !RecordTy->getDecl()->isCompleteDefinition();
2267}
2268
2269/// ContainsIncompleteClassType - Returns whether the given type contains an
2270/// incomplete class type. This is true if
2271///
2272/// * The given type is an incomplete class type.
2273/// * The given type is a pointer type whose pointee type contains an
2274/// incomplete class type.
2275/// * The given type is a member pointer type whose class is an incomplete
2276/// class type.
2277/// * The given type is a member pointer type whoise pointee type contains an
2278/// incomplete class type.
2279/// is an indirect or direct pointer to an incomplete class type.
2280static bool ContainsIncompleteClassType(QualType Ty) {
2281 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2282 if (IsIncompleteClassType(RecordTy))
2283 return true;
2284 }
2285
2286 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2287 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2288
2289 if (const MemberPointerType *MemberPointerTy =
2290 dyn_cast<MemberPointerType>(Ty)) {
2291 // Check if the class type is incomplete.
2292 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2293 if (IsIncompleteClassType(ClassType))
2294 return true;
2295
2296 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2297 }
2298
2299 return false;
2300}
2301
2302// CanUseSingleInheritance - Return whether the given record decl has a "single,
2303// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2304// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2305static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2306 // Check the number of bases.
2307 if (RD->getNumBases() != 1)
2308 return false;
2309
2310 // Get the base.
2311 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2312
2313 // Check that the base is not virtual.
2314 if (Base->isVirtual())
2315 return false;
2316
2317 // Check that the base is public.
2318 if (Base->getAccessSpecifier() != AS_public)
2319 return false;
2320
2321 // Check that the class is dynamic iff the base is.
2322 const CXXRecordDecl *BaseDecl =
2323 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2324 if (!BaseDecl->isEmpty() &&
2325 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2326 return false;
2327
2328 return true;
2329}
2330
2331void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2332 // abi::__class_type_info.
2333 static const char * const ClassTypeInfo =
2334 "_ZTVN10__cxxabiv117__class_type_infoE";
2335 // abi::__si_class_type_info.
2336 static const char * const SIClassTypeInfo =
2337 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2338 // abi::__vmi_class_type_info.
2339 static const char * const VMIClassTypeInfo =
2340 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2341
2342 const char *VTableName = nullptr;
2343
2344 switch (Ty->getTypeClass()) {
2345#define TYPE(Class, Base)
2346#define ABSTRACT_TYPE(Class, Base)
2347#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2348#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2349#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2350#include "clang/AST/TypeNodes.def"
2351 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2352
2353 case Type::LValueReference:
2354 case Type::RValueReference:
2355 llvm_unreachable("References shouldn't get here");
2356
2357 case Type::Auto:
2358 llvm_unreachable("Undeduced auto type shouldn't get here");
2359
2360 case Type::Builtin:
2361 // GCC treats vector and complex types as fundamental types.
2362 case Type::Vector:
2363 case Type::ExtVector:
2364 case Type::Complex:
2365 case Type::Atomic:
2366 // FIXME: GCC treats block pointers as fundamental types?!
2367 case Type::BlockPointer:
2368 // abi::__fundamental_type_info.
2369 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2370 break;
2371
2372 case Type::ConstantArray:
2373 case Type::IncompleteArray:
2374 case Type::VariableArray:
2375 // abi::__array_type_info.
2376 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2377 break;
2378
2379 case Type::FunctionNoProto:
2380 case Type::FunctionProto:
2381 // abi::__function_type_info.
2382 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2383 break;
2384
2385 case Type::Enum:
2386 // abi::__enum_type_info.
2387 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2388 break;
2389
2390 case Type::Record: {
2391 const CXXRecordDecl *RD =
2392 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2393
2394 if (!RD->hasDefinition() || !RD->getNumBases()) {
2395 VTableName = ClassTypeInfo;
2396 } else if (CanUseSingleInheritance(RD)) {
2397 VTableName = SIClassTypeInfo;
2398 } else {
2399 VTableName = VMIClassTypeInfo;
2400 }
2401
2402 break;
2403 }
2404
2405 case Type::ObjCObject:
2406 // Ignore protocol qualifiers.
2407 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2408
2409 // Handle id and Class.
2410 if (isa<BuiltinType>(Ty)) {
2411 VTableName = ClassTypeInfo;
2412 break;
2413 }
2414
2415 assert(isa<ObjCInterfaceType>(Ty));
2416 // Fall through.
2417
2418 case Type::ObjCInterface:
2419 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2420 VTableName = SIClassTypeInfo;
2421 } else {
2422 VTableName = ClassTypeInfo;
2423 }
2424 break;
2425
2426 case Type::ObjCObjectPointer:
2427 case Type::Pointer:
2428 // abi::__pointer_type_info.
2429 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2430 break;
2431
2432 case Type::MemberPointer:
2433 // abi::__pointer_to_member_type_info.
2434 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2435 break;
2436 }
2437
2438 llvm::Constant *VTable =
2439 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2440
2441 llvm::Type *PtrDiffTy =
2442 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2443
2444 // The vtable address point is 2.
2445 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2446 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2447 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2448
2449 Fields.push_back(VTable);
2450}
2451
2452/// \brief Return the linkage that the type info and type info name constants
2453/// should have for the given type.
2454static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2455 QualType Ty) {
2456 // Itanium C++ ABI 2.9.5p7:
2457 // In addition, it and all of the intermediate abi::__pointer_type_info
2458 // structs in the chain down to the abi::__class_type_info for the
2459 // incomplete class type must be prevented from resolving to the
2460 // corresponding type_info structs for the complete class type, possibly
2461 // by making them local static objects. Finally, a dummy class RTTI is
2462 // generated for the incomplete type that will not resolve to the final
2463 // complete class RTTI (because the latter need not exist), possibly by
2464 // making it a local static object.
2465 if (ContainsIncompleteClassType(Ty))
2466 return llvm::GlobalValue::InternalLinkage;
2467
2468 switch (Ty->getLinkage()) {
2469 case NoLinkage:
2470 case InternalLinkage:
2471 case UniqueExternalLinkage:
2472 return llvm::GlobalValue::InternalLinkage;
2473
2474 case VisibleNoLinkage:
2475 case ExternalLinkage:
2476 if (!CGM.getLangOpts().RTTI) {
2477 // RTTI is not enabled, which means that this type info struct is going
2478 // to be used for exception handling. Give it linkonce_odr linkage.
2479 return llvm::GlobalValue::LinkOnceODRLinkage;
2480 }
2481
2482 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2483 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2484 if (RD->hasAttr<WeakAttr>())
2485 return llvm::GlobalValue::WeakODRLinkage;
2486 if (RD->isDynamicClass())
2487 return CGM.getVTableLinkage(RD);
2488 }
2489
2490 return llvm::GlobalValue::LinkOnceODRLinkage;
2491 }
2492
2493 llvm_unreachable("Invalid linkage!");
2494}
2495
2496llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2497 // We want to operate on the canonical type.
2498 Ty = CGM.getContext().getCanonicalType(Ty);
2499
2500 // Check if we've already emitted an RTTI descriptor for this type.
2501 SmallString<256> OutName;
2502 llvm::raw_svector_ostream Out(OutName);
2503 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2504 Out.flush();
2505 StringRef Name = OutName.str();
2506
2507 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2508 if (OldGV && !OldGV->isDeclaration()) {
2509 assert(!OldGV->hasAvailableExternallyLinkage() &&
2510 "available_externally typeinfos not yet implemented");
2511
2512 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2513 }
2514
2515 // Check if there is already an external RTTI descriptor for this type.
2516 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2517 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2518 return GetAddrOfExternalRTTIDescriptor(Ty);
2519
2520 // Emit the standard library with external linkage.
2521 llvm::GlobalVariable::LinkageTypes Linkage;
2522 if (IsStdLib)
2523 Linkage = llvm::GlobalValue::ExternalLinkage;
2524 else
2525 Linkage = getTypeInfoLinkage(CGM, Ty);
2526
2527 // Add the vtable pointer.
2528 BuildVTablePointer(cast<Type>(Ty));
2529
2530 // And the name.
2531 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2532 llvm::Constant *TypeNameField;
2533
2534 // If we're supposed to demote the visibility, be sure to set a flag
2535 // to use a string comparison for type_info comparisons.
2536 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2537 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2538 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2539 // The flag is the sign bit, which on ARM64 is defined to be clear
2540 // for global pointers. This is very ARM64-specific.
2541 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2542 llvm::Constant *flag =
2543 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2544 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2545 TypeNameField =
2546 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2547 } else {
2548 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2549 }
2550 Fields.push_back(TypeNameField);
2551
2552 switch (Ty->getTypeClass()) {
2553#define TYPE(Class, Base)
2554#define ABSTRACT_TYPE(Class, Base)
2555#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2556#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2557#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2558#include "clang/AST/TypeNodes.def"
2559 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2560
2561 // GCC treats vector types as fundamental types.
2562 case Type::Builtin:
2563 case Type::Vector:
2564 case Type::ExtVector:
2565 case Type::Complex:
2566 case Type::BlockPointer:
2567 // Itanium C++ ABI 2.9.5p4:
2568 // abi::__fundamental_type_info adds no data members to std::type_info.
2569 break;
2570
2571 case Type::LValueReference:
2572 case Type::RValueReference:
2573 llvm_unreachable("References shouldn't get here");
2574
2575 case Type::Auto:
2576 llvm_unreachable("Undeduced auto type shouldn't get here");
2577
2578 case Type::ConstantArray:
2579 case Type::IncompleteArray:
2580 case Type::VariableArray:
2581 // Itanium C++ ABI 2.9.5p5:
2582 // abi::__array_type_info adds no data members to std::type_info.
2583 break;
2584
2585 case Type::FunctionNoProto:
2586 case Type::FunctionProto:
2587 // Itanium C++ ABI 2.9.5p5:
2588 // abi::__function_type_info adds no data members to std::type_info.
2589 break;
2590
2591 case Type::Enum:
2592 // Itanium C++ ABI 2.9.5p5:
2593 // abi::__enum_type_info adds no data members to std::type_info.
2594 break;
2595
2596 case Type::Record: {
2597 const CXXRecordDecl *RD =
2598 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2599 if (!RD->hasDefinition() || !RD->getNumBases()) {
2600 // We don't need to emit any fields.
2601 break;
2602 }
2603
2604 if (CanUseSingleInheritance(RD))
2605 BuildSIClassTypeInfo(RD);
2606 else
2607 BuildVMIClassTypeInfo(RD);
2608
2609 break;
2610 }
2611
2612 case Type::ObjCObject:
2613 case Type::ObjCInterface:
2614 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2615 break;
2616
2617 case Type::ObjCObjectPointer:
2618 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2619 break;
2620
2621 case Type::Pointer:
2622 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2623 break;
2624
2625 case Type::MemberPointer:
2626 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2627 break;
2628
2629 case Type::Atomic:
2630 // No fields, at least for the moment.
2631 break;
2632 }
2633
2634 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2635
2636 llvm::GlobalVariable *GV =
2637 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2638 /*Constant=*/true, Linkage, Init, Name);
2639
2640 // If there's already an old global variable, replace it with the new one.
2641 if (OldGV) {
2642 GV->takeName(OldGV);
2643 llvm::Constant *NewPtr =
2644 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2645 OldGV->replaceAllUsesWith(NewPtr);
2646 OldGV->eraseFromParent();
2647 }
2648
2649 // The Itanium ABI specifies that type_info objects must be globally
2650 // unique, with one exception: if the type is an incomplete class
2651 // type or a (possibly indirect) pointer to one. That exception
2652 // affects the general case of comparing type_info objects produced
2653 // by the typeid operator, which is why the comparison operators on
2654 // std::type_info generally use the type_info name pointers instead
2655 // of the object addresses. However, the language's built-in uses
2656 // of RTTI generally require class types to be complete, even when
2657 // manipulating pointers to those class types. This allows the
2658 // implementation of dynamic_cast to rely on address equality tests,
2659 // which is much faster.
2660
2661 // All of this is to say that it's important that both the type_info
2662 // object and the type_info name be uniqued when weakly emitted.
2663
2664 // Give the type_info object and name the formal visibility of the
2665 // type itself.
2666 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2667 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2668 // If the linkage is local, only default visibility makes sense.
2669 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2670 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2671 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2672 else
2673 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2674 TypeName->setVisibility(llvmVisibility);
2675 GV->setVisibility(llvmVisibility);
2676
2677 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2678}
2679
2680/// ComputeQualifierFlags - Compute the pointer type info flags from the
2681/// given qualifier.
2682static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2683 unsigned Flags = 0;
2684
2685 if (Quals.hasConst())
2686 Flags |= ItaniumRTTIBuilder::PTI_Const;
2687 if (Quals.hasVolatile())
2688 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2689 if (Quals.hasRestrict())
2690 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2691
2692 return Flags;
2693}
2694
2695/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2696/// for the given Objective-C object type.
2697void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2698 // Drop qualifiers.
2699 const Type *T = OT->getBaseType().getTypePtr();
2700 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2701
2702 // The builtin types are abi::__class_type_infos and don't require
2703 // extra fields.
2704 if (isa<BuiltinType>(T)) return;
2705
2706 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2707 ObjCInterfaceDecl *Super = Class->getSuperClass();
2708
2709 // Root classes are also __class_type_info.
2710 if (!Super) return;
2711
2712 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2713
2714 // Everything else is single inheritance.
2715 llvm::Constant *BaseTypeInfo =
2716 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2717 Fields.push_back(BaseTypeInfo);
2718}
2719
2720/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2721/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2722void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2723 // Itanium C++ ABI 2.9.5p6b:
2724 // It adds to abi::__class_type_info a single member pointing to the
2725 // type_info structure for the base type,
2726 llvm::Constant *BaseTypeInfo =
2727 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2728 Fields.push_back(BaseTypeInfo);
2729}
2730
2731namespace {
2732 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2733 /// a class hierarchy.
2734 struct SeenBases {
2735 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2736 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2737 };
2738}
2739
2740/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2741/// abi::__vmi_class_type_info.
2742///
2743static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2744 SeenBases &Bases) {
2745
2746 unsigned Flags = 0;
2747
2748 const CXXRecordDecl *BaseDecl =
2749 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2750
2751 if (Base->isVirtual()) {
2752 // Mark the virtual base as seen.
2753 if (!Bases.VirtualBases.insert(BaseDecl)) {
2754 // If this virtual base has been seen before, then the class is diamond
2755 // shaped.
2756 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2757 } else {
2758 if (Bases.NonVirtualBases.count(BaseDecl))
2759 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2760 }
2761 } else {
2762 // Mark the non-virtual base as seen.
2763 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2764 // If this non-virtual base has been seen before, then the class has non-
2765 // diamond shaped repeated inheritance.
2766 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2767 } else {
2768 if (Bases.VirtualBases.count(BaseDecl))
2769 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2770 }
2771 }
2772
2773 // Walk all bases.
2774 for (const auto &I : BaseDecl->bases())
2775 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2776
2777 return Flags;
2778}
2779
2780static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2781 unsigned Flags = 0;
2782 SeenBases Bases;
2783
2784 // Walk all bases.
2785 for (const auto &I : RD->bases())
2786 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2787
2788 return Flags;
2789}
2790
2791/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2792/// classes with bases that do not satisfy the abi::__si_class_type_info
2793/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2794void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2795 llvm::Type *UnsignedIntLTy =
2796 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2797
2798 // Itanium C++ ABI 2.9.5p6c:
2799 // __flags is a word with flags describing details about the class
2800 // structure, which may be referenced by using the __flags_masks
2801 // enumeration. These flags refer to both direct and indirect bases.
2802 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2803 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2804
2805 // Itanium C++ ABI 2.9.5p6c:
2806 // __base_count is a word with the number of direct proper base class
2807 // descriptions that follow.
2808 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2809
2810 if (!RD->getNumBases())
2811 return;
2812
2813 llvm::Type *LongLTy =
2814 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2815
2816 // Now add the base class descriptions.
2817
2818 // Itanium C++ ABI 2.9.5p6c:
2819 // __base_info[] is an array of base class descriptions -- one for every
2820 // direct proper base. Each description is of the type:
2821 //
2822 // struct abi::__base_class_type_info {
2823 // public:
2824 // const __class_type_info *__base_type;
2825 // long __offset_flags;
2826 //
2827 // enum __offset_flags_masks {
2828 // __virtual_mask = 0x1,
2829 // __public_mask = 0x2,
2830 // __offset_shift = 8
2831 // };
2832 // };
2833 for (const auto &Base : RD->bases()) {
2834 // The __base_type member points to the RTTI for the base type.
2835 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2836
2837 const CXXRecordDecl *BaseDecl =
2838 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2839
2840 int64_t OffsetFlags = 0;
2841
2842 // All but the lower 8 bits of __offset_flags are a signed offset.
2843 // For a non-virtual base, this is the offset in the object of the base
2844 // subobject. For a virtual base, this is the offset in the virtual table of
2845 // the virtual base offset for the virtual base referenced (negative).
2846 CharUnits Offset;
2847 if (Base.isVirtual())
2848 Offset =
2849 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2850 else {
2851 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2852 Offset = Layout.getBaseClassOffset(BaseDecl);
2853 };
2854
2855 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2856
2857 // The low-order byte of __offset_flags contains flags, as given by the
2858 // masks from the enumeration __offset_flags_masks.
2859 if (Base.isVirtual())
2860 OffsetFlags |= BCTI_Virtual;
2861 if (Base.getAccessSpecifier() == AS_public)
2862 OffsetFlags |= BCTI_Public;
2863
2864 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2865 }
2866}
2867
2868/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2869/// used for pointer types.
2870void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2871 Qualifiers Quals;
2872 QualType UnqualifiedPointeeTy =
2873 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2874
2875 // Itanium C++ ABI 2.9.5p7:
2876 // __flags is a flag word describing the cv-qualification and other
2877 // attributes of the type pointed to
2878 unsigned Flags = ComputeQualifierFlags(Quals);
2879
2880 // Itanium C++ ABI 2.9.5p7:
2881 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2882 // incomplete class type, the incomplete target type flag is set.
2883 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2884 Flags |= PTI_Incomplete;
2885
2886 llvm::Type *UnsignedIntLTy =
2887 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2888 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2889
2890 // Itanium C++ ABI 2.9.5p7:
2891 // __pointee is a pointer to the std::type_info derivation for the
2892 // unqualified type being pointed to.
2893 llvm::Constant *PointeeTypeInfo =
2894 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2895 Fields.push_back(PointeeTypeInfo);
2896}
2897
2898/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2899/// struct, used for member pointer types.
2900void
2901ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2902 QualType PointeeTy = Ty->getPointeeType();
2903
2904 Qualifiers Quals;
2905 QualType UnqualifiedPointeeTy =
2906 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2907
2908 // Itanium C++ ABI 2.9.5p7:
2909 // __flags is a flag word describing the cv-qualification and other
2910 // attributes of the type pointed to.
2911 unsigned Flags = ComputeQualifierFlags(Quals);
2912
2913 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2914
2915 // Itanium C++ ABI 2.9.5p7:
2916 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2917 // incomplete class type, the incomplete target type flag is set.
2918 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2919 Flags |= PTI_Incomplete;
2920
2921 if (IsIncompleteClassType(ClassType))
2922 Flags |= PTI_ContainingClassIncomplete;
2923
2924 llvm::Type *UnsignedIntLTy =
2925 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2926 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2927
2928 // Itanium C++ ABI 2.9.5p7:
2929 // __pointee is a pointer to the std::type_info derivation for the
2930 // unqualified type being pointed to.
2931 llvm::Constant *PointeeTypeInfo =
2932 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2933 Fields.push_back(PointeeTypeInfo);
2934
2935 // Itanium C++ ABI 2.9.5p9:
2936 // __context is a pointer to an abi::__class_type_info corresponding to the
2937 // class type containing the member pointed to
2938 // (e.g., the "A" in "int A::*").
2939 Fields.push_back(
2940 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2941}
2942
2943llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2944 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2945}
2946
2947void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2948 QualType PointerType = getContext().getPointerType(Type);
2949 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2950 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2951 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2952 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2953}
2954
2955void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2956 QualType FundamentalTypes[] = {
2957 getContext().VoidTy, getContext().NullPtrTy,
2958 getContext().BoolTy, getContext().WCharTy,
2959 getContext().CharTy, getContext().UnsignedCharTy,
2960 getContext().SignedCharTy, getContext().ShortTy,
2961 getContext().UnsignedShortTy, getContext().IntTy,
2962 getContext().UnsignedIntTy, getContext().LongTy,
2963 getContext().UnsignedLongTy, getContext().LongLongTy,
2964 getContext().UnsignedLongLongTy, getContext().HalfTy,
2965 getContext().FloatTy, getContext().DoubleTy,
2966 getContext().LongDoubleTy, getContext().Char16Ty,
2967 getContext().Char32Ty,
2968 };
2969 for (const QualType &FundamentalType : FundamentalTypes)
2970 EmitFundamentalRTTIDescriptor(FundamentalType);
2971}
2972
2973/// What sort of uniqueness rules should we use for the RTTI for the
2974/// given type?
2975ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2976 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2977 if (shouldRTTIBeUnique())
2978 return RUK_Unique;
2979
2980 // It's only necessary for linkonce_odr or weak_odr linkage.
2981 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2982 Linkage != llvm::GlobalValue::WeakODRLinkage)
2983 return RUK_Unique;
2984
2985 // It's only necessary with default visibility.
2986 if (CanTy->getVisibility() != DefaultVisibility)
2987 return RUK_Unique;
2988
2989 // If we're not required to publish this symbol, hide it.
2990 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
2991 return RUK_NonUniqueHidden;
2992
2993 // If we're required to publish this symbol, as we might be under an
2994 // explicit instantiation, leave it with default visibility but
2995 // enable string-comparisons.
2996 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
2997 return RUK_NonUniqueVisible;
2998}