blob: 25cb5fe3714c31affe31b5bfdfb72e79c10d1d2b [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"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000028#include "clang/AST/Mangle.h"
29#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000030#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000033#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000036
37using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000038using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000039
40namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000041class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000042 /// VTables - All the vtables which have been defined.
43 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
44
John McCall475999d2010-08-22 00:05:51 +000045protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000046 bool UseARMMethodPtrABI;
47 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000048
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000049 ItaniumMangleContext &getMangleContext() {
50 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
51 }
52
Charles Davis4e786dd2010-05-25 19:52:27 +000053public:
Mark Seabornedf0d382013-07-24 16:25:13 +000054 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
55 bool UseARMMethodPtrABI = false,
56 bool UseARMGuardVarABI = false) :
57 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
58 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000059
Reid Kleckner40ca9132014-05-13 22:05:45 +000060 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000061
Craig Topper4f12f102014-03-12 06:41:41 +000062 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000063 // Structures with either a non-trivial destructor or a non-trivial
64 // copy constructor are always indirect.
65 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
66 // special members.
67 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
John McCall7f416cc2015-09-08 08:05:57 +000072 bool isThisCompleteObject(GlobalDecl GD) const override {
73 // The Itanium ABI has separate complete-object vs. base-object
74 // variants of both constructors and destructors.
75 if (isa<CXXDestructorDecl>(GD.getDecl())) {
76 switch (GD.getDtorType()) {
77 case Dtor_Complete:
78 case Dtor_Deleting:
79 return true;
80
81 case Dtor_Base:
82 return false;
83
84 case Dtor_Comdat:
85 llvm_unreachable("emitting dtor comdat as function?");
86 }
87 llvm_unreachable("bad dtor kind");
88 }
89 if (isa<CXXConstructorDecl>(GD.getDecl())) {
90 switch (GD.getCtorType()) {
91 case Ctor_Complete:
92 return true;
93
94 case Ctor_Base:
95 return false;
96
97 case Ctor_CopyingClosure:
98 case Ctor_DefaultClosure:
99 llvm_unreachable("closure ctors in Itanium ABI?");
100
101 case Ctor_Comdat:
102 llvm_unreachable("emitting ctor comdat as function?");
103 }
104 llvm_unreachable("bad dtor kind");
105 }
106
107 // No other kinds.
108 return false;
109 }
110
Craig Topper4f12f102014-03-12 06:41:41 +0000111 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000114
Craig Topper4f12f102014-03-12 06:41:41 +0000115 llvm::Value *
116 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
117 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000118 Address This,
119 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000120 llvm::Value *MemFnPtr,
121 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000122
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *
124 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000125 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *MemPtr,
127 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000128
John McCall7a9aac22010-08-23 01:21:21 +0000129 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
130 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000132 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000134
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
David Majnemere2be95b2015-06-23 07:31:01 +0000137 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000138 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 CharUnits offset) override;
140 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000141 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
142 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000143
John McCall7a9aac22010-08-23 01:21:21 +0000144 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000145 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000146 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *Addr,
151 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000152
David Majnemer08681372014-11-01 07:37:17 +0000153 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000154 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000156
John McCall7f416cc2015-09-08 08:05:57 +0000157 CharUnits getAlignmentOfExnObject() {
Akira Hatanaka68ab7fe2016-03-31 06:36:07 +0000158 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
159 return CGM.getContext().toCharUnitsFromBits(Align);
John McCall7f416cc2015-09-08 08:05:57 +0000160 }
161
David Majnemer442d0a22014-11-25 07:20:20 +0000162 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000163 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000164
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000165 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
166
167 llvm::CallInst *
168 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
169 llvm::Value *Exn) override;
170
David Majnemere2cb8d12014-07-07 06:20:47 +0000171 void EmitFundamentalRTTIDescriptor(QualType Type);
172 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000173 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000174 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000175 getAddrOfCXXCatchHandlerType(QualType Ty,
176 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000177 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000178 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000179
David Majnemer1162d252014-06-22 19:05:33 +0000180 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
181 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
182 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000183 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000184 llvm::Type *StdTypeInfoPtrTy) override;
185
186 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
187 QualType SrcRecordTy) override;
188
John McCall7f416cc2015-09-08 08:05:57 +0000189 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000190 QualType SrcRecordTy, QualType DestTy,
191 QualType DestRecordTy,
192 llvm::BasicBlock *CastEnd) override;
193
John McCall7f416cc2015-09-08 08:05:57 +0000194 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000195 QualType SrcRecordTy,
196 QualType DestTy) override;
197
198 bool EmitBadCastCall(CodeGenFunction &CGF) override;
199
Craig Topper4f12f102014-03-12 06:41:41 +0000200 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000201 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000202 const CXXRecordDecl *ClassDecl,
203 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000204
Craig Topper4f12f102014-03-12 06:41:41 +0000205 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000206
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000207 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
208 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000209
Reid Klecknere7de47e2013-07-22 13:51:44 +0000210 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000211 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000212 // Itanium does not emit any destructor variant as an inline thunk.
213 // Delegating may occur as an optimization, but all variants are either
214 // emitted with external linkage or as linkonce if they are inline and used.
215 return false;
216 }
217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000219
Reid Kleckner89077a12013-12-17 19:46:40 +0000220 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000222
Craig Topper4f12f102014-03-12 06:41:41 +0000223 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000224
Reid Kleckner89077a12013-12-17 19:46:40 +0000225 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
226 const CXXConstructorDecl *D,
227 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000228 bool Delegating,
229 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000230
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000231 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
232 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000233 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000234
Craig Topper4f12f102014-03-12 06:41:41 +0000235 void emitVTableDefinitions(CodeGenVTables &CGVT,
236 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000237
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000238 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
239 CodeGenFunction::VPtr Vptr) override;
240
241 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
242 return true;
243 }
244
245 llvm::Constant *
246 getVTableAddressPoint(BaseSubobject Base,
247 const CXXRecordDecl *VTableClass) override;
248
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000249 llvm::Value *getVTableAddressPointInStructor(
250 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000251 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
252
253 llvm::Value *getVTableAddressPointInStructorWithVTT(
254 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
255 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000256
257 llvm::Constant *
258 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000259 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000260
261 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000262 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000263
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000264 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +0000265 Address This, llvm::Type *Ty,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000266 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000267
David Majnemer0c0b6d92014-10-31 20:09:12 +0000268 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
269 const CXXDestructorDecl *Dtor,
270 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000271 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000272 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000273
Craig Topper4f12f102014-03-12 06:41:41 +0000274 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000275
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000276 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000277
Hans Wennborgc94391d2014-06-06 20:04:01 +0000278 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
279 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000280 // Allow inlining of thunks by emitting them with available_externally
281 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000282 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000283 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
284 }
285
John McCall7f416cc2015-09-08 08:05:57 +0000286 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000287 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000288
John McCall7f416cc2015-09-08 08:05:57 +0000289 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000290 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000291
David Majnemer196ac332014-09-11 23:05:02 +0000292 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
293 FunctionArgList &Args) const override {
294 assert(!Args.empty() && "expected the arglist to not be empty!");
295 return Args.size() - 1;
296 }
297
Craig Topper4f12f102014-03-12 06:41:41 +0000298 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
299 StringRef GetDeletedVirtualCallName() override
300 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000301
Craig Topper4f12f102014-03-12 06:41:41 +0000302 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000303 Address InitializeArrayCookie(CodeGenFunction &CGF,
304 Address NewPtr,
305 llvm::Value *NumElements,
306 const CXXNewExpr *expr,
307 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000308 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000309 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000310 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000311
John McCallcdf7ef52010-11-06 09:44:32 +0000312 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000313 llvm::GlobalVariable *DeclPtr,
314 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000315 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000316 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000317
318 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000319 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000320 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000321 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000322 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000323 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000324 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000325
326 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000327 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
328 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000329
Craig Topper4f12f102014-03-12 06:41:41 +0000330 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000331
332 /**************************** RTTI Uniqueness ******************************/
333
334protected:
335 /// Returns true if the ABI requires RTTI type_info objects to be unique
336 /// across a program.
337 virtual bool shouldRTTIBeUnique() const { return true; }
338
339public:
340 /// What sort of unique-RTTI behavior should we use?
341 enum RTTIUniquenessKind {
342 /// We are guaranteeing, or need to guarantee, that the RTTI string
343 /// is unique.
344 RUK_Unique,
345
346 /// We are not guaranteeing uniqueness for the RTTI string, so we
347 /// can demote to hidden visibility but must use string comparisons.
348 RUK_NonUniqueHidden,
349
350 /// We are not guaranteeing uniqueness for the RTTI string, so we
351 /// have to use string comparisons, but we also have to emit it with
352 /// non-hidden visibility.
353 RUK_NonUniqueVisible
354 };
355
356 /// Return the required visibility status for the given type and linkage in
357 /// the current ABI.
358 RTTIUniquenessKind
359 classifyRTTIUniqueness(QualType CanTy,
360 llvm::GlobalValue::LinkageTypes Linkage) const;
361 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000362
363 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000364
365 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000366 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000367 const auto &VtableLayout =
368 CGM.getItaniumVTableContext().getVTableLayout(RD);
369
370 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000371 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000372 continue;
373
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000374 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000375 if (Method->getCanonicalDecl()->isInlined())
376 return true;
377 }
378 return false;
379 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000380
381 bool isVTableHidden(const CXXRecordDecl *RD) const {
382 const auto &VtableLayout =
383 CGM.getItaniumVTableContext().getVTableLayout(RD);
384
385 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
386 if (VtableComponent.isRTTIKind()) {
387 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
388 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
389 return true;
390 } else if (VtableComponent.isUsedFunctionPointerKind()) {
391 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
392 if (Method->getVisibility() == Visibility::HiddenVisibility &&
393 !Method->isDefined())
394 return true;
395 }
396 }
397 return false;
398 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000399};
John McCall86353412010-08-21 22:46:04 +0000400
401class ARMCXXABI : public ItaniumCXXABI {
402public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000403 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
404 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
405 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000406
Craig Topper4f12f102014-03-12 06:41:41 +0000407 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000408 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
409 isa<CXXDestructorDecl>(GD.getDecl()) &&
410 GD.getDtorType() != Dtor_Deleting));
411 }
John McCall5d865c322010-08-31 07:33:07 +0000412
Craig Topper4f12f102014-03-12 06:41:41 +0000413 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
414 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000415
Craig Topper4f12f102014-03-12 06:41:41 +0000416 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000417 Address InitializeArrayCookie(CodeGenFunction &CGF,
418 Address NewPtr,
419 llvm::Value *NumElements,
420 const CXXNewExpr *expr,
421 QualType ElementType) override;
422 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000423 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000424};
Tim Northovera2ee4332014-03-29 15:09:45 +0000425
426class iOS64CXXABI : public ARMCXXABI {
427public:
428 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000429
430 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000431 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000432};
Dan Gohmanc2853072015-09-03 22:51:53 +0000433
434class WebAssemblyCXXABI final : public ItaniumCXXABI {
435public:
436 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
437 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
438 /*UseARMGuardVarABI=*/true) {}
439
440private:
441 bool HasThisReturn(GlobalDecl GD) const override {
442 return isa<CXXConstructorDecl>(GD.getDecl()) ||
443 (isa<CXXDestructorDecl>(GD.getDecl()) &&
444 GD.getDtorType() != Dtor_Deleting);
445 }
446};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000447}
Charles Davis4e786dd2010-05-25 19:52:27 +0000448
Charles Davis53c59df2010-08-16 03:33:14 +0000449CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000450 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000451 // For IR-generation purposes, there's no significant difference
452 // between the ARM and iOS ABIs.
453 case TargetCXXABI::GenericARM:
454 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000455 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000456 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000457
Tim Northovera2ee4332014-03-29 15:09:45 +0000458 case TargetCXXABI::iOS64:
459 return new iOS64CXXABI(CGM);
460
Tim Northover9bb857a2013-01-31 12:13:10 +0000461 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
462 // include the other 32-bit ARM oddities: constructor/destructor return values
463 // and array cookies.
464 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000465 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
466 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000467
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000468 case TargetCXXABI::GenericMIPS:
469 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
470
Dan Gohmanc2853072015-09-03 22:51:53 +0000471 case TargetCXXABI::WebAssembly:
472 return new WebAssemblyCXXABI(CGM);
473
John McCall57625922013-01-25 23:36:14 +0000474 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000475 if (CGM.getContext().getTargetInfo().getTriple().getArch()
476 == llvm::Triple::le32) {
477 // For PNaCl, use ARM-style method pointers so that PNaCl code
478 // does not assume anything about the alignment of function
479 // pointers.
480 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
481 /* UseARMGuardVarABI = */ false);
482 }
John McCall57625922013-01-25 23:36:14 +0000483 return new ItaniumCXXABI(CGM);
484
485 case TargetCXXABI::Microsoft:
486 llvm_unreachable("Microsoft ABI is not Itanium-based");
487 }
488 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000489}
490
Chris Lattnera5f58b02011-07-09 17:41:47 +0000491llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000492ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
493 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000494 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000495 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000496}
497
John McCalld9c6c0b2010-08-22 00:59:17 +0000498/// In the Itanium and ARM ABIs, method pointers have the form:
499/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
500///
501/// In the Itanium ABI:
502/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
503/// - the this-adjustment is (memptr.adj)
504/// - the virtual offset is (memptr.ptr - 1)
505///
506/// In the ARM ABI:
507/// - method pointers are virtual if (memptr.adj & 1) is nonzero
508/// - the this-adjustment is (memptr.adj >> 1)
509/// - the virtual offset is (memptr.ptr)
510/// ARM uses 'adj' for the virtual flag because Thumb functions
511/// may be only single-byte aligned.
512///
513/// If the member is virtual, the adjusted 'this' pointer points
514/// to a vtable pointer from which the virtual offset is applied.
515///
516/// If the member is non-virtual, memptr.ptr is the address of
517/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000518llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000519 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
520 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000521 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000522 CGBuilderTy &Builder = CGF.Builder;
523
524 const FunctionProtoType *FPT =
525 MPT->getPointeeType()->getAs<FunctionProtoType>();
526 const CXXRecordDecl *RD =
527 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
528
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000529 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
530 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000531
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000532 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000533
John McCalld9c6c0b2010-08-22 00:59:17 +0000534 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
535 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
536 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
537
John McCalla1dee5302010-08-22 10:59:02 +0000538 // Extract memptr.adj, which is in the second field.
539 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000540
541 // Compute the true adjustment.
542 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000543 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000544 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000545
546 // Apply the adjustment and cast back to the original struct type
547 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000548 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000549 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
550 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
551 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000552 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000553
554 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000555 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000556
557 // If the LSB in the function pointer is 1, the function pointer points to
558 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000559 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000560 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000561 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
562 else
563 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
564 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000565 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
566
567 // In the virtual path, the adjustment left 'This' pointing to the
568 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000569 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000570 CGF.EmitBlock(FnVirtual);
571
572 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000573 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000574 CharUnits VTablePtrAlign =
575 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
576 CGF.getPointerAlign());
577 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000578 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000579
580 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000581 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000582 if (!UseARMMethodPtrABI)
583 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000584 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000585
586 // Load the virtual function to call.
587 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000588 llvm::Value *VirtualFn =
589 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
590 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000591 CGF.EmitBranch(FnEnd);
592
593 // In the non-virtual path, the function pointer is actually a
594 // function pointer.
595 CGF.EmitBlock(FnNonVirtual);
596 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000597 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000598
599 // We're done.
600 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000601 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000602 Callee->addIncoming(VirtualFn, FnVirtual);
603 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
604 return Callee;
605}
John McCalla8bbb822010-08-22 03:04:22 +0000606
John McCallc134eb52010-08-31 21:07:20 +0000607/// Compute an l-value by applying the given pointer-to-member to a
608/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000609llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000610 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000611 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000612 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000613
614 CGBuilderTy &Builder = CGF.Builder;
615
John McCallc134eb52010-08-31 21:07:20 +0000616 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000617 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000618
619 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000620 llvm::Value *Addr =
621 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000622
623 // Cast the address to the appropriate pointer type, adopting the
624 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000625 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
626 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000627 return Builder.CreateBitCast(Addr, PType);
628}
629
John McCallc62bb392012-02-15 01:22:51 +0000630/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
631/// conversion.
632///
633/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000634///
635/// Obligatory offset/adjustment diagram:
636/// <-- offset --> <-- adjustment -->
637/// |--------------------------|----------------------|--------------------|
638/// ^Derived address point ^Base address point ^Member address point
639///
640/// So when converting a base member pointer to a derived member pointer,
641/// we add the offset to the adjustment because the address point has
642/// decreased; and conversely, when converting a derived MP to a base MP
643/// we subtract the offset from the adjustment because the address point
644/// has increased.
645///
646/// The standard forbids (at compile time) conversion to and from
647/// virtual bases, which is why we don't have to consider them here.
648///
649/// The standard forbids (at run time) casting a derived MP to a base
650/// MP when the derived MP does not point to a member of the base.
651/// This is why -1 is a reasonable choice for null data member
652/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000653llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000654ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
655 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000656 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000657 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000658 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
659 E->getCastKind() == CK_ReinterpretMemberPointer);
660
661 // Under Itanium, reinterprets don't require any additional processing.
662 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
663
664 // Use constant emission if we can.
665 if (isa<llvm::Constant>(src))
666 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
667
668 llvm::Constant *adj = getMemberPointerAdjustment(E);
669 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000670
671 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000672 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000673
John McCallc62bb392012-02-15 01:22:51 +0000674 const MemberPointerType *destTy =
675 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000676
John McCall7a9aac22010-08-23 01:21:21 +0000677 // For member data pointers, this is just a matter of adding the
678 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000679 if (destTy->isMemberDataPointer()) {
680 llvm::Value *dst;
681 if (isDerivedToBase)
682 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000683 else
John McCallc62bb392012-02-15 01:22:51 +0000684 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000685
686 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000687 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
688 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
689 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000690 }
691
John McCalla1dee5302010-08-22 10:59:02 +0000692 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000693 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000694 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
695 offset <<= 1;
696 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000697 }
698
John McCallc62bb392012-02-15 01:22:51 +0000699 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
700 llvm::Value *dstAdj;
701 if (isDerivedToBase)
702 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000703 else
John McCallc62bb392012-02-15 01:22:51 +0000704 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000705
John McCallc62bb392012-02-15 01:22:51 +0000706 return Builder.CreateInsertValue(src, dstAdj, 1);
707}
708
709llvm::Constant *
710ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
711 llvm::Constant *src) {
712 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
713 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
714 E->getCastKind() == CK_ReinterpretMemberPointer);
715
716 // Under Itanium, reinterprets don't require any additional processing.
717 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
718
719 // If the adjustment is trivial, we don't need to do anything.
720 llvm::Constant *adj = getMemberPointerAdjustment(E);
721 if (!adj) return src;
722
723 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
724
725 const MemberPointerType *destTy =
726 E->getType()->castAs<MemberPointerType>();
727
728 // For member data pointers, this is just a matter of adding the
729 // offset if the source is non-null.
730 if (destTy->isMemberDataPointer()) {
731 // null maps to null.
732 if (src->isAllOnesValue()) return src;
733
734 if (isDerivedToBase)
735 return llvm::ConstantExpr::getNSWSub(src, adj);
736 else
737 return llvm::ConstantExpr::getNSWAdd(src, adj);
738 }
739
740 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000741 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000742 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
743 offset <<= 1;
744 adj = llvm::ConstantInt::get(adj->getType(), offset);
745 }
746
747 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
748 llvm::Constant *dstAdj;
749 if (isDerivedToBase)
750 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
751 else
752 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
753
754 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000755}
John McCall84fa5102010-08-22 04:16:24 +0000756
757llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000758ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000759 // Itanium C++ ABI 2.3:
760 // A NULL pointer is represented as -1.
761 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000762 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000763
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000764 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000765 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000766 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000767}
768
John McCallf3a88602011-02-03 08:15:49 +0000769llvm::Constant *
770ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
771 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000772 // Itanium C++ ABI 2.3:
773 // A pointer to data member is an offset from the base address of
774 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000775 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000776}
777
David Majnemere2be95b2015-06-23 07:31:01 +0000778llvm::Constant *
779ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000780 return BuildMemberPointer(MD, CharUnits::Zero());
781}
782
783llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
784 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000785 assert(MD->isInstance() && "Member function must not be static!");
786 MD = MD->getCanonicalDecl();
787
788 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000789
790 // Get the function pointer (or index if this is a virtual function).
791 llvm::Constant *MemPtr[2];
792 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000793 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000794
Ken Dyckdf016282011-04-09 01:30:02 +0000795 const ASTContext &Context = getContext();
796 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000797 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000798 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000799
Mark Seabornedf0d382013-07-24 16:25:13 +0000800 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000801 // ARM C++ ABI 3.2.1:
802 // This ABI specifies that adj contains twice the this
803 // adjustment, plus 1 if the member function is virtual. The
804 // least significant bit of adj then makes exactly the same
805 // discrimination as the least significant bit of ptr does for
806 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000807 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
808 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000809 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000810 } else {
811 // Itanium C++ ABI 2.3:
812 // For a virtual function, [the pointer field] is 1 plus the
813 // virtual table offset (in bytes) of the function,
814 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000815 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
816 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000817 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000818 }
819 } else {
John McCall2979fe02011-04-12 00:42:48 +0000820 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000821 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000822 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000823 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000824 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000825 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000826 } else {
John McCall2979fe02011-04-12 00:42:48 +0000827 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
828 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000829 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000830 }
John McCall2979fe02011-04-12 00:42:48 +0000831 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000832
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000833 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000834 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
835 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000836 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000837 }
John McCall1c456c82010-08-22 06:43:33 +0000838
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000839 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000840}
841
Richard Smithdafff942012-01-14 04:30:29 +0000842llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
843 QualType MPType) {
844 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
845 const ValueDecl *MPD = MP.getMemberPointerDecl();
846 if (!MPD)
847 return EmitNullMemberPointer(MPT);
848
Reid Kleckner452abac2013-05-09 21:01:17 +0000849 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000850
851 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
852 return BuildMemberPointer(MD, ThisAdjustment);
853
854 CharUnits FieldOffset =
855 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
856 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
857}
858
John McCall131d97d2010-08-22 08:30:07 +0000859/// The comparison algorithm is pretty easy: the member pointers are
860/// the same if they're either bitwise identical *or* both null.
861///
862/// ARM is different here only because null-ness is more complicated.
863llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000864ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
865 llvm::Value *L,
866 llvm::Value *R,
867 const MemberPointerType *MPT,
868 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000869 CGBuilderTy &Builder = CGF.Builder;
870
John McCall131d97d2010-08-22 08:30:07 +0000871 llvm::ICmpInst::Predicate Eq;
872 llvm::Instruction::BinaryOps And, Or;
873 if (Inequality) {
874 Eq = llvm::ICmpInst::ICMP_NE;
875 And = llvm::Instruction::Or;
876 Or = llvm::Instruction::And;
877 } else {
878 Eq = llvm::ICmpInst::ICMP_EQ;
879 And = llvm::Instruction::And;
880 Or = llvm::Instruction::Or;
881 }
882
John McCall7a9aac22010-08-23 01:21:21 +0000883 // Member data pointers are easy because there's a unique null
884 // value, so it just comes down to bitwise equality.
885 if (MPT->isMemberDataPointer())
886 return Builder.CreateICmp(Eq, L, R);
887
888 // For member function pointers, the tautologies are more complex.
889 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000890 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000891 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000892 // (L == R) <==> (L.ptr == R.ptr &&
893 // (L.adj == R.adj ||
894 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000895 // The inequality tautologies have exactly the same structure, except
896 // applying De Morgan's laws.
897
898 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
899 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
900
John McCall131d97d2010-08-22 08:30:07 +0000901 // This condition tests whether L.ptr == R.ptr. This must always be
902 // true for equality to hold.
903 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
904
905 // This condition, together with the assumption that L.ptr == R.ptr,
906 // tests whether the pointers are both null. ARM imposes an extra
907 // condition.
908 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
909 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
910
911 // This condition tests whether L.adj == R.adj. If this isn't
912 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000913 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
914 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000915 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
916
917 // Null member function pointers on ARM clear the low bit of Adj,
918 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000919 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000920 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
921
922 // Compute (l.adj | r.adj) & 1 and test it against zero.
923 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
924 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
925 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
926 "cmp.or.adj");
927 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
928 }
929
930 // Tie together all our conditions.
931 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
932 Result = Builder.CreateBinOp(And, PtrEq, Result,
933 Inequality ? "memptr.ne" : "memptr.eq");
934 return Result;
935}
936
937llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000938ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
939 llvm::Value *MemPtr,
940 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000941 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000942
943 /// For member data pointers, this is just a check against -1.
944 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000945 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000946 llvm::Value *NegativeOne =
947 llvm::Constant::getAllOnesValue(MemPtr->getType());
948 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
949 }
John McCall131d97d2010-08-22 08:30:07 +0000950
Daniel Dunbar914bc412011-04-19 23:10:47 +0000951 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000952 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000953
954 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
955 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
956
Daniel Dunbar914bc412011-04-19 23:10:47 +0000957 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
958 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000959 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000960 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000961 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000962 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000963 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
964 "memptr.isvirtual");
965 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000966 }
967
968 return Result;
969}
John McCall1c456c82010-08-22 06:43:33 +0000970
Reid Kleckner40ca9132014-05-13 22:05:45 +0000971bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
972 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
973 if (!RD)
974 return false;
975
Reid Klecknerd355ca72014-05-15 01:26:32 +0000976 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
977 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
978 // special members.
979 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000980 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
981 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000982 return true;
983 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000984 return false;
985}
986
John McCall614dbdc2010-08-22 21:01:12 +0000987/// The Itanium ABI requires non-zero initialization only for data
988/// member pointers, for which '0' is a valid offset.
989bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000990 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000991}
John McCall5d865c322010-08-31 07:33:07 +0000992
John McCall82fb8922012-09-25 10:10:39 +0000993/// The Itanium ABI always places an offset to the complete object
994/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000995void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
996 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000997 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +0000998 QualType ElementType,
999 const CXXDestructorDecl *Dtor) {
1000 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001001 if (UseGlobalDelete) {
1002 // Derive the complete-object pointer, which is what we need
1003 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001004
David Majnemer0c0b6d92014-10-31 20:09:12 +00001005 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001006 auto *ClassDecl =
1007 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1008 llvm::Value *VTable =
1009 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001010
David Majnemer0c0b6d92014-10-31 20:09:12 +00001011 // Track back to entry -2 and pull out the offset there.
1012 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1013 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001014 llvm::Value *Offset =
1015 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001016
1017 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001018 llvm::Value *CompletePtr =
1019 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001020 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1021
1022 // If we're supposed to call the global delete, make sure we do so
1023 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001024 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1025 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001026 }
1027
1028 // FIXME: Provide a source location here even though there's no
1029 // CXXMemberCallExpr for dtor call.
1030 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1031 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1032
1033 if (UseGlobalDelete)
1034 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001035}
1036
David Majnemer442d0a22014-11-25 07:20:20 +00001037void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1038 // void __cxa_rethrow();
1039
1040 llvm::FunctionType *FTy =
1041 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1042
1043 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1044
1045 if (isNoReturn)
1046 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1047 else
1048 CGF.EmitRuntimeCallOrInvoke(Fn);
1049}
1050
David Majnemer7c237072015-03-05 00:46:22 +00001051static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1052 // void *__cxa_allocate_exception(size_t thrown_size);
1053
1054 llvm::FunctionType *FTy =
1055 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1056
1057 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1058}
1059
1060static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1061 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1062 // void (*dest) (void *));
1063
1064 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1065 llvm::FunctionType *FTy =
1066 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1067
1068 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1069}
1070
1071void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1072 QualType ThrowType = E->getSubExpr()->getType();
1073 // Now allocate the exception object.
1074 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1075 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1076
1077 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1078 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1079 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1080
John McCall7f416cc2015-09-08 08:05:57 +00001081 CharUnits ExnAlign = getAlignmentOfExnObject();
1082 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001083
1084 // Now throw the exception.
1085 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1086 /*ForEH=*/true);
1087
1088 // The address of the destructor. If the exception type has a
1089 // trivial destructor (or isn't a record), we just pass null.
1090 llvm::Constant *Dtor = nullptr;
1091 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1092 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1093 if (!Record->hasTrivialDestructor()) {
1094 CXXDestructorDecl *DtorD = Record->getDestructor();
1095 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1096 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1097 }
1098 }
1099 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1100
1101 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1102 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1103}
1104
David Majnemer1162d252014-06-22 19:05:33 +00001105static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1106 // void *__dynamic_cast(const void *sub,
1107 // const abi::__class_type_info *src,
1108 // const abi::__class_type_info *dst,
1109 // std::ptrdiff_t src2dst_offset);
1110
1111 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1112 llvm::Type *PtrDiffTy =
1113 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1114
1115 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1116
1117 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1118
1119 // Mark the function as nounwind readonly.
1120 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1121 llvm::Attribute::ReadOnly };
1122 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1123 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1124
1125 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1126}
1127
1128static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1129 // void __cxa_bad_cast();
1130 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1131 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1132}
1133
1134/// \brief Compute the src2dst_offset hint as described in the
1135/// Itanium C++ ABI [2.9.7]
1136static CharUnits computeOffsetHint(ASTContext &Context,
1137 const CXXRecordDecl *Src,
1138 const CXXRecordDecl *Dst) {
1139 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1140 /*DetectVirtual=*/false);
1141
1142 // If Dst is not derived from Src we can skip the whole computation below and
1143 // return that Src is not a public base of Dst. Record all inheritance paths.
1144 if (!Dst->isDerivedFrom(Src, Paths))
1145 return CharUnits::fromQuantity(-2ULL);
1146
1147 unsigned NumPublicPaths = 0;
1148 CharUnits Offset;
1149
1150 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001151 for (const CXXBasePath &Path : Paths) {
1152 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001153 continue;
1154
1155 ++NumPublicPaths;
1156
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001157 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001158 // If the path contains a virtual base class we can't give any hint.
1159 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001160 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001161 return CharUnits::fromQuantity(-1ULL);
1162
1163 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1164 continue;
1165
1166 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001167 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1168 Offset += L.getBaseClassOffset(
1169 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001170 }
1171 }
1172
1173 // -2: Src is not a public base of Dst.
1174 if (NumPublicPaths == 0)
1175 return CharUnits::fromQuantity(-2ULL);
1176
1177 // -3: Src is a multiple public base type but never a virtual base type.
1178 if (NumPublicPaths > 1)
1179 return CharUnits::fromQuantity(-3ULL);
1180
1181 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1182 // Return the offset of Src from the origin of Dst.
1183 return Offset;
1184}
1185
1186static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1187 // void __cxa_bad_typeid();
1188 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1189
1190 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1191}
1192
1193bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1194 QualType SrcRecordTy) {
1195 return IsDeref;
1196}
1197
1198void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1199 llvm::Value *Fn = getBadTypeidFn(CGF);
1200 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1201 CGF.Builder.CreateUnreachable();
1202}
1203
1204llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1205 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001206 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001207 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001208 auto *ClassDecl =
1209 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001210 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001211 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001212
1213 // Load the type info.
1214 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001215 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001216}
1217
1218bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1219 QualType SrcRecordTy) {
1220 return SrcIsPtr;
1221}
1222
1223llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001224 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001225 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1226 llvm::Type *PtrDiffLTy =
1227 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1228 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1229
1230 llvm::Value *SrcRTTI =
1231 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1232 llvm::Value *DestRTTI =
1233 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1234
1235 // Compute the offset hint.
1236 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1237 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1238 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1239 PtrDiffLTy,
1240 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1241
1242 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001243 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001244 Value = CGF.EmitCastToVoidPtr(Value);
1245
1246 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1247 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1248 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1249
1250 /// C++ [expr.dynamic.cast]p9:
1251 /// A failed cast to reference type throws std::bad_cast
1252 if (DestTy->isReferenceType()) {
1253 llvm::BasicBlock *BadCastBlock =
1254 CGF.createBasicBlock("dynamic_cast.bad_cast");
1255
1256 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1257 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1258
1259 CGF.EmitBlock(BadCastBlock);
1260 EmitBadCastCall(CGF);
1261 }
1262
1263 return Value;
1264}
1265
1266llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001267 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001268 QualType SrcRecordTy,
1269 QualType DestTy) {
1270 llvm::Type *PtrDiffLTy =
1271 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1272 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1273
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001274 auto *ClassDecl =
1275 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001276 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001277 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1278 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001279
1280 // Get the offset-to-top from the vtable.
1281 llvm::Value *OffsetToTop =
1282 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001283 OffsetToTop =
1284 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1285 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001286
1287 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001288 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001289 Value = CGF.EmitCastToVoidPtr(Value);
1290 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1291
1292 return CGF.Builder.CreateBitCast(Value, DestLTy);
1293}
1294
1295bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1296 llvm::Value *Fn = getBadCastFn(CGF);
1297 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1298 CGF.Builder.CreateUnreachable();
1299 return true;
1300}
1301
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001302llvm::Value *
1303ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001304 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001305 const CXXRecordDecl *ClassDecl,
1306 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001307 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001308 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001309 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1310 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001311
1312 llvm::Value *VBaseOffsetPtr =
1313 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1314 "vbase.offset.ptr");
1315 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1316 CGM.PtrDiffTy->getPointerTo());
1317
1318 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001319 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1320 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001321
1322 return VBaseOffset;
1323}
1324
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001325void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1326 // Just make sure we're in sync with TargetCXXABI.
1327 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1328
Rafael Espindolac3cde362013-12-09 14:51:17 +00001329 // The constructor used for constructing this as a base class;
1330 // ignores virtual bases.
1331 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1332
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001333 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001334 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001335 if (!D->getParent()->isAbstract()) {
1336 // We don't need to emit the complete ctor if the class is abstract.
1337 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1338 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001339}
1340
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001341void
1342ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1343 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001344 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001345
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001346 // All parameters are already in place except VTT, which goes after 'this'.
1347 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001348
1349 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001350 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1351 ArgTys.insert(ArgTys.begin() + 1,
1352 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001353}
1354
Reid Klecknere7de47e2013-07-22 13:51:44 +00001355void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001356 // The destructor used for destructing this as a base class; ignores
1357 // virtual bases.
1358 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001359
1360 // The destructor used for destructing this as a most-derived class;
1361 // call the base destructor and then destructs any virtual bases.
1362 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1363
Rafael Espindolac3cde362013-12-09 14:51:17 +00001364 // The destructor in a virtual table is always a 'deleting'
1365 // destructor, which calls the complete destructor and then uses the
1366 // appropriate operator delete.
1367 if (D->isVirtual())
1368 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001369}
1370
Reid Kleckner89077a12013-12-17 19:46:40 +00001371void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1372 QualType &ResTy,
1373 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001374 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001375 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001376
1377 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001378 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001379 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001380
1381 // FIXME: avoid the fake decl
1382 QualType T = Context.getPointerType(Context.VoidPtrTy);
1383 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001384 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001385 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001386 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001387 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001388 }
1389}
1390
John McCall5d865c322010-08-31 07:33:07 +00001391void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1392 /// Initialize the 'this' slot.
1393 EmitThisParam(CGF);
1394
1395 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001396 if (getStructorImplicitParamDecl(CGF)) {
1397 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1398 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001399 }
John McCall5d865c322010-08-31 07:33:07 +00001400
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001401 /// If this is a function that the ABI specifies returns 'this', initialize
1402 /// the return slot to 'this' at the start of the function.
1403 ///
1404 /// Unlike the setting of return types, this is done within the ABI
1405 /// implementation instead of by clients of CGCXXABI because:
1406 /// 1) getThisValue is currently protected
1407 /// 2) in theory, an ABI could implement 'this' returns some other way;
1408 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001409 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001410 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001411}
1412
Reid Kleckner89077a12013-12-17 19:46:40 +00001413unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1414 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1415 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1416 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1417 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001418
Reid Kleckner89077a12013-12-17 19:46:40 +00001419 // Insert the implicit 'vtt' argument as the second argument.
1420 llvm::Value *VTT =
1421 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1422 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1423 Args.insert(Args.begin() + 1,
1424 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1425 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001426}
1427
1428void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1429 const CXXDestructorDecl *DD,
1430 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001431 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001432 GlobalDecl GD(DD, Type);
1433 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1434 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1435
Craig Topper8a13c412014-05-21 05:09:00 +00001436 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001437 if (getContext().getLangOpts().AppleKext)
1438 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1439
1440 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001441 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001442
John McCall7f416cc2015-09-08 08:05:57 +00001443 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1444 This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001445}
1446
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001447void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1448 const CXXRecordDecl *RD) {
1449 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1450 if (VTable->hasInitializer())
1451 return;
1452
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001453 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001454 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1455 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001456 llvm::Constant *RTTI =
1457 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001458
1459 // Create and set the initializer.
1460 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1461 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001462 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001463 VTable->setInitializer(Init);
1464
1465 // Set the correct linkage.
1466 VTable->setLinkage(Linkage);
1467
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001468 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1469 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001470
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001471 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001472 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001473
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001474 // Use pointer alignment for the vtable. Otherwise we would align them based
1475 // on the size of the initializer which doesn't make sense as only single
1476 // values are read.
1477 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1478 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1479
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001480 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1481 // we will emit the typeinfo for the fundamental types. This is the
1482 // same behaviour as GCC.
1483 const DeclContext *DC = RD->getDeclContext();
1484 if (RD->getIdentifier() &&
1485 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1486 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1487 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1488 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001489 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001490
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001491 if (!VTable->isDeclarationForLinker())
1492 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001493}
1494
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001495bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1496 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1497 if (Vptr.NearestVBase == nullptr)
1498 return false;
1499 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001500}
1501
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001502llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1503 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1504 const CXXRecordDecl *NearestVBase) {
1505
1506 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1507 NeedsVTTParameter(CGF.CurGD)) {
1508 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1509 NearestVBase);
1510 }
1511 return getVTableAddressPoint(Base, VTableClass);
1512}
1513
1514llvm::Constant *
1515ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1516 const CXXRecordDecl *VTableClass) {
1517 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001518
1519 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001520 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1521 .getVTableLayout(VTableClass)
1522 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001523 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001524 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1525 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001526 };
1527
David Blaikiee3b172a2015-04-02 18:55:21 +00001528 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1529 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001530}
1531
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001532llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1533 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1534 const CXXRecordDecl *NearestVBase) {
1535 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1536 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1537
1538 // Get the secondary vpointer index.
1539 uint64_t VirtualPointerIndex =
1540 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1541
1542 /// Load the VTT.
1543 llvm::Value *VTT = CGF.LoadCXXVTT();
1544 if (VirtualPointerIndex)
1545 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1546
1547 // And load the address point from the VTT.
1548 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1549}
1550
1551llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1552 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1553 return getVTableAddressPoint(Base, VTableClass);
1554}
1555
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001556llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1557 CharUnits VPtrOffset) {
1558 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1559
1560 llvm::GlobalVariable *&VTable = VTables[RD];
1561 if (VTable)
1562 return VTable;
1563
Eric Christopherd160c502016-01-29 01:35:53 +00001564 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001565 CGM.addDeferredVTable(RD);
1566
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001567 SmallString<256> Name;
1568 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001569 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001570
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001571 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001572 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1573 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1574
1575 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1576 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1577 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001578
1579 if (RD->hasAttr<DLLImportAttr>())
1580 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1581 else if (RD->hasAttr<DLLExportAttr>())
1582 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1583
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001584 return VTable;
1585}
1586
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001587llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1588 GlobalDecl GD,
John McCall7f416cc2015-09-08 08:05:57 +00001589 Address This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001590 llvm::Type *Ty,
1591 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001592 GD = GD.getCanonicalDecl();
1593 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001594 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1595 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001596
Peter Collingbournefb532b92016-02-24 20:46:36 +00001597 CGF.EmitBitSetCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001598
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001599 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001600 llvm::Value *VFuncPtr =
1601 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Renato Golin41106182015-10-01 12:58:41 +00001602 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001603}
1604
David Majnemer0c0b6d92014-10-31 20:09:12 +00001605llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1606 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001607 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001608 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001609 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1610
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001611 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1612 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001613 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001614 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001615 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1616 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001617
John McCall7f416cc2015-09-08 08:05:57 +00001618 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1619 This.getPointer(), /*ImplicitParam=*/nullptr,
1620 QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001621 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001622}
1623
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001624void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001625 CodeGenVTables &VTables = CGM.getVTables();
1626 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001627 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001628}
1629
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001630bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001631 // We don't emit available_externally vtables if we are in -fapple-kext mode
1632 // because kext mode does not permit devirtualization.
1633 if (CGM.getLangOpts().AppleKext)
1634 return false;
1635
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001636 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001637 // then we are safe to emit available_externally copy of vtable.
1638 // FIXME we can still emit a copy of the vtable if we
1639 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001640 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001641}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001642static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001643 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001644 int64_t NonVirtualAdjustment,
1645 int64_t VirtualAdjustment,
1646 bool IsReturnAdjustment) {
1647 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001648 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001649
John McCall7f416cc2015-09-08 08:05:57 +00001650 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001651
John McCall7f416cc2015-09-08 08:05:57 +00001652 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001653 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001654 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1655 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001656 }
1657
John McCall7f416cc2015-09-08 08:05:57 +00001658 // Perform the virtual adjustment if we have one.
1659 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001660 if (VirtualAdjustment) {
1661 llvm::Type *PtrDiffTy =
1662 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1663
John McCall7f416cc2015-09-08 08:05:57 +00001664 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001665 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1666
1667 llvm::Value *OffsetPtr =
1668 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1669
1670 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1671
1672 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001673 llvm::Value *Offset =
1674 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001675
1676 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001677 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1678 } else {
1679 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001680 }
1681
John McCall7f416cc2015-09-08 08:05:57 +00001682 // In a derived-to-base conversion, the non-virtual adjustment is
1683 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001684 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001685 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1686 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001687 }
1688
1689 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001690 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001691}
1692
1693llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001694 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001695 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001696 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1697 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001698 /*IsReturnAdjustment=*/false);
1699}
1700
1701llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001702ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001703 const ReturnAdjustment &RA) {
1704 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1705 RA.Virtual.Itanium.VBaseOffsetOffset,
1706 /*IsReturnAdjustment=*/true);
1707}
1708
John McCall5d865c322010-08-31 07:33:07 +00001709void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1710 RValue RV, QualType ResultType) {
1711 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1712 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1713
1714 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001715 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001716 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1717 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1718}
John McCall8ed55a52010-09-02 09:58:18 +00001719
1720/************************** Array allocation cookies **************************/
1721
John McCallb91cd662012-05-01 05:23:51 +00001722CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1723 // The array cookie is a size_t; pad that up to the element alignment.
1724 // The cookie is actually right-justified in that space.
1725 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1726 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001727}
1728
John McCall7f416cc2015-09-08 08:05:57 +00001729Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1730 Address NewPtr,
1731 llvm::Value *NumElements,
1732 const CXXNewExpr *expr,
1733 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001734 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001735
John McCall7f416cc2015-09-08 08:05:57 +00001736 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001737
John McCall9bca9232010-09-02 10:25:57 +00001738 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001739 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001740
1741 // The size of the cookie.
1742 CharUnits CookieSize =
1743 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001744 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001745
1746 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001747 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001748 CharUnits CookieOffset = CookieSize - SizeSize;
1749 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001750 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001751
1752 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001753 Address NumElementsPtr =
1754 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001755 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001756
1757 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001758 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001759 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001760 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001761 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1762 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001763 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001764 llvm::Constant *F =
1765 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001766 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001767 }
John McCall8ed55a52010-09-02 09:58:18 +00001768
1769 // Finally, compute a pointer to the actual data buffer by skipping
1770 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001771 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001772}
1773
John McCallb91cd662012-05-01 05:23:51 +00001774llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001775 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001776 CharUnits cookieSize) {
1777 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001778 Address numElementsPtr = allocPtr;
1779 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001780 if (!numElementsOffset.isZero())
1781 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001782 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001783
John McCall7f416cc2015-09-08 08:05:57 +00001784 unsigned AS = allocPtr.getAddressSpace();
1785 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001786 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001787 return CGF.Builder.CreateLoad(numElementsPtr);
1788 // In asan mode emit a function call instead of a regular load and let the
1789 // run-time deal with it: if the shadow is properly poisoned return the
1790 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1791 // We can't simply ignore this load using nosanitize metadata because
1792 // the metadata may be lost.
1793 llvm::FunctionType *FTy =
1794 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1795 llvm::Constant *F =
1796 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001797 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001798}
1799
John McCallb91cd662012-05-01 05:23:51 +00001800CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001801 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001802 // struct array_cookie {
1803 // std::size_t element_size; // element_size != 0
1804 // std::size_t element_count;
1805 // };
John McCallc19c7062013-01-25 23:36:19 +00001806 // But the base ABI doesn't give anything an alignment greater than
1807 // 8, so we can dismiss this as typical ABI-author blindness to
1808 // actual language complexity and round up to the element alignment.
1809 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1810 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001811}
1812
John McCall7f416cc2015-09-08 08:05:57 +00001813Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1814 Address newPtr,
1815 llvm::Value *numElements,
1816 const CXXNewExpr *expr,
1817 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001818 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001819
John McCall8ed55a52010-09-02 09:58:18 +00001820 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001821 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001822
1823 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001824 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001825 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1826 getContext().getTypeSizeInChars(elementType).getQuantity());
1827 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001828
1829 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001830 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001831 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001832
1833 // Finally, compute a pointer to the actual data buffer by skipping
1834 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001835 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001836 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001837}
1838
John McCallb91cd662012-05-01 05:23:51 +00001839llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001840 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001841 CharUnits cookieSize) {
1842 // The number of elements is at offset sizeof(size_t) relative to
1843 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001844 Address numElementsPtr
1845 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001846
John McCall7f416cc2015-09-08 08:05:57 +00001847 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001848 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001849}
1850
John McCall68ff0372010-09-08 01:44:27 +00001851/*********************** Static local initialization **************************/
1852
1853static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001854 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001855 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001856 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001857 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001858 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001859 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001860 llvm::AttributeSet::get(CGM.getLLVMContext(),
1861 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001862 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001863}
1864
1865static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001866 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001867 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001868 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001869 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001870 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001871 llvm::AttributeSet::get(CGM.getLLVMContext(),
1872 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001873 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001874}
1875
1876static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001877 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001878 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001879 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001880 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001881 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001882 llvm::AttributeSet::get(CGM.getLLVMContext(),
1883 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001884 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001885}
1886
1887namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001888 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001889 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001890 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001891
Craig Topper4f12f102014-03-12 06:41:41 +00001892 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001893 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1894 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001895 }
1896 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001897}
John McCall68ff0372010-09-08 01:44:27 +00001898
1899/// The ARM code here follows the Itanium code closely enough that we
1900/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001901void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1902 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001903 llvm::GlobalVariable *var,
1904 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001905 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001906
Richard Smithdbf74ba2013-04-14 23:01:42 +00001907 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001908 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001909 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1910 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001911
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001912 // If we have a global variable with internal linkage and thread-safe statics
1913 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001914 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1915
1916 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001917 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001918 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001919 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001920 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001921 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001922 // Guard variables are 64 bits in the generic ABI and size width on ARM
1923 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001924 if (UseARMGuardVarABI) {
1925 guardTy = CGF.SizeTy;
1926 guardAlignment = CGF.getSizeAlign();
1927 } else {
1928 guardTy = CGF.Int64Ty;
1929 guardAlignment = CharUnits::fromQuantity(
1930 CGM.getDataLayout().getABITypeAlignment(guardTy));
1931 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001932 }
John McCallb88a5662012-03-30 21:00:39 +00001933 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001934
John McCallb88a5662012-03-30 21:00:39 +00001935 // Create the guard variable if we don't already have it (as we
1936 // might if we're double-emitting this function body).
1937 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1938 if (!guard) {
1939 // Mangle the name for the guard.
1940 SmallString<256> guardName;
1941 {
1942 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001943 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001944 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001945
John McCallb88a5662012-03-30 21:00:39 +00001946 // Create the guard variable with a zero-initializer.
1947 // Just absorb linkage and visibility from the guarded variable.
1948 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1949 false, var->getLinkage(),
1950 llvm::ConstantInt::get(guardTy, 0),
1951 guardName.str());
1952 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001953 // If the variable is thread-local, so is its guard variable.
1954 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00001955 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00001956
Yaron Keren5bfa1082015-09-03 20:33:29 +00001957 // The ABI says: "It is suggested that it be emitted in the same COMDAT
1958 // group as the associated data object." In practice, this doesn't work for
1959 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001960 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00001961 if (!D.isLocalVarDecl() && C &&
1962 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001963 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001964 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001965 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1966 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001967 }
1968
John McCallb88a5662012-03-30 21:00:39 +00001969 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1970 }
John McCall87590e62012-03-30 07:09:50 +00001971
John McCall7f416cc2015-09-08 08:05:57 +00001972 Address guardAddr = Address(guard, guardAlignment);
1973
John McCall68ff0372010-09-08 01:44:27 +00001974 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001975 //
John McCall68ff0372010-09-08 01:44:27 +00001976 // Itanium C++ ABI 3.3.2:
1977 // The following is pseudo-code showing how these functions can be used:
1978 // if (obj_guard.first_byte == 0) {
1979 // if ( __cxa_guard_acquire (&obj_guard) ) {
1980 // try {
1981 // ... initialize the object ...;
1982 // } catch (...) {
1983 // __cxa_guard_abort (&obj_guard);
1984 // throw;
1985 // }
1986 // ... queue object destructor with __cxa_atexit() ...;
1987 // __cxa_guard_release (&obj_guard);
1988 // }
1989 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001990
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001991 // Load the first byte of the guard variable.
1992 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00001993 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00001994
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001995 // Itanium ABI:
1996 // An implementation supporting thread-safety on multiprocessor
1997 // systems must also guarantee that references to the initialized
1998 // object do not occur before the load of the initialization flag.
1999 //
2000 // In LLVM, we do this by marking the load Acquire.
2001 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002002 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002003
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002004 // For ARM, we should only check the first bit, rather than the entire byte:
2005 //
2006 // ARM C++ ABI 3.2.3.1:
2007 // To support the potential use of initialization guard variables
2008 // as semaphores that are the target of ARM SWP and LDREX/STREX
2009 // synchronizing instructions we define a static initialization
2010 // guard variable to be a 4-byte aligned, 4-byte word with the
2011 // following inline access protocol.
2012 // #define INITIALIZED 1
2013 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2014 // if (__cxa_guard_acquire(&obj_guard))
2015 // ...
2016 // }
2017 //
2018 // and similarly for ARM64:
2019 //
2020 // ARM64 C++ ABI 3.2.2:
2021 // This ABI instead only specifies the value bit 0 of the static guard
2022 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2023 // variable is not initialized and 1 when it is.
2024 llvm::Value *V =
2025 (UseARMGuardVarABI && !useInt8GuardVariable)
2026 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2027 : LI;
2028 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002029
2030 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2031 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2032
2033 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002034 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002035
2036 CGF.EmitBlock(InitCheckBlock);
2037
2038 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002039 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002040 // Call __cxa_guard_acquire.
2041 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002042 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002043
2044 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2045
2046 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2047 InitBlock, EndBlock);
2048
2049 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002050 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002051
2052 CGF.EmitBlock(InitBlock);
2053 }
2054
2055 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002056 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002057
John McCall5aa52592011-06-17 07:33:57 +00002058 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002059 // Pop the guard-abort cleanup if we pushed one.
2060 CGF.PopCleanupBlock();
2061
2062 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002063 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2064 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002065 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002066 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002067 }
2068
2069 CGF.EmitBlock(EndBlock);
2070}
John McCallc84ed6a2012-05-01 06:13:13 +00002071
2072/// Register a global destructor using __cxa_atexit.
2073static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2074 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002075 llvm::Constant *addr,
2076 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002077 const char *Name = "__cxa_atexit";
2078 if (TLS) {
2079 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002080 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002081 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002082
John McCallc84ed6a2012-05-01 06:13:13 +00002083 // We're assuming that the destructor function is something we can
2084 // reasonably call with the default CC. Go ahead and cast it to the
2085 // right prototype.
2086 llvm::Type *dtorTy =
2087 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2088
2089 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2090 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2091 llvm::FunctionType *atexitTy =
2092 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2093
2094 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002095 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002096 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2097 fn->setDoesNotThrow();
2098
2099 // Create a variable that binds the atexit to this shared object.
2100 llvm::Constant *handle =
2101 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2102
2103 llvm::Value *args[] = {
2104 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2105 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2106 handle
2107 };
John McCall882987f2013-02-28 19:01:20 +00002108 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002109}
2110
2111/// Register a global destructor as best as we know how.
2112void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002113 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002114 llvm::Constant *dtor,
2115 llvm::Constant *addr) {
2116 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002117 if (CGM.getCodeGenOpts().CXAAtExit)
2118 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2119
2120 if (D.getTLSKind())
2121 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002122
2123 // In Apple kexts, we want to add a global destructor entry.
2124 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002125 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002126 // Generate a global destructor entry.
2127 return CGM.AddCXXDtorEntry(dtor, addr);
2128 }
2129
David Blaikieebe87e12013-08-27 23:57:18 +00002130 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002131}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002132
David Majnemer9b21c332014-07-11 20:28:10 +00002133static bool isThreadWrapperReplaceable(const VarDecl *VD,
2134 CodeGen::CodeGenModule &CGM) {
2135 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002136 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002137 // the thread wrapper instead of directly referencing the backing variable.
2138 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002139 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002140}
2141
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002142/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002143/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002144/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002145static llvm::GlobalValue::LinkageTypes
2146getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2147 llvm::GlobalValue::LinkageTypes VarLinkage =
2148 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2149
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002150 // For internal linkage variables, we don't need an external or weak wrapper.
2151 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2152 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002153
David Majnemer9b21c332014-07-11 20:28:10 +00002154 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002155 if (isThreadWrapperReplaceable(VD, CGM))
2156 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2157 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2158 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002159 return llvm::GlobalValue::WeakODRLinkage;
2160}
2161
2162llvm::Function *
2163ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002164 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002165 // Mangle the name for the thread_local wrapper function.
2166 SmallString<256> WrapperName;
2167 {
2168 llvm::raw_svector_ostream Out(WrapperName);
2169 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002170 }
2171
Akira Hatanaka26907f92016-01-15 03:34:06 +00002172 // FIXME: If VD is a definition, we should regenerate the function attributes
2173 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002174 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002175 return cast<llvm::Function>(V);
2176
Akira Hatanaka26907f92016-01-15 03:34:06 +00002177 QualType RetQT = VD->getType();
2178 if (RetQT->isReferenceType())
2179 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002180
John McCallc56a8b32016-03-11 04:30:31 +00002181 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2182 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002183
2184 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002185 llvm::Function *Wrapper =
2186 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2187 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002188
2189 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2190
2191 if (VD->hasDefinition())
2192 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2193
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002194 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002195 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2196 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2197 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002198 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002199
2200 if (isThreadWrapperReplaceable(VD, CGM)) {
2201 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2202 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2203 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002204 return Wrapper;
2205}
2206
2207void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002208 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2209 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2210 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002211 llvm::Function *InitFunc = nullptr;
2212 if (!CXXThreadLocalInits.empty()) {
2213 // Generate a guarded initialization function.
2214 llvm::FunctionType *FTy =
2215 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002216 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2217 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002218 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002219 /*TLS=*/true);
2220 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2221 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2222 llvm::GlobalVariable::InternalLinkage,
2223 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2224 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002225
2226 CharUnits GuardAlign = CharUnits::One();
2227 Guard->setAlignment(GuardAlign.getQuantity());
2228
David Majnemerb3341ea2014-10-05 05:05:40 +00002229 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002230 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2231 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002232 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2233 if (CGM.getTarget().getTriple().isOSDarwin()) {
2234 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2235 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2236 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002237 }
Richard Smith5a99c492015-12-01 01:10:48 +00002238 for (const VarDecl *VD : CXXThreadLocals) {
2239 llvm::GlobalVariable *Var =
2240 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002241
David Majnemer9b21c332014-07-11 20:28:10 +00002242 // Some targets require that all access to thread local variables go through
2243 // the thread wrapper. This means that we cannot attempt to create a thread
2244 // wrapper or a thread helper.
2245 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2246 continue;
2247
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002248 // Mangle the name for the thread_local initialization function.
2249 SmallString<256> InitFnName;
2250 {
2251 llvm::raw_svector_ostream Out(InitFnName);
2252 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002253 }
2254
2255 // If we have a definition for the variable, emit the initialization
2256 // function as an alias to the global Init function (if any). Otherwise,
2257 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002258 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002259 bool InitIsInitFunc = false;
2260 if (VD->hasDefinition()) {
2261 InitIsInitFunc = true;
2262 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002263 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2264 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002265 } else {
2266 // Emit a weak global function referring to the initialization function.
2267 // This function will not exist if the TU defining the thread_local
2268 // variable in question does not need any dynamic initialization for
2269 // its thread_local variables.
2270 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2271 Init = llvm::Function::Create(
2272 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2273 &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002274 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002275 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002276 }
2277
2278 if (Init)
2279 Init->setVisibility(Var->getVisibility());
2280
2281 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2282 llvm::LLVMContext &Context = CGM.getModule().getContext();
2283 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002284 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002285 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002286 if (Init) {
2287 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2288 if (isThreadWrapperReplaceable(VD, CGM))
2289 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2290 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002291 } else {
2292 // Don't know whether we have an init function. Call it if it exists.
2293 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2294 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2295 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2296 Builder.CreateCondBr(Have, InitBB, ExitBB);
2297
2298 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002299 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002300 Builder.CreateBr(ExitBB);
2301
2302 Builder.SetInsertPoint(ExitBB);
2303 }
2304
2305 // For a reference, the result of the wrapper function is a pointer to
2306 // the referenced object.
2307 llvm::Value *Val = Var;
2308 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002309 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2310 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002311 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002312 if (Val->getType() != Wrapper->getReturnType())
2313 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2314 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002315 Builder.CreateRet(Val);
2316 }
2317}
2318
Richard Smith0f383742014-03-26 22:48:22 +00002319LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2320 const VarDecl *VD,
2321 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002322 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002323 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002324
Manman Renb0b3af72015-12-17 00:42:36 +00002325 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
2326 if (isThreadWrapperReplaceable(VD, CGF.CGM))
2327 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002328
2329 LValue LV;
2330 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002331 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002332 else
Manman Renb0b3af72015-12-17 00:42:36 +00002333 LV = CGF.MakeAddrLValue(CallVal, LValType,
2334 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002335 // FIXME: need setObjCGCLValueClass?
2336 return LV;
2337}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002338
2339/// Return whether the given global decl needs a VTT parameter, which it does
2340/// if it's a base constructor or destructor with virtual bases.
2341bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2342 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2343
2344 // We don't have any virtual bases, just return early.
2345 if (!MD->getParent()->getNumVBases())
2346 return false;
2347
2348 // Check if we have a base constructor.
2349 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2350 return true;
2351
2352 // Check if we have a base destructor.
2353 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2354 return true;
2355
2356 return false;
2357}
David Majnemere2cb8d12014-07-07 06:20:47 +00002358
2359namespace {
2360class ItaniumRTTIBuilder {
2361 CodeGenModule &CGM; // Per-module state.
2362 llvm::LLVMContext &VMContext;
2363 const ItaniumCXXABI &CXXABI; // Per-module state.
2364
2365 /// Fields - The fields of the RTTI descriptor currently being built.
2366 SmallVector<llvm::Constant *, 16> Fields;
2367
2368 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2369 llvm::GlobalVariable *
2370 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2371
2372 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2373 /// descriptor of the given type.
2374 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2375
2376 /// BuildVTablePointer - Build the vtable pointer for the given type.
2377 void BuildVTablePointer(const Type *Ty);
2378
2379 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2380 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2381 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2382
2383 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2384 /// classes with bases that do not satisfy the abi::__si_class_type_info
2385 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2386 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2387
2388 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2389 /// for pointer types.
2390 void BuildPointerTypeInfo(QualType PointeeTy);
2391
2392 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2393 /// type_info for an object type.
2394 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2395
2396 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2397 /// struct, used for member pointer types.
2398 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2399
2400public:
2401 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2402 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2403
2404 // Pointer type info flags.
2405 enum {
2406 /// PTI_Const - Type has const qualifier.
2407 PTI_Const = 0x1,
2408
2409 /// PTI_Volatile - Type has volatile qualifier.
2410 PTI_Volatile = 0x2,
2411
2412 /// PTI_Restrict - Type has restrict qualifier.
2413 PTI_Restrict = 0x4,
2414
2415 /// PTI_Incomplete - Type is incomplete.
2416 PTI_Incomplete = 0x8,
2417
2418 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2419 /// (in pointer to member).
2420 PTI_ContainingClassIncomplete = 0x10
2421 };
2422
2423 // VMI type info flags.
2424 enum {
2425 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2426 VMI_NonDiamondRepeat = 0x1,
2427
2428 /// VMI_DiamondShaped - Class is diamond shaped.
2429 VMI_DiamondShaped = 0x2
2430 };
2431
2432 // Base class type info flags.
2433 enum {
2434 /// BCTI_Virtual - Base class is virtual.
2435 BCTI_Virtual = 0x1,
2436
2437 /// BCTI_Public - Base class is public.
2438 BCTI_Public = 0x2
2439 };
2440
2441 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2442 ///
2443 /// \param Force - true to force the creation of this RTTI value
2444 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2445};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002446}
David Majnemere2cb8d12014-07-07 06:20:47 +00002447
2448llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2449 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002450 SmallString<256> Name;
2451 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002452 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002453
2454 // We know that the mangled name of the type starts at index 4 of the
2455 // mangled name of the typename, so we can just index into it in order to
2456 // get the mangled name of the type.
2457 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2458 Name.substr(4));
2459
2460 llvm::GlobalVariable *GV =
2461 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2462
2463 GV->setInitializer(Init);
2464
2465 return GV;
2466}
2467
2468llvm::Constant *
2469ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2470 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002471 SmallString<256> Name;
2472 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002473 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002474
2475 // Look for an existing global.
2476 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2477
2478 if (!GV) {
2479 // Create a new global variable.
2480 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2481 /*Constant=*/true,
2482 llvm::GlobalValue::ExternalLinkage, nullptr,
2483 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002484 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2485 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2486 if (RD->hasAttr<DLLImportAttr>())
2487 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2488 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002489 }
2490
2491 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2492}
2493
2494/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2495/// info for that type is defined in the standard library.
2496static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2497 // Itanium C++ ABI 2.9.2:
2498 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2499 // the run-time support library. Specifically, the run-time support
2500 // library should contain type_info objects for the types X, X* and
2501 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2502 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2503 // long, unsigned long, long long, unsigned long long, float, double,
2504 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2505 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002506 //
2507 // GCC also emits RTTI for __int128.
2508 // FIXME: We do not emit RTTI information for decimal types here.
2509
2510 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002511 switch (Ty->getKind()) {
2512 case BuiltinType::Void:
2513 case BuiltinType::NullPtr:
2514 case BuiltinType::Bool:
2515 case BuiltinType::WChar_S:
2516 case BuiltinType::WChar_U:
2517 case BuiltinType::Char_U:
2518 case BuiltinType::Char_S:
2519 case BuiltinType::UChar:
2520 case BuiltinType::SChar:
2521 case BuiltinType::Short:
2522 case BuiltinType::UShort:
2523 case BuiltinType::Int:
2524 case BuiltinType::UInt:
2525 case BuiltinType::Long:
2526 case BuiltinType::ULong:
2527 case BuiltinType::LongLong:
2528 case BuiltinType::ULongLong:
2529 case BuiltinType::Half:
2530 case BuiltinType::Float:
2531 case BuiltinType::Double:
2532 case BuiltinType::LongDouble:
2533 case BuiltinType::Char16:
2534 case BuiltinType::Char32:
2535 case BuiltinType::Int128:
2536 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002537 return true;
2538
Alexey Bader954ba212016-04-08 13:40:33 +00002539#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2540 case BuiltinType::Id:
2541#include "clang/AST/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002542 case BuiltinType::OCLSampler:
2543 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002544 case BuiltinType::OCLClkEvent:
2545 case BuiltinType::OCLQueue:
2546 case BuiltinType::OCLNDRange:
2547 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002548 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002549
2550 case BuiltinType::Dependent:
2551#define BUILTIN_TYPE(Id, SingletonId)
2552#define PLACEHOLDER_TYPE(Id, SingletonId) \
2553 case BuiltinType::Id:
2554#include "clang/AST/BuiltinTypes.def"
2555 llvm_unreachable("asking for RRTI for a placeholder type!");
2556
2557 case BuiltinType::ObjCId:
2558 case BuiltinType::ObjCClass:
2559 case BuiltinType::ObjCSel:
2560 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2561 }
2562
2563 llvm_unreachable("Invalid BuiltinType Kind!");
2564}
2565
2566static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2567 QualType PointeeTy = PointerTy->getPointeeType();
2568 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2569 if (!BuiltinTy)
2570 return false;
2571
2572 // Check the qualifiers.
2573 Qualifiers Quals = PointeeTy.getQualifiers();
2574 Quals.removeConst();
2575
2576 if (!Quals.empty())
2577 return false;
2578
2579 return TypeInfoIsInStandardLibrary(BuiltinTy);
2580}
2581
2582/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2583/// information for the given type exists in the standard library.
2584static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2585 // Type info for builtin types is defined in the standard library.
2586 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2587 return TypeInfoIsInStandardLibrary(BuiltinTy);
2588
2589 // Type info for some pointer types to builtin types is defined in the
2590 // standard library.
2591 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2592 return TypeInfoIsInStandardLibrary(PointerTy);
2593
2594 return false;
2595}
2596
2597/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2598/// the given type exists somewhere else, and that we should not emit the type
2599/// information in this translation unit. Assumes that it is not a
2600/// standard-library type.
2601static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2602 QualType Ty) {
2603 ASTContext &Context = CGM.getContext();
2604
2605 // If RTTI is disabled, assume it might be disabled in the
2606 // translation unit that defines any potential key function, too.
2607 if (!Context.getLangOpts().RTTI) return false;
2608
2609 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2610 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2611 if (!RD->hasDefinition())
2612 return false;
2613
2614 if (!RD->isDynamicClass())
2615 return false;
2616
2617 // FIXME: this may need to be reconsidered if the key function
2618 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002619 // N.B. We must always emit the RTTI data ourselves if there exists a key
2620 // function.
2621 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002622 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002623 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002624
David Majnemerbe9022c2015-08-06 20:56:55 +00002625 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002626 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002627 }
2628
2629 return false;
2630}
2631
2632/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2633static bool IsIncompleteClassType(const RecordType *RecordTy) {
2634 return !RecordTy->getDecl()->isCompleteDefinition();
2635}
2636
2637/// ContainsIncompleteClassType - Returns whether the given type contains an
2638/// incomplete class type. This is true if
2639///
2640/// * The given type is an incomplete class type.
2641/// * The given type is a pointer type whose pointee type contains an
2642/// incomplete class type.
2643/// * The given type is a member pointer type whose class is an incomplete
2644/// class type.
2645/// * The given type is a member pointer type whoise pointee type contains an
2646/// incomplete class type.
2647/// is an indirect or direct pointer to an incomplete class type.
2648static bool ContainsIncompleteClassType(QualType Ty) {
2649 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2650 if (IsIncompleteClassType(RecordTy))
2651 return true;
2652 }
2653
2654 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2655 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2656
2657 if (const MemberPointerType *MemberPointerTy =
2658 dyn_cast<MemberPointerType>(Ty)) {
2659 // Check if the class type is incomplete.
2660 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2661 if (IsIncompleteClassType(ClassType))
2662 return true;
2663
2664 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2665 }
2666
2667 return false;
2668}
2669
2670// CanUseSingleInheritance - Return whether the given record decl has a "single,
2671// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2672// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2673static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2674 // Check the number of bases.
2675 if (RD->getNumBases() != 1)
2676 return false;
2677
2678 // Get the base.
2679 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2680
2681 // Check that the base is not virtual.
2682 if (Base->isVirtual())
2683 return false;
2684
2685 // Check that the base is public.
2686 if (Base->getAccessSpecifier() != AS_public)
2687 return false;
2688
2689 // Check that the class is dynamic iff the base is.
2690 const CXXRecordDecl *BaseDecl =
2691 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2692 if (!BaseDecl->isEmpty() &&
2693 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2694 return false;
2695
2696 return true;
2697}
2698
2699void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2700 // abi::__class_type_info.
2701 static const char * const ClassTypeInfo =
2702 "_ZTVN10__cxxabiv117__class_type_infoE";
2703 // abi::__si_class_type_info.
2704 static const char * const SIClassTypeInfo =
2705 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2706 // abi::__vmi_class_type_info.
2707 static const char * const VMIClassTypeInfo =
2708 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2709
2710 const char *VTableName = nullptr;
2711
2712 switch (Ty->getTypeClass()) {
2713#define TYPE(Class, Base)
2714#define ABSTRACT_TYPE(Class, Base)
2715#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2716#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2717#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2718#include "clang/AST/TypeNodes.def"
2719 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2720
2721 case Type::LValueReference:
2722 case Type::RValueReference:
2723 llvm_unreachable("References shouldn't get here");
2724
2725 case Type::Auto:
2726 llvm_unreachable("Undeduced auto type shouldn't get here");
2727
Xiuli Pan9c14e282016-01-09 12:53:17 +00002728 case Type::Pipe:
2729 llvm_unreachable("Pipe types shouldn't get here");
2730
David Majnemere2cb8d12014-07-07 06:20:47 +00002731 case Type::Builtin:
2732 // GCC treats vector and complex types as fundamental types.
2733 case Type::Vector:
2734 case Type::ExtVector:
2735 case Type::Complex:
2736 case Type::Atomic:
2737 // FIXME: GCC treats block pointers as fundamental types?!
2738 case Type::BlockPointer:
2739 // abi::__fundamental_type_info.
2740 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2741 break;
2742
2743 case Type::ConstantArray:
2744 case Type::IncompleteArray:
2745 case Type::VariableArray:
2746 // abi::__array_type_info.
2747 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2748 break;
2749
2750 case Type::FunctionNoProto:
2751 case Type::FunctionProto:
2752 // abi::__function_type_info.
2753 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2754 break;
2755
2756 case Type::Enum:
2757 // abi::__enum_type_info.
2758 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2759 break;
2760
2761 case Type::Record: {
2762 const CXXRecordDecl *RD =
2763 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2764
2765 if (!RD->hasDefinition() || !RD->getNumBases()) {
2766 VTableName = ClassTypeInfo;
2767 } else if (CanUseSingleInheritance(RD)) {
2768 VTableName = SIClassTypeInfo;
2769 } else {
2770 VTableName = VMIClassTypeInfo;
2771 }
2772
2773 break;
2774 }
2775
2776 case Type::ObjCObject:
2777 // Ignore protocol qualifiers.
2778 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2779
2780 // Handle id and Class.
2781 if (isa<BuiltinType>(Ty)) {
2782 VTableName = ClassTypeInfo;
2783 break;
2784 }
2785
2786 assert(isa<ObjCInterfaceType>(Ty));
2787 // Fall through.
2788
2789 case Type::ObjCInterface:
2790 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2791 VTableName = SIClassTypeInfo;
2792 } else {
2793 VTableName = ClassTypeInfo;
2794 }
2795 break;
2796
2797 case Type::ObjCObjectPointer:
2798 case Type::Pointer:
2799 // abi::__pointer_type_info.
2800 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2801 break;
2802
2803 case Type::MemberPointer:
2804 // abi::__pointer_to_member_type_info.
2805 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2806 break;
2807 }
2808
2809 llvm::Constant *VTable =
2810 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2811
2812 llvm::Type *PtrDiffTy =
2813 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2814
2815 // The vtable address point is 2.
2816 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002817 VTable =
2818 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002819 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2820
2821 Fields.push_back(VTable);
2822}
2823
2824/// \brief Return the linkage that the type info and type info name constants
2825/// should have for the given type.
2826static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2827 QualType Ty) {
2828 // Itanium C++ ABI 2.9.5p7:
2829 // In addition, it and all of the intermediate abi::__pointer_type_info
2830 // structs in the chain down to the abi::__class_type_info for the
2831 // incomplete class type must be prevented from resolving to the
2832 // corresponding type_info structs for the complete class type, possibly
2833 // by making them local static objects. Finally, a dummy class RTTI is
2834 // generated for the incomplete type that will not resolve to the final
2835 // complete class RTTI (because the latter need not exist), possibly by
2836 // making it a local static object.
2837 if (ContainsIncompleteClassType(Ty))
2838 return llvm::GlobalValue::InternalLinkage;
2839
2840 switch (Ty->getLinkage()) {
2841 case NoLinkage:
2842 case InternalLinkage:
2843 case UniqueExternalLinkage:
2844 return llvm::GlobalValue::InternalLinkage;
2845
2846 case VisibleNoLinkage:
2847 case ExternalLinkage:
2848 if (!CGM.getLangOpts().RTTI) {
2849 // RTTI is not enabled, which means that this type info struct is going
2850 // to be used for exception handling. Give it linkonce_odr linkage.
2851 return llvm::GlobalValue::LinkOnceODRLinkage;
2852 }
2853
2854 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2855 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2856 if (RD->hasAttr<WeakAttr>())
2857 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002858 if (RD->isDynamicClass()) {
2859 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2860 // MinGW won't export the RTTI information when there is a key function.
2861 // Make sure we emit our own copy instead of attempting to dllimport it.
2862 if (RD->hasAttr<DLLImportAttr>() &&
2863 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2864 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2865 return LT;
2866 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002867 }
2868
2869 return llvm::GlobalValue::LinkOnceODRLinkage;
2870 }
2871
2872 llvm_unreachable("Invalid linkage!");
2873}
2874
2875llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2876 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002877 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002878
2879 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002880 SmallString<256> Name;
2881 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002882 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002883
2884 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2885 if (OldGV && !OldGV->isDeclaration()) {
2886 assert(!OldGV->hasAvailableExternallyLinkage() &&
2887 "available_externally typeinfos not yet implemented");
2888
2889 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2890 }
2891
2892 // Check if there is already an external RTTI descriptor for this type.
2893 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2894 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2895 return GetAddrOfExternalRTTIDescriptor(Ty);
2896
2897 // Emit the standard library with external linkage.
2898 llvm::GlobalVariable::LinkageTypes Linkage;
2899 if (IsStdLib)
2900 Linkage = llvm::GlobalValue::ExternalLinkage;
2901 else
2902 Linkage = getTypeInfoLinkage(CGM, Ty);
2903
2904 // Add the vtable pointer.
2905 BuildVTablePointer(cast<Type>(Ty));
2906
2907 // And the name.
2908 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2909 llvm::Constant *TypeNameField;
2910
2911 // If we're supposed to demote the visibility, be sure to set a flag
2912 // to use a string comparison for type_info comparisons.
2913 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2914 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2915 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2916 // The flag is the sign bit, which on ARM64 is defined to be clear
2917 // for global pointers. This is very ARM64-specific.
2918 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2919 llvm::Constant *flag =
2920 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2921 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2922 TypeNameField =
2923 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2924 } else {
2925 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2926 }
2927 Fields.push_back(TypeNameField);
2928
2929 switch (Ty->getTypeClass()) {
2930#define TYPE(Class, Base)
2931#define ABSTRACT_TYPE(Class, Base)
2932#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2933#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2934#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2935#include "clang/AST/TypeNodes.def"
2936 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2937
2938 // GCC treats vector types as fundamental types.
2939 case Type::Builtin:
2940 case Type::Vector:
2941 case Type::ExtVector:
2942 case Type::Complex:
2943 case Type::BlockPointer:
2944 // Itanium C++ ABI 2.9.5p4:
2945 // abi::__fundamental_type_info adds no data members to std::type_info.
2946 break;
2947
2948 case Type::LValueReference:
2949 case Type::RValueReference:
2950 llvm_unreachable("References shouldn't get here");
2951
2952 case Type::Auto:
2953 llvm_unreachable("Undeduced auto type shouldn't get here");
2954
Xiuli Pan9c14e282016-01-09 12:53:17 +00002955 case Type::Pipe:
2956 llvm_unreachable("Pipe type shouldn't get here");
2957
David Majnemere2cb8d12014-07-07 06:20:47 +00002958 case Type::ConstantArray:
2959 case Type::IncompleteArray:
2960 case Type::VariableArray:
2961 // Itanium C++ ABI 2.9.5p5:
2962 // abi::__array_type_info adds no data members to std::type_info.
2963 break;
2964
2965 case Type::FunctionNoProto:
2966 case Type::FunctionProto:
2967 // Itanium C++ ABI 2.9.5p5:
2968 // abi::__function_type_info adds no data members to std::type_info.
2969 break;
2970
2971 case Type::Enum:
2972 // Itanium C++ ABI 2.9.5p5:
2973 // abi::__enum_type_info adds no data members to std::type_info.
2974 break;
2975
2976 case Type::Record: {
2977 const CXXRecordDecl *RD =
2978 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2979 if (!RD->hasDefinition() || !RD->getNumBases()) {
2980 // We don't need to emit any fields.
2981 break;
2982 }
2983
2984 if (CanUseSingleInheritance(RD))
2985 BuildSIClassTypeInfo(RD);
2986 else
2987 BuildVMIClassTypeInfo(RD);
2988
2989 break;
2990 }
2991
2992 case Type::ObjCObject:
2993 case Type::ObjCInterface:
2994 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2995 break;
2996
2997 case Type::ObjCObjectPointer:
2998 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2999 break;
3000
3001 case Type::Pointer:
3002 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3003 break;
3004
3005 case Type::MemberPointer:
3006 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3007 break;
3008
3009 case Type::Atomic:
3010 // No fields, at least for the moment.
3011 break;
3012 }
3013
3014 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3015
Rafael Espindolacb92c192015-01-15 23:18:01 +00003016 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003017 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003018 new llvm::GlobalVariable(M, Init->getType(),
3019 /*Constant=*/true, Linkage, Init, Name);
3020
David Majnemere2cb8d12014-07-07 06:20:47 +00003021 // If there's already an old global variable, replace it with the new one.
3022 if (OldGV) {
3023 GV->takeName(OldGV);
3024 llvm::Constant *NewPtr =
3025 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3026 OldGV->replaceAllUsesWith(NewPtr);
3027 OldGV->eraseFromParent();
3028 }
3029
Yaron Keren04da2382015-07-29 15:42:28 +00003030 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3031 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3032
David Majnemere2cb8d12014-07-07 06:20:47 +00003033 // The Itanium ABI specifies that type_info objects must be globally
3034 // unique, with one exception: if the type is an incomplete class
3035 // type or a (possibly indirect) pointer to one. That exception
3036 // affects the general case of comparing type_info objects produced
3037 // by the typeid operator, which is why the comparison operators on
3038 // std::type_info generally use the type_info name pointers instead
3039 // of the object addresses. However, the language's built-in uses
3040 // of RTTI generally require class types to be complete, even when
3041 // manipulating pointers to those class types. This allows the
3042 // implementation of dynamic_cast to rely on address equality tests,
3043 // which is much faster.
3044
3045 // All of this is to say that it's important that both the type_info
3046 // object and the type_info name be uniqued when weakly emitted.
3047
3048 // Give the type_info object and name the formal visibility of the
3049 // type itself.
3050 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3051 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3052 // If the linkage is local, only default visibility makes sense.
3053 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3054 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3055 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3056 else
3057 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3058 TypeName->setVisibility(llvmVisibility);
3059 GV->setVisibility(llvmVisibility);
3060
3061 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3062}
3063
3064/// ComputeQualifierFlags - Compute the pointer type info flags from the
3065/// given qualifier.
3066static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3067 unsigned Flags = 0;
3068
3069 if (Quals.hasConst())
3070 Flags |= ItaniumRTTIBuilder::PTI_Const;
3071 if (Quals.hasVolatile())
3072 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3073 if (Quals.hasRestrict())
3074 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3075
3076 return Flags;
3077}
3078
3079/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3080/// for the given Objective-C object type.
3081void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3082 // Drop qualifiers.
3083 const Type *T = OT->getBaseType().getTypePtr();
3084 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3085
3086 // The builtin types are abi::__class_type_infos and don't require
3087 // extra fields.
3088 if (isa<BuiltinType>(T)) return;
3089
3090 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3091 ObjCInterfaceDecl *Super = Class->getSuperClass();
3092
3093 // Root classes are also __class_type_info.
3094 if (!Super) return;
3095
3096 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3097
3098 // Everything else is single inheritance.
3099 llvm::Constant *BaseTypeInfo =
3100 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3101 Fields.push_back(BaseTypeInfo);
3102}
3103
3104/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3105/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3106void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3107 // Itanium C++ ABI 2.9.5p6b:
3108 // It adds to abi::__class_type_info a single member pointing to the
3109 // type_info structure for the base type,
3110 llvm::Constant *BaseTypeInfo =
3111 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3112 Fields.push_back(BaseTypeInfo);
3113}
3114
3115namespace {
3116 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3117 /// a class hierarchy.
3118 struct SeenBases {
3119 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3120 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3121 };
3122}
3123
3124/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3125/// abi::__vmi_class_type_info.
3126///
3127static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3128 SeenBases &Bases) {
3129
3130 unsigned Flags = 0;
3131
3132 const CXXRecordDecl *BaseDecl =
3133 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3134
3135 if (Base->isVirtual()) {
3136 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003137 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003138 // If this virtual base has been seen before, then the class is diamond
3139 // shaped.
3140 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3141 } else {
3142 if (Bases.NonVirtualBases.count(BaseDecl))
3143 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3144 }
3145 } else {
3146 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003147 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003148 // If this non-virtual base has been seen before, then the class has non-
3149 // diamond shaped repeated inheritance.
3150 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3151 } else {
3152 if (Bases.VirtualBases.count(BaseDecl))
3153 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3154 }
3155 }
3156
3157 // Walk all bases.
3158 for (const auto &I : BaseDecl->bases())
3159 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3160
3161 return Flags;
3162}
3163
3164static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3165 unsigned Flags = 0;
3166 SeenBases Bases;
3167
3168 // Walk all bases.
3169 for (const auto &I : RD->bases())
3170 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3171
3172 return Flags;
3173}
3174
3175/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3176/// classes with bases that do not satisfy the abi::__si_class_type_info
3177/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3178void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3179 llvm::Type *UnsignedIntLTy =
3180 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3181
3182 // Itanium C++ ABI 2.9.5p6c:
3183 // __flags is a word with flags describing details about the class
3184 // structure, which may be referenced by using the __flags_masks
3185 // enumeration. These flags refer to both direct and indirect bases.
3186 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3187 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3188
3189 // Itanium C++ ABI 2.9.5p6c:
3190 // __base_count is a word with the number of direct proper base class
3191 // descriptions that follow.
3192 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3193
3194 if (!RD->getNumBases())
3195 return;
3196
3197 llvm::Type *LongLTy =
3198 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3199
3200 // Now add the base class descriptions.
3201
3202 // Itanium C++ ABI 2.9.5p6c:
3203 // __base_info[] is an array of base class descriptions -- one for every
3204 // direct proper base. Each description is of the type:
3205 //
3206 // struct abi::__base_class_type_info {
3207 // public:
3208 // const __class_type_info *__base_type;
3209 // long __offset_flags;
3210 //
3211 // enum __offset_flags_masks {
3212 // __virtual_mask = 0x1,
3213 // __public_mask = 0x2,
3214 // __offset_shift = 8
3215 // };
3216 // };
3217 for (const auto &Base : RD->bases()) {
3218 // The __base_type member points to the RTTI for the base type.
3219 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3220
3221 const CXXRecordDecl *BaseDecl =
3222 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3223
3224 int64_t OffsetFlags = 0;
3225
3226 // All but the lower 8 bits of __offset_flags are a signed offset.
3227 // For a non-virtual base, this is the offset in the object of the base
3228 // subobject. For a virtual base, this is the offset in the virtual table of
3229 // the virtual base offset for the virtual base referenced (negative).
3230 CharUnits Offset;
3231 if (Base.isVirtual())
3232 Offset =
3233 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3234 else {
3235 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3236 Offset = Layout.getBaseClassOffset(BaseDecl);
3237 };
3238
3239 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3240
3241 // The low-order byte of __offset_flags contains flags, as given by the
3242 // masks from the enumeration __offset_flags_masks.
3243 if (Base.isVirtual())
3244 OffsetFlags |= BCTI_Virtual;
3245 if (Base.getAccessSpecifier() == AS_public)
3246 OffsetFlags |= BCTI_Public;
3247
3248 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3249 }
3250}
3251
3252/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3253/// used for pointer types.
3254void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3255 Qualifiers Quals;
3256 QualType UnqualifiedPointeeTy =
3257 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3258
3259 // Itanium C++ ABI 2.9.5p7:
3260 // __flags is a flag word describing the cv-qualification and other
3261 // attributes of the type pointed to
3262 unsigned Flags = ComputeQualifierFlags(Quals);
3263
3264 // Itanium C++ ABI 2.9.5p7:
3265 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3266 // incomplete class type, the incomplete target type flag is set.
3267 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3268 Flags |= PTI_Incomplete;
3269
3270 llvm::Type *UnsignedIntLTy =
3271 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3272 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3273
3274 // Itanium C++ ABI 2.9.5p7:
3275 // __pointee is a pointer to the std::type_info derivation for the
3276 // unqualified type being pointed to.
3277 llvm::Constant *PointeeTypeInfo =
3278 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3279 Fields.push_back(PointeeTypeInfo);
3280}
3281
3282/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3283/// struct, used for member pointer types.
3284void
3285ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3286 QualType PointeeTy = Ty->getPointeeType();
3287
3288 Qualifiers Quals;
3289 QualType UnqualifiedPointeeTy =
3290 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3291
3292 // Itanium C++ ABI 2.9.5p7:
3293 // __flags is a flag word describing the cv-qualification and other
3294 // attributes of the type pointed to.
3295 unsigned Flags = ComputeQualifierFlags(Quals);
3296
3297 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3298
3299 // Itanium C++ ABI 2.9.5p7:
3300 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3301 // incomplete class type, the incomplete target type flag is set.
3302 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3303 Flags |= PTI_Incomplete;
3304
3305 if (IsIncompleteClassType(ClassType))
3306 Flags |= PTI_ContainingClassIncomplete;
3307
3308 llvm::Type *UnsignedIntLTy =
3309 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3310 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3311
3312 // Itanium C++ ABI 2.9.5p7:
3313 // __pointee is a pointer to the std::type_info derivation for the
3314 // unqualified type being pointed to.
3315 llvm::Constant *PointeeTypeInfo =
3316 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3317 Fields.push_back(PointeeTypeInfo);
3318
3319 // Itanium C++ ABI 2.9.5p9:
3320 // __context is a pointer to an abi::__class_type_info corresponding to the
3321 // class type containing the member pointed to
3322 // (e.g., the "A" in "int A::*").
3323 Fields.push_back(
3324 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3325}
3326
David Majnemer443250f2015-03-17 20:35:00 +00003327llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003328 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3329}
3330
3331void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3332 QualType PointerType = getContext().getPointerType(Type);
3333 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3334 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3335 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3336 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3337}
3338
3339void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
Richard Smith4a382012016-02-03 01:32:42 +00003340 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003341 QualType FundamentalTypes[] = {
3342 getContext().VoidTy, getContext().NullPtrTy,
3343 getContext().BoolTy, getContext().WCharTy,
3344 getContext().CharTy, getContext().UnsignedCharTy,
3345 getContext().SignedCharTy, getContext().ShortTy,
3346 getContext().UnsignedShortTy, getContext().IntTy,
3347 getContext().UnsignedIntTy, getContext().LongTy,
3348 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003349 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3350 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003351 getContext().FloatTy, getContext().DoubleTy,
3352 getContext().LongDoubleTy, getContext().Char16Ty,
3353 getContext().Char32Ty,
3354 };
3355 for (const QualType &FundamentalType : FundamentalTypes)
3356 EmitFundamentalRTTIDescriptor(FundamentalType);
3357}
3358
3359/// What sort of uniqueness rules should we use for the RTTI for the
3360/// given type?
3361ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3362 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3363 if (shouldRTTIBeUnique())
3364 return RUK_Unique;
3365
3366 // It's only necessary for linkonce_odr or weak_odr linkage.
3367 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3368 Linkage != llvm::GlobalValue::WeakODRLinkage)
3369 return RUK_Unique;
3370
3371 // It's only necessary with default visibility.
3372 if (CanTy->getVisibility() != DefaultVisibility)
3373 return RUK_Unique;
3374
3375 // If we're not required to publish this symbol, hide it.
3376 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3377 return RUK_NonUniqueHidden;
3378
3379 // If we're required to publish this symbol, as we might be under an
3380 // explicit instantiation, leave it with default visibility but
3381 // enable string-comparisons.
3382 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3383 return RUK_NonUniqueVisible;
3384}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003385
Rafael Espindola1e4df922014-09-16 15:18:21 +00003386// Find out how to codegen the complete destructor and constructor
3387namespace {
3388enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3389}
3390static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3391 const CXXMethodDecl *MD) {
3392 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3393 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003394
Rafael Espindola1e4df922014-09-16 15:18:21 +00003395 // The complete and base structors are not equivalent if there are any virtual
3396 // bases, so emit separate functions.
3397 if (MD->getParent()->getNumVBases())
3398 return StructorCodegen::Emit;
3399
3400 GlobalDecl AliasDecl;
3401 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3402 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3403 } else {
3404 const auto *CD = cast<CXXConstructorDecl>(MD);
3405 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3406 }
3407 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3408
3409 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3410 return StructorCodegen::RAUW;
3411
3412 // FIXME: Should we allow available_externally aliases?
3413 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3414 return StructorCodegen::RAUW;
3415
Rafael Espindola0806f982014-09-16 20:19:43 +00003416 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3417 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3418 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3419 return StructorCodegen::COMDAT;
3420 return StructorCodegen::Emit;
3421 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003422
3423 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003424}
3425
Rafael Espindola1e4df922014-09-16 15:18:21 +00003426static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3427 GlobalDecl AliasDecl,
3428 GlobalDecl TargetDecl) {
3429 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3430
3431 StringRef MangledName = CGM.getMangledName(AliasDecl);
3432 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3433 if (Entry && !Entry->isDeclaration())
3434 return;
3435
3436 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003437
3438 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003439 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003440
3441 // Switch any previous uses to the alias.
3442 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003443 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003444 "declaration exists with different type");
3445 Alias->takeName(Entry);
3446 Entry->replaceAllUsesWith(Alias);
3447 Entry->eraseFromParent();
3448 } else {
3449 Alias->setName(MangledName);
3450 }
3451
3452 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003453 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003454}
3455
3456void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3457 StructorType Type) {
3458 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3459 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3460
3461 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3462
3463 if (Type == StructorType::Complete) {
3464 GlobalDecl CompleteDecl;
3465 GlobalDecl BaseDecl;
3466 if (CD) {
3467 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3468 BaseDecl = GlobalDecl(CD, Ctor_Base);
3469 } else {
3470 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3471 BaseDecl = GlobalDecl(DD, Dtor_Base);
3472 }
3473
3474 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3475 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3476 return;
3477 }
3478
3479 if (CGType == StructorCodegen::RAUW) {
3480 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003481 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003482 CGM.addReplacement(MangledName, Aliasee);
3483 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003484 }
3485 }
3486
3487 // The base destructor is equivalent to the base destructor of its
3488 // base class if there is exactly one non-virtual base class with a
3489 // non-trivial destructor, there are no fields with a non-trivial
3490 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003491 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3492 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003493 return;
3494
Rafael Espindola1e4df922014-09-16 15:18:21 +00003495 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003496
Rafael Espindola1e4df922014-09-16 15:18:21 +00003497 if (CGType == StructorCodegen::COMDAT) {
3498 SmallString<256> Buffer;
3499 llvm::raw_svector_ostream Out(Buffer);
3500 if (DD)
3501 getMangleContext().mangleCXXDtorComdat(DD, Out);
3502 else
3503 getMangleContext().mangleCXXCtorComdat(CD, Out);
3504 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3505 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003506 } else {
3507 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003508 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003509}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003510
3511static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3512 // void *__cxa_begin_catch(void*);
3513 llvm::FunctionType *FTy = llvm::FunctionType::get(
3514 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3515
3516 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3517}
3518
3519static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3520 // void __cxa_end_catch();
3521 llvm::FunctionType *FTy =
3522 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3523
3524 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3525}
3526
3527static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3528 // void *__cxa_get_exception_ptr(void*);
3529 llvm::FunctionType *FTy = llvm::FunctionType::get(
3530 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3531
3532 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3533}
3534
3535namespace {
3536 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3537 /// exception type lets us state definitively that the thrown exception
3538 /// type does not have a destructor. In particular:
3539 /// - Catch-alls tell us nothing, so we have to conservatively
3540 /// assume that the thrown exception might have a destructor.
3541 /// - Catches by reference behave according to their base types.
3542 /// - Catches of non-record types will only trigger for exceptions
3543 /// of non-record types, which never have destructors.
3544 /// - Catches of record types can trigger for arbitrary subclasses
3545 /// of the caught type, so we have to assume the actual thrown
3546 /// exception type might have a throwing destructor, even if the
3547 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003548 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003549 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3550 bool MightThrow;
3551
3552 void Emit(CodeGenFunction &CGF, Flags flags) override {
3553 if (!MightThrow) {
3554 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3555 return;
3556 }
3557
3558 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3559 }
3560 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003561}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003562
3563/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3564/// __cxa_end_catch.
3565///
3566/// \param EndMightThrow - true if __cxa_end_catch might throw
3567static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3568 llvm::Value *Exn,
3569 bool EndMightThrow) {
3570 llvm::CallInst *call =
3571 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3572
3573 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3574
3575 return call;
3576}
3577
3578/// A "special initializer" callback for initializing a catch
3579/// parameter during catch initialization.
3580static void InitCatchParam(CodeGenFunction &CGF,
3581 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003582 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003583 SourceLocation Loc) {
3584 // Load the exception from where the landing pad saved it.
3585 llvm::Value *Exn = CGF.getExceptionFromSlot();
3586
3587 CanQualType CatchType =
3588 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3589 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3590
3591 // If we're catching by reference, we can just cast the object
3592 // pointer to the appropriate pointer.
3593 if (isa<ReferenceType>(CatchType)) {
3594 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3595 bool EndCatchMightThrow = CaughtType->isRecordType();
3596
3597 // __cxa_begin_catch returns the adjusted object pointer.
3598 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3599
3600 // We have no way to tell the personality function that we're
3601 // catching by reference, so if we're catching a pointer,
3602 // __cxa_begin_catch will actually return that pointer by value.
3603 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3604 QualType PointeeType = PT->getPointeeType();
3605
3606 // When catching by reference, generally we should just ignore
3607 // this by-value pointer and use the exception object instead.
3608 if (!PointeeType->isRecordType()) {
3609
3610 // Exn points to the struct _Unwind_Exception header, which
3611 // we have to skip past in order to reach the exception data.
3612 unsigned HeaderSize =
3613 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3614 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3615
3616 // However, if we're catching a pointer-to-record type that won't
3617 // work, because the personality function might have adjusted
3618 // the pointer. There's actually no way for us to fully satisfy
3619 // the language/ABI contract here: we can't use Exn because it
3620 // might have the wrong adjustment, but we can't use the by-value
3621 // pointer because it's off by a level of abstraction.
3622 //
3623 // The current solution is to dump the adjusted pointer into an
3624 // alloca, which breaks language semantics (because changing the
3625 // pointer doesn't change the exception) but at least works.
3626 // The better solution would be to filter out non-exact matches
3627 // and rethrow them, but this is tricky because the rethrow
3628 // really needs to be catchable by other sites at this landing
3629 // pad. The best solution is to fix the personality function.
3630 } else {
3631 // Pull the pointer for the reference type off.
3632 llvm::Type *PtrTy =
3633 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3634
3635 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003636 Address ExnPtrTmp =
3637 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003638 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3639 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3640
3641 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003642 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003643 }
3644 }
3645
3646 llvm::Value *ExnCast =
3647 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3648 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3649 return;
3650 }
3651
3652 // Scalars and complexes.
3653 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3654 if (TEK != TEK_Aggregate) {
3655 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3656
3657 // If the catch type is a pointer type, __cxa_begin_catch returns
3658 // the pointer by value.
3659 if (CatchType->hasPointerRepresentation()) {
3660 llvm::Value *CastExn =
3661 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3662
3663 switch (CatchType.getQualifiers().getObjCLifetime()) {
3664 case Qualifiers::OCL_Strong:
3665 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3666 // fallthrough
3667
3668 case Qualifiers::OCL_None:
3669 case Qualifiers::OCL_ExplicitNone:
3670 case Qualifiers::OCL_Autoreleasing:
3671 CGF.Builder.CreateStore(CastExn, ParamAddr);
3672 return;
3673
3674 case Qualifiers::OCL_Weak:
3675 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3676 return;
3677 }
3678 llvm_unreachable("bad ownership qualifier!");
3679 }
3680
3681 // Otherwise, it returns a pointer into the exception object.
3682
3683 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3684 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3685
3686 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003687 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003688 switch (TEK) {
3689 case TEK_Complex:
3690 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3691 /*init*/ true);
3692 return;
3693 case TEK_Scalar: {
3694 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3695 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3696 return;
3697 }
3698 case TEK_Aggregate:
3699 llvm_unreachable("evaluation kind filtered out!");
3700 }
3701 llvm_unreachable("bad evaluation kind");
3702 }
3703
3704 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003705 auto catchRD = CatchType->getAsCXXRecordDecl();
3706 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003707
3708 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3709
3710 // Check for a copy expression. If we don't have a copy expression,
3711 // that means a trivial copy is okay.
3712 const Expr *copyExpr = CatchParam.getInit();
3713 if (!copyExpr) {
3714 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003715 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3716 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003717 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3718 return;
3719 }
3720
3721 // We have to call __cxa_get_exception_ptr to get the adjusted
3722 // pointer before copying.
3723 llvm::CallInst *rawAdjustedExn =
3724 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3725
3726 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003727 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3728 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003729
3730 // The copy expression is defined in terms of an OpaqueValueExpr.
3731 // Find it and map it to the adjusted expression.
3732 CodeGenFunction::OpaqueValueMapping
3733 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3734 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3735
3736 // Call the copy ctor in a terminate scope.
3737 CGF.EHStack.pushTerminate();
3738
3739 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003740 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003741 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003742 AggValueSlot::IsNotDestructed,
3743 AggValueSlot::DoesNotNeedGCBarriers,
3744 AggValueSlot::IsNotAliased));
3745
3746 // Leave the terminate scope.
3747 CGF.EHStack.popTerminate();
3748
3749 // Undo the opaque value mapping.
3750 opaque.pop();
3751
3752 // Finally we can call __cxa_begin_catch.
3753 CallBeginCatch(CGF, Exn, true);
3754}
3755
3756/// Begins a catch statement by initializing the catch variable and
3757/// calling __cxa_begin_catch.
3758void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3759 const CXXCatchStmt *S) {
3760 // We have to be very careful with the ordering of cleanups here:
3761 // C++ [except.throw]p4:
3762 // The destruction [of the exception temporary] occurs
3763 // immediately after the destruction of the object declared in
3764 // the exception-declaration in the handler.
3765 //
3766 // So the precise ordering is:
3767 // 1. Construct catch variable.
3768 // 2. __cxa_begin_catch
3769 // 3. Enter __cxa_end_catch cleanup
3770 // 4. Enter dtor cleanup
3771 //
3772 // We do this by using a slightly abnormal initialization process.
3773 // Delegation sequence:
3774 // - ExitCXXTryStmt opens a RunCleanupsScope
3775 // - EmitAutoVarAlloca creates the variable and debug info
3776 // - InitCatchParam initializes the variable from the exception
3777 // - CallBeginCatch calls __cxa_begin_catch
3778 // - CallBeginCatch enters the __cxa_end_catch cleanup
3779 // - EmitAutoVarCleanups enters the variable destructor cleanup
3780 // - EmitCXXTryStmt emits the code for the catch body
3781 // - EmitCXXTryStmt close the RunCleanupsScope
3782
3783 VarDecl *CatchParam = S->getExceptionDecl();
3784 if (!CatchParam) {
3785 llvm::Value *Exn = CGF.getExceptionFromSlot();
3786 CallBeginCatch(CGF, Exn, true);
3787 return;
3788 }
3789
3790 // Emit the local.
3791 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3792 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3793 CGF.EmitAutoVarCleanups(var);
3794}
3795
3796/// Get or define the following function:
3797/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3798/// This code is used only in C++.
3799static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3800 llvm::FunctionType *fnTy =
3801 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3802 llvm::Constant *fnRef =
3803 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3804
3805 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3806 if (fn && fn->empty()) {
3807 fn->setDoesNotThrow();
3808 fn->setDoesNotReturn();
3809
3810 // What we really want is to massively penalize inlining without
3811 // forbidding it completely. The difference between that and
3812 // 'noinline' is negligible.
3813 fn->addFnAttr(llvm::Attribute::NoInline);
3814
3815 // Allow this function to be shared across translation units, but
3816 // we don't want it to turn into an exported symbol.
3817 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3818 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003819 if (CGM.supportsCOMDAT())
3820 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003821
3822 // Set up the function.
3823 llvm::BasicBlock *entry =
3824 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003825 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003826
3827 // Pull the exception pointer out of the parameter list.
3828 llvm::Value *exn = &*fn->arg_begin();
3829
3830 // Call __cxa_begin_catch(exn).
3831 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3832 catchCall->setDoesNotThrow();
3833 catchCall->setCallingConv(CGM.getRuntimeCC());
3834
3835 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003836 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003837 termCall->setDoesNotThrow();
3838 termCall->setDoesNotReturn();
3839 termCall->setCallingConv(CGM.getRuntimeCC());
3840
3841 // std::terminate cannot return.
3842 builder.CreateUnreachable();
3843 }
3844
3845 return fnRef;
3846}
3847
3848llvm::CallInst *
3849ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3850 llvm::Value *Exn) {
3851 // In C++, we want to call __cxa_begin_catch() before terminating.
3852 if (Exn) {
3853 assert(CGF.CGM.getLangOpts().CPlusPlus);
3854 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3855 }
3856 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3857}