blob: e6d38aff340daa9cfb71ab79790b39fac0035d94 [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"
John McCall5ad74072017-03-02 20:04:19 +000028#include "clang/CodeGen/ConstantInitBuilder.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000029#include "clang/AST/Mangle.h"
30#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000031#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000034#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000037
38using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000039using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000040
41namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000042class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000043 /// VTables - All the vtables which have been defined.
44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
45
John McCall475999d2010-08-22 00:05:51 +000046protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000047 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000049 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000051 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
53 }
54
Charles Davis4e786dd2010-05-25 19:52:27 +000055public:
Mark Seabornedf0d382013-07-24 16:25:13 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000060 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000061 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000062
Reid Kleckner40ca9132014-05-13 22:05:45 +000063 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064
Craig Topper4f12f102014-03-12 06:41:41 +000065 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000066 // Structures with either a non-trivial destructor or a non-trivial
67 // copy constructor are always indirect.
68 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
69 // special members.
70 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000071 return RAA_Indirect;
72 return RAA_Default;
73 }
74
John McCall7f416cc2015-09-08 08:05:57 +000075 bool isThisCompleteObject(GlobalDecl GD) const override {
76 // The Itanium ABI has separate complete-object vs. base-object
77 // variants of both constructors and destructors.
78 if (isa<CXXDestructorDecl>(GD.getDecl())) {
79 switch (GD.getDtorType()) {
80 case Dtor_Complete:
81 case Dtor_Deleting:
82 return true;
83
84 case Dtor_Base:
85 return false;
86
87 case Dtor_Comdat:
88 llvm_unreachable("emitting dtor comdat as function?");
89 }
90 llvm_unreachable("bad dtor kind");
91 }
92 if (isa<CXXConstructorDecl>(GD.getDecl())) {
93 switch (GD.getCtorType()) {
94 case Ctor_Complete:
95 return true;
96
97 case Ctor_Base:
98 return false;
99
100 case Ctor_CopyingClosure:
101 case Ctor_DefaultClosure:
102 llvm_unreachable("closure ctors in Itanium ABI?");
103
104 case Ctor_Comdat:
105 llvm_unreachable("emitting ctor comdat as function?");
106 }
107 llvm_unreachable("bad dtor kind");
108 }
109
110 // No other kinds.
111 return false;
112 }
113
Craig Topper4f12f102014-03-12 06:41:41 +0000114 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000115
Craig Topper4f12f102014-03-12 06:41:41 +0000116 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000117
John McCallb92ab1a2016-10-26 23:46:34 +0000118 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000119 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
120 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000121 Address This,
122 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *MemFnPtr,
124 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000125
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *
127 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000128 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000129 llvm::Value *MemPtr,
130 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000131
John McCall7a9aac22010-08-23 01:21:21 +0000132 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
133 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000134 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000135 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000137
Craig Topper4f12f102014-03-12 06:41:41 +0000138 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000139
David Majnemere2be95b2015-06-23 07:31:01 +0000140 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000141 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000142 CharUnits offset) override;
143 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000144 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
145 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000146
John McCall7a9aac22010-08-23 01:21:21 +0000147 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000148 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000149 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000151
John McCall7a9aac22010-08-23 01:21:21 +0000152 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000153 llvm::Value *Addr,
154 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000155
David Majnemer08681372014-11-01 07:37:17 +0000156 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000157 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000158 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000159
John McCall7f416cc2015-09-08 08:05:57 +0000160 CharUnits getAlignmentOfExnObject() {
Akira Hatanaka68ab7fe2016-03-31 06:36:07 +0000161 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
162 return CGM.getContext().toCharUnitsFromBits(Align);
John McCall7f416cc2015-09-08 08:05:57 +0000163 }
164
David Majnemer442d0a22014-11-25 07:20:20 +0000165 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000166 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000167
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000168 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
169
170 llvm::CallInst *
171 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
172 llvm::Value *Exn) override;
173
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000174 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
175 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000176 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000177 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000178 getAddrOfCXXCatchHandlerType(QualType Ty,
179 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000180 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000181 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000182
David Majnemer1162d252014-06-22 19:05:33 +0000183 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
184 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
185 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000186 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000187 llvm::Type *StdTypeInfoPtrTy) override;
188
189 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
190 QualType SrcRecordTy) override;
191
John McCall7f416cc2015-09-08 08:05:57 +0000192 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000193 QualType SrcRecordTy, QualType DestTy,
194 QualType DestRecordTy,
195 llvm::BasicBlock *CastEnd) override;
196
John McCall7f416cc2015-09-08 08:05:57 +0000197 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000198 QualType SrcRecordTy,
199 QualType DestTy) override;
200
201 bool EmitBadCastCall(CodeGenFunction &CGF) override;
202
Craig Topper4f12f102014-03-12 06:41:41 +0000203 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000204 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000205 const CXXRecordDecl *ClassDecl,
206 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000207
Craig Topper4f12f102014-03-12 06:41:41 +0000208 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000209
George Burgess IVf203dbf2017-02-22 20:28:02 +0000210 AddedStructorArgs
211 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
212 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000213
Reid Klecknere7de47e2013-07-22 13:51:44 +0000214 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000215 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000216 // Itanium does not emit any destructor variant as an inline thunk.
217 // Delegating may occur as an optimization, but all variants are either
218 // emitted with external linkage or as linkonce if they are inline and used.
219 return false;
220 }
221
Craig Topper4f12f102014-03-12 06:41:41 +0000222 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000223
Reid Kleckner89077a12013-12-17 19:46:40 +0000224 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000225 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000226
Craig Topper4f12f102014-03-12 06:41:41 +0000227 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000228
George Burgess IVf203dbf2017-02-22 20:28:02 +0000229 AddedStructorArgs
230 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
231 CXXCtorType Type, bool ForVirtualBase,
232 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000233
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000234 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
235 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000236 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void emitVTableDefinitions(CodeGenVTables &CGVT,
239 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000240
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000241 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
242 CodeGenFunction::VPtr Vptr) override;
243
244 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
245 return true;
246 }
247
248 llvm::Constant *
249 getVTableAddressPoint(BaseSubobject Base,
250 const CXXRecordDecl *VTableClass) override;
251
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000252 llvm::Value *getVTableAddressPointInStructor(
253 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000254 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
255
256 llvm::Value *getVTableAddressPointInStructorWithVTT(
257 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
258 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000259
260 llvm::Constant *
261 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000262 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000263
264 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000265 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000266
John McCallb92ab1a2016-10-26 23:46:34 +0000267 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
268 Address This, llvm::Type *Ty,
269 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000270
David Majnemer0c0b6d92014-10-31 20:09:12 +0000271 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
272 const CXXDestructorDecl *Dtor,
273 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000274 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000275 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000276
Craig Topper4f12f102014-03-12 06:41:41 +0000277 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000278
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000279 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000280
Hans Wennborgc94391d2014-06-06 20:04:01 +0000281 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
282 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000283 // Allow inlining of thunks by emitting them with available_externally
284 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000285 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000286 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
287 }
288
John McCall7f416cc2015-09-08 08:05:57 +0000289 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000290 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000291
John McCall7f416cc2015-09-08 08:05:57 +0000292 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000293 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000294
David Majnemer196ac332014-09-11 23:05:02 +0000295 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
296 FunctionArgList &Args) const override {
297 assert(!Args.empty() && "expected the arglist to not be empty!");
298 return Args.size() - 1;
299 }
300
Craig Topper4f12f102014-03-12 06:41:41 +0000301 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
302 StringRef GetDeletedVirtualCallName() override
303 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000304
Craig Topper4f12f102014-03-12 06:41:41 +0000305 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000306 Address InitializeArrayCookie(CodeGenFunction &CGF,
307 Address NewPtr,
308 llvm::Value *NumElements,
309 const CXXNewExpr *expr,
310 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000311 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000312 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000313 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000314
John McCallcdf7ef52010-11-06 09:44:32 +0000315 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000316 llvm::GlobalVariable *DeclPtr,
317 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000318 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000319 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000320
321 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000322 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000323 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000324 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000325 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000326 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000327 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000328
329 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000330 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
331 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000332
Craig Topper4f12f102014-03-12 06:41:41 +0000333 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000334
335 /**************************** RTTI Uniqueness ******************************/
336
337protected:
338 /// Returns true if the ABI requires RTTI type_info objects to be unique
339 /// across a program.
340 virtual bool shouldRTTIBeUnique() const { return true; }
341
342public:
343 /// What sort of unique-RTTI behavior should we use?
344 enum RTTIUniquenessKind {
345 /// We are guaranteeing, or need to guarantee, that the RTTI string
346 /// is unique.
347 RUK_Unique,
348
349 /// We are not guaranteeing uniqueness for the RTTI string, so we
350 /// can demote to hidden visibility but must use string comparisons.
351 RUK_NonUniqueHidden,
352
353 /// We are not guaranteeing uniqueness for the RTTI string, so we
354 /// have to use string comparisons, but we also have to emit it with
355 /// non-hidden visibility.
356 RUK_NonUniqueVisible
357 };
358
359 /// Return the required visibility status for the given type and linkage in
360 /// the current ABI.
361 RTTIUniquenessKind
362 classifyRTTIUniqueness(QualType CanTy,
363 llvm::GlobalValue::LinkageTypes Linkage) const;
364 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000365
366 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000367
368 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000369 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
370 const auto &VtableLayout =
371 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000372
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000373 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
374 // Skip empty slot.
375 if (!VtableComponent.isUsedFunctionPointerKind())
376 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000377
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000378 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
379 if (!Method->getCanonicalDecl()->isInlined())
380 continue;
381
382 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
383 auto *Entry = CGM.GetGlobalValue(Name);
384 // This checks if virtual inline function has already been emitted.
385 // Note that it is possible that this inline function would be emitted
386 // after trying to emit vtable speculatively. Because of this we do
387 // an extra pass after emitting all deferred vtables to find and emit
388 // these vtables opportunistically.
389 if (!Entry || Entry->isDeclaration())
390 return true;
391 }
392 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000393 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000394
395 bool isVTableHidden(const CXXRecordDecl *RD) const {
396 const auto &VtableLayout =
397 CGM.getItaniumVTableContext().getVTableLayout(RD);
398
399 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
400 if (VtableComponent.isRTTIKind()) {
401 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
402 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
403 return true;
404 } else if (VtableComponent.isUsedFunctionPointerKind()) {
405 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
406 if (Method->getVisibility() == Visibility::HiddenVisibility &&
407 !Method->isDefined())
408 return true;
409 }
410 }
411 return false;
412 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000413};
John McCall86353412010-08-21 22:46:04 +0000414
415class ARMCXXABI : public ItaniumCXXABI {
416public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000417 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
418 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
419 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000420
Craig Topper4f12f102014-03-12 06:41:41 +0000421 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000422 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
423 isa<CXXDestructorDecl>(GD.getDecl()) &&
424 GD.getDtorType() != Dtor_Deleting));
425 }
John McCall5d865c322010-08-31 07:33:07 +0000426
Craig Topper4f12f102014-03-12 06:41:41 +0000427 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
428 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000429
Craig Topper4f12f102014-03-12 06:41:41 +0000430 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000431 Address InitializeArrayCookie(CodeGenFunction &CGF,
432 Address NewPtr,
433 llvm::Value *NumElements,
434 const CXXNewExpr *expr,
435 QualType ElementType) override;
436 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000437 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000438};
Tim Northovera2ee4332014-03-29 15:09:45 +0000439
440class iOS64CXXABI : public ARMCXXABI {
441public:
John McCalld23b27e2016-09-16 02:40:45 +0000442 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
443 Use32BitVTableOffsetABI = true;
444 }
Tim Northover65f582f2014-03-30 17:32:48 +0000445
446 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000447 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000448};
Dan Gohmanc2853072015-09-03 22:51:53 +0000449
450class WebAssemblyCXXABI final : public ItaniumCXXABI {
451public:
452 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
453 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
454 /*UseARMGuardVarABI=*/true) {}
455
456private:
457 bool HasThisReturn(GlobalDecl GD) const override {
458 return isa<CXXConstructorDecl>(GD.getDecl()) ||
459 (isa<CXXDestructorDecl>(GD.getDecl()) &&
460 GD.getDtorType() != Dtor_Deleting);
461 }
Derek Schuff8179be42016-05-10 17:44:55 +0000462 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000463};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000464}
Charles Davis4e786dd2010-05-25 19:52:27 +0000465
Charles Davis53c59df2010-08-16 03:33:14 +0000466CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000467 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000468 // For IR-generation purposes, there's no significant difference
469 // between the ARM and iOS ABIs.
470 case TargetCXXABI::GenericARM:
471 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000472 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000473 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000474
Tim Northovera2ee4332014-03-29 15:09:45 +0000475 case TargetCXXABI::iOS64:
476 return new iOS64CXXABI(CGM);
477
Tim Northover9bb857a2013-01-31 12:13:10 +0000478 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
479 // include the other 32-bit ARM oddities: constructor/destructor return values
480 // and array cookies.
481 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000482 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
483 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000484
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000485 case TargetCXXABI::GenericMIPS:
486 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
487
Dan Gohmanc2853072015-09-03 22:51:53 +0000488 case TargetCXXABI::WebAssembly:
489 return new WebAssemblyCXXABI(CGM);
490
John McCall57625922013-01-25 23:36:14 +0000491 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000492 if (CGM.getContext().getTargetInfo().getTriple().getArch()
493 == llvm::Triple::le32) {
494 // For PNaCl, use ARM-style method pointers so that PNaCl code
495 // does not assume anything about the alignment of function
496 // pointers.
497 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
498 /* UseARMGuardVarABI = */ false);
499 }
John McCall57625922013-01-25 23:36:14 +0000500 return new ItaniumCXXABI(CGM);
501
502 case TargetCXXABI::Microsoft:
503 llvm_unreachable("Microsoft ABI is not Itanium-based");
504 }
505 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000506}
507
Chris Lattnera5f58b02011-07-09 17:41:47 +0000508llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000509ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
510 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000511 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000512 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000513}
514
John McCalld9c6c0b2010-08-22 00:59:17 +0000515/// In the Itanium and ARM ABIs, method pointers have the form:
516/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
517///
518/// In the Itanium ABI:
519/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
520/// - the this-adjustment is (memptr.adj)
521/// - the virtual offset is (memptr.ptr - 1)
522///
523/// In the ARM ABI:
524/// - method pointers are virtual if (memptr.adj & 1) is nonzero
525/// - the this-adjustment is (memptr.adj >> 1)
526/// - the virtual offset is (memptr.ptr)
527/// ARM uses 'adj' for the virtual flag because Thumb functions
528/// may be only single-byte aligned.
529///
530/// If the member is virtual, the adjusted 'this' pointer points
531/// to a vtable pointer from which the virtual offset is applied.
532///
533/// If the member is non-virtual, memptr.ptr is the address of
534/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000535CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000536 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
537 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000538 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000539 CGBuilderTy &Builder = CGF.Builder;
540
541 const FunctionProtoType *FPT =
542 MPT->getPointeeType()->getAs<FunctionProtoType>();
543 const CXXRecordDecl *RD =
544 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
545
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000546 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
547 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000548
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000549 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000550
John McCalld9c6c0b2010-08-22 00:59:17 +0000551 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
552 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
553 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
554
John McCalla1dee5302010-08-22 10:59:02 +0000555 // Extract memptr.adj, which is in the second field.
556 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000557
558 // Compute the true adjustment.
559 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000560 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000561 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000562
563 // Apply the adjustment and cast back to the original struct type
564 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000565 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000566 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
567 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
568 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000569 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000570
571 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000572 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000573
574 // If the LSB in the function pointer is 1, the function pointer points to
575 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000576 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000577 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000578 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
579 else
580 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
581 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000582 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
583
584 // In the virtual path, the adjustment left 'This' pointing to the
585 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000586 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000587 CGF.EmitBlock(FnVirtual);
588
589 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000590 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000591 CharUnits VTablePtrAlign =
592 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
593 CGF.getPointerAlign());
594 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000595 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000596
597 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000598 // On ARM64, to reserve extra space in virtual member function pointers,
599 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000600 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000601 if (!UseARMMethodPtrABI)
602 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000603 if (Use32BitVTableOffsetABI) {
604 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
605 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
606 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000607 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000608
609 // Load the virtual function to call.
610 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000611 llvm::Value *VirtualFn =
612 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
613 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000614 CGF.EmitBranch(FnEnd);
615
616 // In the non-virtual path, the function pointer is actually a
617 // function pointer.
618 CGF.EmitBlock(FnNonVirtual);
619 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000620 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000621
622 // We're done.
623 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000624 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
625 CalleePtr->addIncoming(VirtualFn, FnVirtual);
626 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
627
628 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000629 return Callee;
630}
John McCalla8bbb822010-08-22 03:04:22 +0000631
John McCallc134eb52010-08-31 21:07:20 +0000632/// Compute an l-value by applying the given pointer-to-member to a
633/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000634llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000635 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000636 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000637 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000638
639 CGBuilderTy &Builder = CGF.Builder;
640
John McCallc134eb52010-08-31 21:07:20 +0000641 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000642 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000643
644 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000645 llvm::Value *Addr =
646 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000647
648 // Cast the address to the appropriate pointer type, adopting the
649 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000650 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
651 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000652 return Builder.CreateBitCast(Addr, PType);
653}
654
John McCallc62bb392012-02-15 01:22:51 +0000655/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
656/// conversion.
657///
658/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000659///
660/// Obligatory offset/adjustment diagram:
661/// <-- offset --> <-- adjustment -->
662/// |--------------------------|----------------------|--------------------|
663/// ^Derived address point ^Base address point ^Member address point
664///
665/// So when converting a base member pointer to a derived member pointer,
666/// we add the offset to the adjustment because the address point has
667/// decreased; and conversely, when converting a derived MP to a base MP
668/// we subtract the offset from the adjustment because the address point
669/// has increased.
670///
671/// The standard forbids (at compile time) conversion to and from
672/// virtual bases, which is why we don't have to consider them here.
673///
674/// The standard forbids (at run time) casting a derived MP to a base
675/// MP when the derived MP does not point to a member of the base.
676/// This is why -1 is a reasonable choice for null data member
677/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000678llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000679ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
680 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000681 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000682 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000683 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
684 E->getCastKind() == CK_ReinterpretMemberPointer);
685
686 // Under Itanium, reinterprets don't require any additional processing.
687 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
688
689 // Use constant emission if we can.
690 if (isa<llvm::Constant>(src))
691 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
692
693 llvm::Constant *adj = getMemberPointerAdjustment(E);
694 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000695
696 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000697 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000698
John McCallc62bb392012-02-15 01:22:51 +0000699 const MemberPointerType *destTy =
700 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000701
John McCall7a9aac22010-08-23 01:21:21 +0000702 // For member data pointers, this is just a matter of adding the
703 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000704 if (destTy->isMemberDataPointer()) {
705 llvm::Value *dst;
706 if (isDerivedToBase)
707 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000708 else
John McCallc62bb392012-02-15 01:22:51 +0000709 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000710
711 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000712 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
713 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
714 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000715 }
716
John McCalla1dee5302010-08-22 10:59:02 +0000717 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000718 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000719 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
720 offset <<= 1;
721 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000722 }
723
John McCallc62bb392012-02-15 01:22:51 +0000724 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
725 llvm::Value *dstAdj;
726 if (isDerivedToBase)
727 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000728 else
John McCallc62bb392012-02-15 01:22:51 +0000729 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000730
John McCallc62bb392012-02-15 01:22:51 +0000731 return Builder.CreateInsertValue(src, dstAdj, 1);
732}
733
734llvm::Constant *
735ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
736 llvm::Constant *src) {
737 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
738 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
739 E->getCastKind() == CK_ReinterpretMemberPointer);
740
741 // Under Itanium, reinterprets don't require any additional processing.
742 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
743
744 // If the adjustment is trivial, we don't need to do anything.
745 llvm::Constant *adj = getMemberPointerAdjustment(E);
746 if (!adj) return src;
747
748 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
749
750 const MemberPointerType *destTy =
751 E->getType()->castAs<MemberPointerType>();
752
753 // For member data pointers, this is just a matter of adding the
754 // offset if the source is non-null.
755 if (destTy->isMemberDataPointer()) {
756 // null maps to null.
757 if (src->isAllOnesValue()) return src;
758
759 if (isDerivedToBase)
760 return llvm::ConstantExpr::getNSWSub(src, adj);
761 else
762 return llvm::ConstantExpr::getNSWAdd(src, adj);
763 }
764
765 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000766 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000767 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
768 offset <<= 1;
769 adj = llvm::ConstantInt::get(adj->getType(), offset);
770 }
771
772 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
773 llvm::Constant *dstAdj;
774 if (isDerivedToBase)
775 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
776 else
777 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
778
779 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000780}
John McCall84fa5102010-08-22 04:16:24 +0000781
782llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000783ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000784 // Itanium C++ ABI 2.3:
785 // A NULL pointer is represented as -1.
786 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000787 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000788
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000789 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000790 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000791 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000792}
793
John McCallf3a88602011-02-03 08:15:49 +0000794llvm::Constant *
795ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
796 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000797 // Itanium C++ ABI 2.3:
798 // A pointer to data member is an offset from the base address of
799 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000800 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000801}
802
David Majnemere2be95b2015-06-23 07:31:01 +0000803llvm::Constant *
804ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000805 return BuildMemberPointer(MD, CharUnits::Zero());
806}
807
808llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
809 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000810 assert(MD->isInstance() && "Member function must not be static!");
811 MD = MD->getCanonicalDecl();
812
813 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000814
815 // Get the function pointer (or index if this is a virtual function).
816 llvm::Constant *MemPtr[2];
817 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000818 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000819
Ken Dyckdf016282011-04-09 01:30:02 +0000820 const ASTContext &Context = getContext();
821 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000822 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000823 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000824
Mark Seabornedf0d382013-07-24 16:25:13 +0000825 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000826 // ARM C++ ABI 3.2.1:
827 // This ABI specifies that adj contains twice the this
828 // adjustment, plus 1 if the member function is virtual. The
829 // least significant bit of adj then makes exactly the same
830 // discrimination as the least significant bit of ptr does for
831 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000832 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
833 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000834 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000835 } else {
836 // Itanium C++ ABI 2.3:
837 // For a virtual function, [the pointer field] is 1 plus the
838 // virtual table offset (in bytes) of the function,
839 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000840 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
841 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000842 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000843 }
844 } else {
John McCall2979fe02011-04-12 00:42:48 +0000845 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000846 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000847 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000848 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000849 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000850 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000851 } else {
John McCall2979fe02011-04-12 00:42:48 +0000852 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
853 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000854 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000855 }
John McCall2979fe02011-04-12 00:42:48 +0000856 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000857
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000858 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000859 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
860 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000861 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000862 }
John McCall1c456c82010-08-22 06:43:33 +0000863
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000864 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000865}
866
Richard Smithdafff942012-01-14 04:30:29 +0000867llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
868 QualType MPType) {
869 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
870 const ValueDecl *MPD = MP.getMemberPointerDecl();
871 if (!MPD)
872 return EmitNullMemberPointer(MPT);
873
Reid Kleckner452abac2013-05-09 21:01:17 +0000874 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000875
876 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
877 return BuildMemberPointer(MD, ThisAdjustment);
878
879 CharUnits FieldOffset =
880 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
881 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
882}
883
John McCall131d97d2010-08-22 08:30:07 +0000884/// The comparison algorithm is pretty easy: the member pointers are
885/// the same if they're either bitwise identical *or* both null.
886///
887/// ARM is different here only because null-ness is more complicated.
888llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000889ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
890 llvm::Value *L,
891 llvm::Value *R,
892 const MemberPointerType *MPT,
893 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000894 CGBuilderTy &Builder = CGF.Builder;
895
John McCall131d97d2010-08-22 08:30:07 +0000896 llvm::ICmpInst::Predicate Eq;
897 llvm::Instruction::BinaryOps And, Or;
898 if (Inequality) {
899 Eq = llvm::ICmpInst::ICMP_NE;
900 And = llvm::Instruction::Or;
901 Or = llvm::Instruction::And;
902 } else {
903 Eq = llvm::ICmpInst::ICMP_EQ;
904 And = llvm::Instruction::And;
905 Or = llvm::Instruction::Or;
906 }
907
John McCall7a9aac22010-08-23 01:21:21 +0000908 // Member data pointers are easy because there's a unique null
909 // value, so it just comes down to bitwise equality.
910 if (MPT->isMemberDataPointer())
911 return Builder.CreateICmp(Eq, L, R);
912
913 // For member function pointers, the tautologies are more complex.
914 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000915 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000916 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000917 // (L == R) <==> (L.ptr == R.ptr &&
918 // (L.adj == R.adj ||
919 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000920 // The inequality tautologies have exactly the same structure, except
921 // applying De Morgan's laws.
922
923 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
924 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
925
John McCall131d97d2010-08-22 08:30:07 +0000926 // This condition tests whether L.ptr == R.ptr. This must always be
927 // true for equality to hold.
928 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
929
930 // This condition, together with the assumption that L.ptr == R.ptr,
931 // tests whether the pointers are both null. ARM imposes an extra
932 // condition.
933 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
934 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
935
936 // This condition tests whether L.adj == R.adj. If this isn't
937 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000938 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
939 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000940 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
941
942 // Null member function pointers on ARM clear the low bit of Adj,
943 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000944 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000945 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
946
947 // Compute (l.adj | r.adj) & 1 and test it against zero.
948 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
949 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
950 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
951 "cmp.or.adj");
952 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
953 }
954
955 // Tie together all our conditions.
956 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
957 Result = Builder.CreateBinOp(And, PtrEq, Result,
958 Inequality ? "memptr.ne" : "memptr.eq");
959 return Result;
960}
961
962llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000963ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
964 llvm::Value *MemPtr,
965 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000966 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000967
968 /// For member data pointers, this is just a check against -1.
969 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000970 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000971 llvm::Value *NegativeOne =
972 llvm::Constant::getAllOnesValue(MemPtr->getType());
973 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
974 }
John McCall131d97d2010-08-22 08:30:07 +0000975
Daniel Dunbar914bc412011-04-19 23:10:47 +0000976 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000977 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000978
979 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
980 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
981
Daniel Dunbar914bc412011-04-19 23:10:47 +0000982 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
983 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000984 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000985 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000986 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000987 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000988 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
989 "memptr.isvirtual");
990 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000991 }
992
993 return Result;
994}
John McCall1c456c82010-08-22 06:43:33 +0000995
Reid Kleckner40ca9132014-05-13 22:05:45 +0000996bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
997 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
998 if (!RD)
999 return false;
1000
Reid Klecknerd355ca72014-05-15 01:26:32 +00001001 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
1002 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
1003 // special members.
1004 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +00001005 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1006 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001007 return true;
1008 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001009 return false;
1010}
1011
John McCall614dbdc2010-08-22 21:01:12 +00001012/// The Itanium ABI requires non-zero initialization only for data
1013/// member pointers, for which '0' is a valid offset.
1014bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001015 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001016}
John McCall5d865c322010-08-31 07:33:07 +00001017
John McCall82fb8922012-09-25 10:10:39 +00001018/// The Itanium ABI always places an offset to the complete object
1019/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001020void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1021 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001022 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001023 QualType ElementType,
1024 const CXXDestructorDecl *Dtor) {
1025 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001026 if (UseGlobalDelete) {
1027 // Derive the complete-object pointer, which is what we need
1028 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001029
David Majnemer0c0b6d92014-10-31 20:09:12 +00001030 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001031 auto *ClassDecl =
1032 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1033 llvm::Value *VTable =
1034 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001035
David Majnemer0c0b6d92014-10-31 20:09:12 +00001036 // Track back to entry -2 and pull out the offset there.
1037 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1038 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001039 llvm::Value *Offset =
1040 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001041
1042 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001043 llvm::Value *CompletePtr =
1044 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001045 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1046
1047 // If we're supposed to call the global delete, make sure we do so
1048 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001049 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1050 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001051 }
1052
1053 // FIXME: Provide a source location here even though there's no
1054 // CXXMemberCallExpr for dtor call.
1055 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1056 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1057
1058 if (UseGlobalDelete)
1059 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001060}
1061
David Majnemer442d0a22014-11-25 07:20:20 +00001062void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1063 // void __cxa_rethrow();
1064
1065 llvm::FunctionType *FTy =
1066 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1067
1068 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1069
1070 if (isNoReturn)
1071 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1072 else
1073 CGF.EmitRuntimeCallOrInvoke(Fn);
1074}
1075
David Majnemer7c237072015-03-05 00:46:22 +00001076static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1077 // void *__cxa_allocate_exception(size_t thrown_size);
1078
1079 llvm::FunctionType *FTy =
1080 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1081
1082 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1083}
1084
1085static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1086 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1087 // void (*dest) (void *));
1088
1089 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1090 llvm::FunctionType *FTy =
1091 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1092
1093 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1094}
1095
1096void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1097 QualType ThrowType = E->getSubExpr()->getType();
1098 // Now allocate the exception object.
1099 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1100 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1101
1102 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1103 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1104 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1105
John McCall7f416cc2015-09-08 08:05:57 +00001106 CharUnits ExnAlign = getAlignmentOfExnObject();
1107 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001108
1109 // Now throw the exception.
1110 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1111 /*ForEH=*/true);
1112
1113 // The address of the destructor. If the exception type has a
1114 // trivial destructor (or isn't a record), we just pass null.
1115 llvm::Constant *Dtor = nullptr;
1116 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1117 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1118 if (!Record->hasTrivialDestructor()) {
1119 CXXDestructorDecl *DtorD = Record->getDestructor();
1120 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1121 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1122 }
1123 }
1124 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1125
1126 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1127 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1128}
1129
David Majnemer1162d252014-06-22 19:05:33 +00001130static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1131 // void *__dynamic_cast(const void *sub,
1132 // const abi::__class_type_info *src,
1133 // const abi::__class_type_info *dst,
1134 // std::ptrdiff_t src2dst_offset);
1135
1136 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1137 llvm::Type *PtrDiffTy =
1138 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1139
1140 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1141
1142 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1143
1144 // Mark the function as nounwind readonly.
1145 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1146 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001147 llvm::AttributeList Attrs = llvm::AttributeList::get(
1148 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001149
1150 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1151}
1152
1153static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1154 // void __cxa_bad_cast();
1155 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1156 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1157}
1158
1159/// \brief Compute the src2dst_offset hint as described in the
1160/// Itanium C++ ABI [2.9.7]
1161static CharUnits computeOffsetHint(ASTContext &Context,
1162 const CXXRecordDecl *Src,
1163 const CXXRecordDecl *Dst) {
1164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1165 /*DetectVirtual=*/false);
1166
1167 // If Dst is not derived from Src we can skip the whole computation below and
1168 // return that Src is not a public base of Dst. Record all inheritance paths.
1169 if (!Dst->isDerivedFrom(Src, Paths))
1170 return CharUnits::fromQuantity(-2ULL);
1171
1172 unsigned NumPublicPaths = 0;
1173 CharUnits Offset;
1174
1175 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001176 for (const CXXBasePath &Path : Paths) {
1177 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001178 continue;
1179
1180 ++NumPublicPaths;
1181
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001182 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001183 // If the path contains a virtual base class we can't give any hint.
1184 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001185 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001186 return CharUnits::fromQuantity(-1ULL);
1187
1188 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1189 continue;
1190
1191 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001192 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1193 Offset += L.getBaseClassOffset(
1194 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001195 }
1196 }
1197
1198 // -2: Src is not a public base of Dst.
1199 if (NumPublicPaths == 0)
1200 return CharUnits::fromQuantity(-2ULL);
1201
1202 // -3: Src is a multiple public base type but never a virtual base type.
1203 if (NumPublicPaths > 1)
1204 return CharUnits::fromQuantity(-3ULL);
1205
1206 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1207 // Return the offset of Src from the origin of Dst.
1208 return Offset;
1209}
1210
1211static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1212 // void __cxa_bad_typeid();
1213 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1214
1215 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1216}
1217
1218bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1219 QualType SrcRecordTy) {
1220 return IsDeref;
1221}
1222
1223void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1224 llvm::Value *Fn = getBadTypeidFn(CGF);
1225 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1226 CGF.Builder.CreateUnreachable();
1227}
1228
1229llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1230 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001231 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001232 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001233 auto *ClassDecl =
1234 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001235 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001236 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001237
1238 // Load the type info.
1239 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001240 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001241}
1242
1243bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1244 QualType SrcRecordTy) {
1245 return SrcIsPtr;
1246}
1247
1248llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001249 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001250 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1251 llvm::Type *PtrDiffLTy =
1252 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1253 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1254
1255 llvm::Value *SrcRTTI =
1256 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1257 llvm::Value *DestRTTI =
1258 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1259
1260 // Compute the offset hint.
1261 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1262 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1263 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1264 PtrDiffLTy,
1265 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1266
1267 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001268 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001269 Value = CGF.EmitCastToVoidPtr(Value);
1270
1271 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1272 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1273 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1274
1275 /// C++ [expr.dynamic.cast]p9:
1276 /// A failed cast to reference type throws std::bad_cast
1277 if (DestTy->isReferenceType()) {
1278 llvm::BasicBlock *BadCastBlock =
1279 CGF.createBasicBlock("dynamic_cast.bad_cast");
1280
1281 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1282 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1283
1284 CGF.EmitBlock(BadCastBlock);
1285 EmitBadCastCall(CGF);
1286 }
1287
1288 return Value;
1289}
1290
1291llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001292 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001293 QualType SrcRecordTy,
1294 QualType DestTy) {
1295 llvm::Type *PtrDiffLTy =
1296 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1297 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1298
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001299 auto *ClassDecl =
1300 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001301 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001302 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1303 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001304
1305 // Get the offset-to-top from the vtable.
1306 llvm::Value *OffsetToTop =
1307 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001308 OffsetToTop =
1309 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1310 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001311
1312 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001313 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001314 Value = CGF.EmitCastToVoidPtr(Value);
1315 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1316
1317 return CGF.Builder.CreateBitCast(Value, DestLTy);
1318}
1319
1320bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1321 llvm::Value *Fn = getBadCastFn(CGF);
1322 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1323 CGF.Builder.CreateUnreachable();
1324 return true;
1325}
1326
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001327llvm::Value *
1328ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001329 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001330 const CXXRecordDecl *ClassDecl,
1331 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001332 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001333 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001334 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1335 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001336
1337 llvm::Value *VBaseOffsetPtr =
1338 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1339 "vbase.offset.ptr");
1340 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1341 CGM.PtrDiffTy->getPointerTo());
1342
1343 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001344 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1345 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001346
1347 return VBaseOffset;
1348}
1349
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001350void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1351 // Just make sure we're in sync with TargetCXXABI.
1352 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1353
Rafael Espindolac3cde362013-12-09 14:51:17 +00001354 // The constructor used for constructing this as a base class;
1355 // ignores virtual bases.
1356 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1357
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001358 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001359 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001360 if (!D->getParent()->isAbstract()) {
1361 // We don't need to emit the complete ctor if the class is abstract.
1362 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1363 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001364}
1365
George Burgess IVf203dbf2017-02-22 20:28:02 +00001366CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001367ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1368 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001369 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001370
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001371 // All parameters are already in place except VTT, which goes after 'this'.
1372 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001373
1374 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001375 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001376 ArgTys.insert(ArgTys.begin() + 1,
1377 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001378 return AddedStructorArgs::prefix(1);
1379 }
1380 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001381}
1382
Reid Klecknere7de47e2013-07-22 13:51:44 +00001383void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001384 // The destructor used for destructing this as a base class; ignores
1385 // virtual bases.
1386 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001387
1388 // The destructor used for destructing this as a most-derived class;
1389 // call the base destructor and then destructs any virtual bases.
1390 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1391
Rafael Espindolac3cde362013-12-09 14:51:17 +00001392 // The destructor in a virtual table is always a 'deleting'
1393 // destructor, which calls the complete destructor and then uses the
1394 // appropriate operator delete.
1395 if (D->isVirtual())
1396 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001397}
1398
Reid Kleckner89077a12013-12-17 19:46:40 +00001399void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1400 QualType &ResTy,
1401 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001402 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001403 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001404
1405 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001406 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001407 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001408
1409 // FIXME: avoid the fake decl
1410 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001411 auto *VTTDecl = ImplicitParamDecl::Create(
1412 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1413 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001414 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001415 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001416 }
1417}
1418
John McCall5d865c322010-08-31 07:33:07 +00001419void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001420 // Naked functions have no prolog.
1421 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1422 return;
1423
John McCall5d865c322010-08-31 07:33:07 +00001424 /// Initialize the 'this' slot.
1425 EmitThisParam(CGF);
1426
1427 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001428 if (getStructorImplicitParamDecl(CGF)) {
1429 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1430 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001431 }
John McCall5d865c322010-08-31 07:33:07 +00001432
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001433 /// If this is a function that the ABI specifies returns 'this', initialize
1434 /// the return slot to 'this' at the start of the function.
1435 ///
1436 /// Unlike the setting of return types, this is done within the ABI
1437 /// implementation instead of by clients of CGCXXABI because:
1438 /// 1) getThisValue is currently protected
1439 /// 2) in theory, an ABI could implement 'this' returns some other way;
1440 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001441 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001442 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001443}
1444
George Burgess IVf203dbf2017-02-22 20:28:02 +00001445CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001446 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1447 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1448 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001449 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001450
Reid Kleckner89077a12013-12-17 19:46:40 +00001451 // Insert the implicit 'vtt' argument as the second argument.
1452 llvm::Value *VTT =
1453 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1454 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1455 Args.insert(Args.begin() + 1,
1456 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001457 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001458}
1459
1460void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1461 const CXXDestructorDecl *DD,
1462 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001463 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001464 GlobalDecl GD(DD, Type);
1465 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1466 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1467
John McCallb92ab1a2016-10-26 23:46:34 +00001468 CGCallee Callee;
1469 if (getContext().getLangOpts().AppleKext &&
1470 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001471 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001472 else
1473 Callee =
1474 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1475 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001476
John McCall7f416cc2015-09-08 08:05:57 +00001477 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001478 This.getPointer(), VTT, VTTTy,
1479 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001480}
1481
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001482void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1483 const CXXRecordDecl *RD) {
1484 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1485 if (VTable->hasInitializer())
1486 return;
1487
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001488 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001489 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1490 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001491 llvm::Constant *RTTI =
1492 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001493
1494 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001495 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001496 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001497 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1498 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001499
1500 // Set the correct linkage.
1501 VTable->setLinkage(Linkage);
1502
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001503 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1504 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001505
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001506 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001507 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001508
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001509 // Use pointer alignment for the vtable. Otherwise we would align them based
1510 // on the size of the initializer which doesn't make sense as only single
1511 // values are read.
1512 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1513 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1514
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001515 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1516 // we will emit the typeinfo for the fundamental types. This is the
1517 // same behaviour as GCC.
1518 const DeclContext *DC = RD->getDeclContext();
1519 if (RD->getIdentifier() &&
1520 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1521 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1522 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1523 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001524 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001525
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001526 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001527 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001528}
1529
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001530bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1531 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1532 if (Vptr.NearestVBase == nullptr)
1533 return false;
1534 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001535}
1536
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001537llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1538 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1539 const CXXRecordDecl *NearestVBase) {
1540
1541 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1542 NeedsVTTParameter(CGF.CurGD)) {
1543 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1544 NearestVBase);
1545 }
1546 return getVTableAddressPoint(Base, VTableClass);
1547}
1548
1549llvm::Constant *
1550ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1551 const CXXRecordDecl *VTableClass) {
1552 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001553
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001554 // Find the appropriate vtable within the vtable group, and the address point
1555 // within that vtable.
1556 VTableLayout::AddressPointLocation AddressPoint =
1557 CGM.getItaniumVTableContext()
1558 .getVTableLayout(VTableClass)
1559 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001560 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001561 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001562 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1563 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001564 };
1565
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001566 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1567 Indices, /*InBounds=*/true,
1568 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001569}
1570
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001571llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1572 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1573 const CXXRecordDecl *NearestVBase) {
1574 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1575 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1576
1577 // Get the secondary vpointer index.
1578 uint64_t VirtualPointerIndex =
1579 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1580
1581 /// Load the VTT.
1582 llvm::Value *VTT = CGF.LoadCXXVTT();
1583 if (VirtualPointerIndex)
1584 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1585
1586 // And load the address point from the VTT.
1587 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1588}
1589
1590llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1591 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1592 return getVTableAddressPoint(Base, VTableClass);
1593}
1594
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001595llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1596 CharUnits VPtrOffset) {
1597 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1598
1599 llvm::GlobalVariable *&VTable = VTables[RD];
1600 if (VTable)
1601 return VTable;
1602
Eric Christopherd160c502016-01-29 01:35:53 +00001603 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001604 CGM.addDeferredVTable(RD);
1605
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001606 SmallString<256> Name;
1607 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001608 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001609
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001610 const VTableLayout &VTLayout =
1611 CGM.getItaniumVTableContext().getVTableLayout(RD);
1612 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001613
1614 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001615 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001616 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001617
1618 if (RD->hasAttr<DLLImportAttr>())
1619 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1620 else if (RD->hasAttr<DLLExportAttr>())
1621 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1622
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001623 return VTable;
1624}
1625
John McCallb92ab1a2016-10-26 23:46:34 +00001626CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1627 GlobalDecl GD,
1628 Address This,
1629 llvm::Type *Ty,
1630 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001631 GD = GD.getCanonicalDecl();
1632 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001633 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1634 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001635
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001636 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001637 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001638 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001639 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001640 MethodDecl->getParent(), VTable,
1641 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1642 } else {
1643 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1644
1645 llvm::Value *VFuncPtr =
1646 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001647 auto *VFuncLoad =
1648 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1649
1650 // Add !invariant.load md to virtual function load to indicate that
1651 // function didn't change inside vtable.
1652 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1653 // help in devirtualization because it will only matter if we will have 2
1654 // the same virtual function loads from the same vtable load, which won't
1655 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1656 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1657 CGM.getCodeGenOpts().StrictVTablePointers)
1658 VFuncLoad->setMetadata(
1659 llvm::LLVMContext::MD_invariant_load,
1660 llvm::MDNode::get(CGM.getLLVMContext(),
1661 llvm::ArrayRef<llvm::Metadata *>()));
1662 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001663 }
John McCallb92ab1a2016-10-26 23:46:34 +00001664
1665 CGCallee Callee(MethodDecl, VFunc);
1666 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001667}
1668
David Majnemer0c0b6d92014-10-31 20:09:12 +00001669llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1670 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001671 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001672 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001673 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1674
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001675 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1676 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001677 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001678 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001679 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1680 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001681
John McCall7f416cc2015-09-08 08:05:57 +00001682 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1683 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001684 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001685 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001686}
1687
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001688void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001689 CodeGenVTables &VTables = CGM.getVTables();
1690 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001691 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001692}
1693
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001694bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001695 // We don't emit available_externally vtables if we are in -fapple-kext mode
1696 // because kext mode does not permit devirtualization.
1697 if (CGM.getLangOpts().AppleKext)
1698 return false;
1699
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001700 // If we don't have any not emitted inline virtual function, and if vtable is
1701 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001702 // FIXME we can still emit a copy of the vtable if we
1703 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001704 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001705}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001706static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001707 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001708 int64_t NonVirtualAdjustment,
1709 int64_t VirtualAdjustment,
1710 bool IsReturnAdjustment) {
1711 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001712 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001713
John McCall7f416cc2015-09-08 08:05:57 +00001714 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001715
John McCall7f416cc2015-09-08 08:05:57 +00001716 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001717 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001718 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1719 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001720 }
1721
John McCall7f416cc2015-09-08 08:05:57 +00001722 // Perform the virtual adjustment if we have one.
1723 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724 if (VirtualAdjustment) {
1725 llvm::Type *PtrDiffTy =
1726 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1727
John McCall7f416cc2015-09-08 08:05:57 +00001728 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001729 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1730
1731 llvm::Value *OffsetPtr =
1732 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1733
1734 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1735
1736 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001737 llvm::Value *Offset =
1738 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001739
1740 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001741 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1742 } else {
1743 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001744 }
1745
John McCall7f416cc2015-09-08 08:05:57 +00001746 // In a derived-to-base conversion, the non-virtual adjustment is
1747 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001748 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001749 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1750 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001751 }
1752
1753 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001754 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001755}
1756
1757llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001758 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001759 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001760 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1761 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001762 /*IsReturnAdjustment=*/false);
1763}
1764
1765llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001766ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001767 const ReturnAdjustment &RA) {
1768 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1769 RA.Virtual.Itanium.VBaseOffsetOffset,
1770 /*IsReturnAdjustment=*/true);
1771}
1772
John McCall5d865c322010-08-31 07:33:07 +00001773void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1774 RValue RV, QualType ResultType) {
1775 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1776 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1777
1778 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001779 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001780 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1781 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1782}
John McCall8ed55a52010-09-02 09:58:18 +00001783
1784/************************** Array allocation cookies **************************/
1785
John McCallb91cd662012-05-01 05:23:51 +00001786CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1787 // The array cookie is a size_t; pad that up to the element alignment.
1788 // The cookie is actually right-justified in that space.
1789 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1790 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001791}
1792
John McCall7f416cc2015-09-08 08:05:57 +00001793Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1794 Address NewPtr,
1795 llvm::Value *NumElements,
1796 const CXXNewExpr *expr,
1797 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001798 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001799
John McCall7f416cc2015-09-08 08:05:57 +00001800 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001801
John McCall9bca9232010-09-02 10:25:57 +00001802 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001803 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001804
1805 // The size of the cookie.
1806 CharUnits CookieSize =
1807 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001808 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001809
1810 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001811 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001812 CharUnits CookieOffset = CookieSize - SizeSize;
1813 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001814 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001815
1816 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001817 Address NumElementsPtr =
1818 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001819 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001820
1821 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001822 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001823 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001824 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001825 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1826 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001827 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001828 llvm::Constant *F =
1829 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001830 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001831 }
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 McCall7f416cc2015-09-08 08:05:57 +00001835 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001836}
1837
John McCallb91cd662012-05-01 05:23:51 +00001838llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001839 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001840 CharUnits cookieSize) {
1841 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001842 Address numElementsPtr = allocPtr;
1843 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001844 if (!numElementsOffset.isZero())
1845 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001846 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001847
John McCall7f416cc2015-09-08 08:05:57 +00001848 unsigned AS = allocPtr.getAddressSpace();
1849 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001850 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001851 return CGF.Builder.CreateLoad(numElementsPtr);
1852 // In asan mode emit a function call instead of a regular load and let the
1853 // run-time deal with it: if the shadow is properly poisoned return the
1854 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1855 // We can't simply ignore this load using nosanitize metadata because
1856 // the metadata may be lost.
1857 llvm::FunctionType *FTy =
1858 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1859 llvm::Constant *F =
1860 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001861 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001862}
1863
John McCallb91cd662012-05-01 05:23:51 +00001864CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001865 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001866 // struct array_cookie {
1867 // std::size_t element_size; // element_size != 0
1868 // std::size_t element_count;
1869 // };
John McCallc19c7062013-01-25 23:36:19 +00001870 // But the base ABI doesn't give anything an alignment greater than
1871 // 8, so we can dismiss this as typical ABI-author blindness to
1872 // actual language complexity and round up to the element alignment.
1873 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1874 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001875}
1876
John McCall7f416cc2015-09-08 08:05:57 +00001877Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1878 Address newPtr,
1879 llvm::Value *numElements,
1880 const CXXNewExpr *expr,
1881 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001882 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001883
John McCall8ed55a52010-09-02 09:58:18 +00001884 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001885 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001886
1887 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001888 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001889 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1890 getContext().getTypeSizeInChars(elementType).getQuantity());
1891 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001892
1893 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001894 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001895 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001896
1897 // Finally, compute a pointer to the actual data buffer by skipping
1898 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001899 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001900 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001901}
1902
John McCallb91cd662012-05-01 05:23:51 +00001903llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001904 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001905 CharUnits cookieSize) {
1906 // The number of elements is at offset sizeof(size_t) relative to
1907 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001908 Address numElementsPtr
1909 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001910
John McCall7f416cc2015-09-08 08:05:57 +00001911 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001912 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001913}
1914
John McCall68ff0372010-09-08 01:44:27 +00001915/*********************** Static local initialization **************************/
1916
1917static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001918 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001919 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001920 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001921 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001922 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001923 return CGM.CreateRuntimeFunction(
1924 FTy, "__cxa_guard_acquire",
1925 llvm::AttributeList::get(CGM.getLLVMContext(),
1926 llvm::AttributeList::FunctionIndex,
1927 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001928}
1929
1930static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001931 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001932 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001933 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001934 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001935 return CGM.CreateRuntimeFunction(
1936 FTy, "__cxa_guard_release",
1937 llvm::AttributeList::get(CGM.getLLVMContext(),
1938 llvm::AttributeList::FunctionIndex,
1939 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001940}
1941
1942static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001943 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001944 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001945 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001946 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001947 return CGM.CreateRuntimeFunction(
1948 FTy, "__cxa_guard_abort",
1949 llvm::AttributeList::get(CGM.getLLVMContext(),
1950 llvm::AttributeList::FunctionIndex,
1951 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001952}
1953
1954namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001955 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001956 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001957 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001958
Craig Topper4f12f102014-03-12 06:41:41 +00001959 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001960 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1961 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001962 }
1963 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001964}
John McCall68ff0372010-09-08 01:44:27 +00001965
1966/// The ARM code here follows the Itanium code closely enough that we
1967/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001968void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1969 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001970 llvm::GlobalVariable *var,
1971 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001972 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001973
Richard Smith62f19e72016-06-25 00:15:56 +00001974 // Inline variables that weren't instantiated from variable templates have
1975 // partially-ordered initialization within their translation unit.
1976 bool NonTemplateInline =
1977 D.isInline() &&
1978 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1979
1980 // We only need to use thread-safe statics for local non-TLS variables and
1981 // inline variables; other global initialization is always single-threaded
1982 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001983 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001984 (D.isLocalVarDecl() || NonTemplateInline) &&
1985 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001986
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001987 // If we have a global variable with internal linkage and thread-safe statics
1988 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001989 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1990
1991 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001992 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001993 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001994 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001995 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001996 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001997 // Guard variables are 64 bits in the generic ABI and size width on ARM
1998 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001999 if (UseARMGuardVarABI) {
2000 guardTy = CGF.SizeTy;
2001 guardAlignment = CGF.getSizeAlign();
2002 } else {
2003 guardTy = CGF.Int64Ty;
2004 guardAlignment = CharUnits::fromQuantity(
2005 CGM.getDataLayout().getABITypeAlignment(guardTy));
2006 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002007 }
John McCallb88a5662012-03-30 21:00:39 +00002008 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002009
John McCallb88a5662012-03-30 21:00:39 +00002010 // Create the guard variable if we don't already have it (as we
2011 // might if we're double-emitting this function body).
2012 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2013 if (!guard) {
2014 // Mangle the name for the guard.
2015 SmallString<256> guardName;
2016 {
2017 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002018 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002019 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002020
John McCallb88a5662012-03-30 21:00:39 +00002021 // Create the guard variable with a zero-initializer.
2022 // Just absorb linkage and visibility from the guarded variable.
2023 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2024 false, var->getLinkage(),
2025 llvm::ConstantInt::get(guardTy, 0),
2026 guardName.str());
2027 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002028 // If the variable is thread-local, so is its guard variable.
2029 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002030 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002031
Yaron Keren5bfa1082015-09-03 20:33:29 +00002032 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2033 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002034 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002035 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002036 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002037 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2038 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002039 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002040 // An inline variable's guard function is run from the per-TU
2041 // initialization function, not via a dedicated global ctor function, so
2042 // we can't put it in a comdat.
2043 if (!NonTemplateInline)
2044 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002045 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2046 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002047 }
2048
John McCallb88a5662012-03-30 21:00:39 +00002049 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2050 }
John McCall87590e62012-03-30 07:09:50 +00002051
John McCall7f416cc2015-09-08 08:05:57 +00002052 Address guardAddr = Address(guard, guardAlignment);
2053
John McCall68ff0372010-09-08 01:44:27 +00002054 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002055 //
John McCall68ff0372010-09-08 01:44:27 +00002056 // Itanium C++ ABI 3.3.2:
2057 // The following is pseudo-code showing how these functions can be used:
2058 // if (obj_guard.first_byte == 0) {
2059 // if ( __cxa_guard_acquire (&obj_guard) ) {
2060 // try {
2061 // ... initialize the object ...;
2062 // } catch (...) {
2063 // __cxa_guard_abort (&obj_guard);
2064 // throw;
2065 // }
2066 // ... queue object destructor with __cxa_atexit() ...;
2067 // __cxa_guard_release (&obj_guard);
2068 // }
2069 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002070
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002071 // Load the first byte of the guard variable.
2072 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002073 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002074
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002075 // Itanium ABI:
2076 // An implementation supporting thread-safety on multiprocessor
2077 // systems must also guarantee that references to the initialized
2078 // object do not occur before the load of the initialization flag.
2079 //
2080 // In LLVM, we do this by marking the load Acquire.
2081 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002082 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002083
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002084 // For ARM, we should only check the first bit, rather than the entire byte:
2085 //
2086 // ARM C++ ABI 3.2.3.1:
2087 // To support the potential use of initialization guard variables
2088 // as semaphores that are the target of ARM SWP and LDREX/STREX
2089 // synchronizing instructions we define a static initialization
2090 // guard variable to be a 4-byte aligned, 4-byte word with the
2091 // following inline access protocol.
2092 // #define INITIALIZED 1
2093 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2094 // if (__cxa_guard_acquire(&obj_guard))
2095 // ...
2096 // }
2097 //
2098 // and similarly for ARM64:
2099 //
2100 // ARM64 C++ ABI 3.2.2:
2101 // This ABI instead only specifies the value bit 0 of the static guard
2102 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2103 // variable is not initialized and 1 when it is.
2104 llvm::Value *V =
2105 (UseARMGuardVarABI && !useInt8GuardVariable)
2106 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2107 : LI;
2108 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002109
2110 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2111 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2112
2113 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002114 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002115
2116 CGF.EmitBlock(InitCheckBlock);
2117
2118 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002119 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002120 // Call __cxa_guard_acquire.
2121 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002122 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002123
2124 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2125
2126 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2127 InitBlock, EndBlock);
2128
2129 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002130 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002131
2132 CGF.EmitBlock(InitBlock);
2133 }
2134
2135 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002136 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002137
John McCall5aa52592011-06-17 07:33:57 +00002138 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002139 // Pop the guard-abort cleanup if we pushed one.
2140 CGF.PopCleanupBlock();
2141
2142 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002143 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2144 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002145 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002146 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002147 }
2148
2149 CGF.EmitBlock(EndBlock);
2150}
John McCallc84ed6a2012-05-01 06:13:13 +00002151
2152/// Register a global destructor using __cxa_atexit.
2153static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2154 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002155 llvm::Constant *addr,
2156 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002157 const char *Name = "__cxa_atexit";
2158 if (TLS) {
2159 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002160 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002161 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002162
John McCallc84ed6a2012-05-01 06:13:13 +00002163 // We're assuming that the destructor function is something we can
2164 // reasonably call with the default CC. Go ahead and cast it to the
2165 // right prototype.
2166 llvm::Type *dtorTy =
2167 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2168
2169 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2170 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2171 llvm::FunctionType *atexitTy =
2172 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2173
2174 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002175 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002176 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2177 fn->setDoesNotThrow();
2178
2179 // Create a variable that binds the atexit to this shared object.
2180 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002181 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2182 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2183 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002184
2185 llvm::Value *args[] = {
2186 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2187 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2188 handle
2189 };
John McCall882987f2013-02-28 19:01:20 +00002190 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002191}
2192
2193/// Register a global destructor as best as we know how.
2194void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002195 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002196 llvm::Constant *dtor,
2197 llvm::Constant *addr) {
2198 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002199 if (CGM.getCodeGenOpts().CXAAtExit)
2200 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2201
2202 if (D.getTLSKind())
2203 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002204
2205 // In Apple kexts, we want to add a global destructor entry.
2206 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002207 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002208 // Generate a global destructor entry.
2209 return CGM.AddCXXDtorEntry(dtor, addr);
2210 }
2211
David Blaikieebe87e12013-08-27 23:57:18 +00002212 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002213}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002214
David Majnemer9b21c332014-07-11 20:28:10 +00002215static bool isThreadWrapperReplaceable(const VarDecl *VD,
2216 CodeGen::CodeGenModule &CGM) {
2217 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002218 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002219 // the thread wrapper instead of directly referencing the backing variable.
2220 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002221 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002222}
2223
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002224/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002225/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002226/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002227static llvm::GlobalValue::LinkageTypes
2228getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2229 llvm::GlobalValue::LinkageTypes VarLinkage =
2230 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2231
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002232 // For internal linkage variables, we don't need an external or weak wrapper.
2233 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2234 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002235
David Majnemer9b21c332014-07-11 20:28:10 +00002236 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002237 if (isThreadWrapperReplaceable(VD, CGM))
2238 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2239 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2240 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002241 return llvm::GlobalValue::WeakODRLinkage;
2242}
2243
2244llvm::Function *
2245ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002246 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002247 // Mangle the name for the thread_local wrapper function.
2248 SmallString<256> WrapperName;
2249 {
2250 llvm::raw_svector_ostream Out(WrapperName);
2251 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002252 }
2253
Akira Hatanaka26907f92016-01-15 03:34:06 +00002254 // FIXME: If VD is a definition, we should regenerate the function attributes
2255 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002256 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002257 return cast<llvm::Function>(V);
2258
Akira Hatanaka26907f92016-01-15 03:34:06 +00002259 QualType RetQT = VD->getType();
2260 if (RetQT->isReferenceType())
2261 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002262
John McCallc56a8b32016-03-11 04:30:31 +00002263 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2264 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002265
2266 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002267 llvm::Function *Wrapper =
2268 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2269 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002270
2271 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2272
2273 if (VD->hasDefinition())
2274 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2275
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002276 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002277 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2278 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2279 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002280 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002281
2282 if (isThreadWrapperReplaceable(VD, CGM)) {
2283 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2284 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2285 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002286 return Wrapper;
2287}
2288
2289void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002290 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2291 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2292 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002293 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002294
2295 // Separate initializers into those with ordered (or partially-ordered)
2296 // initialization and those with unordered initialization.
2297 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2298 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2299 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2300 if (isTemplateInstantiation(
2301 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2302 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2303 CXXThreadLocalInits[I];
2304 else
2305 OrderedInits.push_back(CXXThreadLocalInits[I]);
2306 }
2307
2308 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002309 // Generate a guarded initialization function.
2310 llvm::FunctionType *FTy =
2311 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002312 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2313 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002314 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002315 /*TLS=*/true);
2316 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2317 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2318 llvm::GlobalVariable::InternalLinkage,
2319 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2320 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002321
2322 CharUnits GuardAlign = CharUnits::One();
2323 Guard->setAlignment(GuardAlign.getQuantity());
2324
Richard Smithfbe23692017-01-13 00:43:31 +00002325 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2326 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002327 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2328 if (CGM.getTarget().getTriple().isOSDarwin()) {
2329 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2330 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2331 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002332 }
Richard Smithfbe23692017-01-13 00:43:31 +00002333
2334 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002335 for (const VarDecl *VD : CXXThreadLocals) {
2336 llvm::GlobalVariable *Var =
2337 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002338 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002339
David Majnemer9b21c332014-07-11 20:28:10 +00002340 // Some targets require that all access to thread local variables go through
2341 // the thread wrapper. This means that we cannot attempt to create a thread
2342 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002343 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2344 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002345 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002346 }
David Majnemer9b21c332014-07-11 20:28:10 +00002347
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002348 // Mangle the name for the thread_local initialization function.
2349 SmallString<256> InitFnName;
2350 {
2351 llvm::raw_svector_ostream Out(InitFnName);
2352 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002353 }
2354
2355 // If we have a definition for the variable, emit the initialization
2356 // function as an alias to the global Init function (if any). Otherwise,
2357 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002358 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002359 bool InitIsInitFunc = false;
2360 if (VD->hasDefinition()) {
2361 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002362 llvm::Function *InitFuncToUse = InitFunc;
2363 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2364 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2365 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002366 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002367 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002368 } else {
2369 // Emit a weak global function referring to the initialization function.
2370 // This function will not exist if the TU defining the thread_local
2371 // variable in question does not need any dynamic initialization for
2372 // its thread_local variables.
2373 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002374 Init = llvm::Function::Create(FnTy,
2375 llvm::GlobalVariable::ExternalWeakLinkage,
2376 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002377 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002378 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002379 }
2380
2381 if (Init)
2382 Init->setVisibility(Var->getVisibility());
2383
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002384 llvm::LLVMContext &Context = CGM.getModule().getContext();
2385 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002386 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002387 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002388 if (Init) {
2389 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2390 if (isThreadWrapperReplaceable(VD, CGM))
2391 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2392 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002393 } else {
2394 // Don't know whether we have an init function. Call it if it exists.
2395 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2396 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2397 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2398 Builder.CreateCondBr(Have, InitBB, ExitBB);
2399
2400 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002401 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002402 Builder.CreateBr(ExitBB);
2403
2404 Builder.SetInsertPoint(ExitBB);
2405 }
2406
2407 // For a reference, the result of the wrapper function is a pointer to
2408 // the referenced object.
2409 llvm::Value *Val = Var;
2410 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002411 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2412 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002413 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002414 if (Val->getType() != Wrapper->getReturnType())
2415 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2416 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002417 Builder.CreateRet(Val);
2418 }
2419}
2420
Richard Smith0f383742014-03-26 22:48:22 +00002421LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2422 const VarDecl *VD,
2423 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002424 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002425 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002426
Manman Renb0b3af72015-12-17 00:42:36 +00002427 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002428 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002429
2430 LValue LV;
2431 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002432 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002433 else
Manman Renb0b3af72015-12-17 00:42:36 +00002434 LV = CGF.MakeAddrLValue(CallVal, LValType,
2435 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002436 // FIXME: need setObjCGCLValueClass?
2437 return LV;
2438}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002439
2440/// Return whether the given global decl needs a VTT parameter, which it does
2441/// if it's a base constructor or destructor with virtual bases.
2442bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2443 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2444
2445 // We don't have any virtual bases, just return early.
2446 if (!MD->getParent()->getNumVBases())
2447 return false;
2448
2449 // Check if we have a base constructor.
2450 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2451 return true;
2452
2453 // Check if we have a base destructor.
2454 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2455 return true;
2456
2457 return false;
2458}
David Majnemere2cb8d12014-07-07 06:20:47 +00002459
2460namespace {
2461class ItaniumRTTIBuilder {
2462 CodeGenModule &CGM; // Per-module state.
2463 llvm::LLVMContext &VMContext;
2464 const ItaniumCXXABI &CXXABI; // Per-module state.
2465
2466 /// Fields - The fields of the RTTI descriptor currently being built.
2467 SmallVector<llvm::Constant *, 16> Fields;
2468
2469 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2470 llvm::GlobalVariable *
2471 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2472
2473 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2474 /// descriptor of the given type.
2475 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2476
2477 /// BuildVTablePointer - Build the vtable pointer for the given type.
2478 void BuildVTablePointer(const Type *Ty);
2479
2480 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2481 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2482 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2483
2484 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2485 /// classes with bases that do not satisfy the abi::__si_class_type_info
2486 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2487 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2488
2489 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2490 /// for pointer types.
2491 void BuildPointerTypeInfo(QualType PointeeTy);
2492
2493 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2494 /// type_info for an object type.
2495 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2496
2497 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2498 /// struct, used for member pointer types.
2499 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2500
2501public:
2502 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2503 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2504
2505 // Pointer type info flags.
2506 enum {
2507 /// PTI_Const - Type has const qualifier.
2508 PTI_Const = 0x1,
2509
2510 /// PTI_Volatile - Type has volatile qualifier.
2511 PTI_Volatile = 0x2,
2512
2513 /// PTI_Restrict - Type has restrict qualifier.
2514 PTI_Restrict = 0x4,
2515
2516 /// PTI_Incomplete - Type is incomplete.
2517 PTI_Incomplete = 0x8,
2518
2519 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2520 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002521 PTI_ContainingClassIncomplete = 0x10,
2522
2523 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2524 //PTI_TransactionSafe = 0x20,
2525
2526 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2527 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002528 };
2529
2530 // VMI type info flags.
2531 enum {
2532 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2533 VMI_NonDiamondRepeat = 0x1,
2534
2535 /// VMI_DiamondShaped - Class is diamond shaped.
2536 VMI_DiamondShaped = 0x2
2537 };
2538
2539 // Base class type info flags.
2540 enum {
2541 /// BCTI_Virtual - Base class is virtual.
2542 BCTI_Virtual = 0x1,
2543
2544 /// BCTI_Public - Base class is public.
2545 BCTI_Public = 0x2
2546 };
2547
2548 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2549 ///
2550 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002551 /// \param DLLExport - true to mark the RTTI value as DLLExport
2552 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2553 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002554};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002555}
David Majnemere2cb8d12014-07-07 06:20:47 +00002556
2557llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2558 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002559 SmallString<256> Name;
2560 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002561 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002562
2563 // We know that the mangled name of the type starts at index 4 of the
2564 // mangled name of the typename, so we can just index into it in order to
2565 // get the mangled name of the type.
2566 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2567 Name.substr(4));
2568
2569 llvm::GlobalVariable *GV =
2570 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2571
2572 GV->setInitializer(Init);
2573
2574 return GV;
2575}
2576
2577llvm::Constant *
2578ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2579 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002580 SmallString<256> Name;
2581 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002582 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002583
2584 // Look for an existing global.
2585 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2586
2587 if (!GV) {
2588 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002589 // Note for the future: If we would ever like to do deferred emission of
2590 // RTTI, check if emitting vtables opportunistically need any adjustment.
2591
David Majnemere2cb8d12014-07-07 06:20:47 +00002592 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2593 /*Constant=*/true,
2594 llvm::GlobalValue::ExternalLinkage, nullptr,
2595 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002596 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2597 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2598 if (RD->hasAttr<DLLImportAttr>())
2599 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2600 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002601 }
2602
2603 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2604}
2605
2606/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2607/// info for that type is defined in the standard library.
2608static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2609 // Itanium C++ ABI 2.9.2:
2610 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2611 // the run-time support library. Specifically, the run-time support
2612 // library should contain type_info objects for the types X, X* and
2613 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2614 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2615 // long, unsigned long, long long, unsigned long long, float, double,
2616 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2617 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002618 //
2619 // GCC also emits RTTI for __int128.
2620 // FIXME: We do not emit RTTI information for decimal types here.
2621
2622 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002623 switch (Ty->getKind()) {
2624 case BuiltinType::Void:
2625 case BuiltinType::NullPtr:
2626 case BuiltinType::Bool:
2627 case BuiltinType::WChar_S:
2628 case BuiltinType::WChar_U:
2629 case BuiltinType::Char_U:
2630 case BuiltinType::Char_S:
2631 case BuiltinType::UChar:
2632 case BuiltinType::SChar:
2633 case BuiltinType::Short:
2634 case BuiltinType::UShort:
2635 case BuiltinType::Int:
2636 case BuiltinType::UInt:
2637 case BuiltinType::Long:
2638 case BuiltinType::ULong:
2639 case BuiltinType::LongLong:
2640 case BuiltinType::ULongLong:
2641 case BuiltinType::Half:
2642 case BuiltinType::Float:
2643 case BuiltinType::Double:
2644 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002645 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002646 case BuiltinType::Char16:
2647 case BuiltinType::Char32:
2648 case BuiltinType::Int128:
2649 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002650 return true;
2651
Alexey Bader954ba212016-04-08 13:40:33 +00002652#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2653 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002654#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002655 case BuiltinType::OCLSampler:
2656 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002657 case BuiltinType::OCLClkEvent:
2658 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002659 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002660 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002661
2662 case BuiltinType::Dependent:
2663#define BUILTIN_TYPE(Id, SingletonId)
2664#define PLACEHOLDER_TYPE(Id, SingletonId) \
2665 case BuiltinType::Id:
2666#include "clang/AST/BuiltinTypes.def"
2667 llvm_unreachable("asking for RRTI for a placeholder type!");
2668
2669 case BuiltinType::ObjCId:
2670 case BuiltinType::ObjCClass:
2671 case BuiltinType::ObjCSel:
2672 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2673 }
2674
2675 llvm_unreachable("Invalid BuiltinType Kind!");
2676}
2677
2678static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2679 QualType PointeeTy = PointerTy->getPointeeType();
2680 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2681 if (!BuiltinTy)
2682 return false;
2683
2684 // Check the qualifiers.
2685 Qualifiers Quals = PointeeTy.getQualifiers();
2686 Quals.removeConst();
2687
2688 if (!Quals.empty())
2689 return false;
2690
2691 return TypeInfoIsInStandardLibrary(BuiltinTy);
2692}
2693
2694/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2695/// information for the given type exists in the standard library.
2696static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2697 // Type info for builtin types is defined in the standard library.
2698 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2699 return TypeInfoIsInStandardLibrary(BuiltinTy);
2700
2701 // Type info for some pointer types to builtin types is defined in the
2702 // standard library.
2703 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2704 return TypeInfoIsInStandardLibrary(PointerTy);
2705
2706 return false;
2707}
2708
2709/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2710/// the given type exists somewhere else, and that we should not emit the type
2711/// information in this translation unit. Assumes that it is not a
2712/// standard-library type.
2713static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2714 QualType Ty) {
2715 ASTContext &Context = CGM.getContext();
2716
2717 // If RTTI is disabled, assume it might be disabled in the
2718 // translation unit that defines any potential key function, too.
2719 if (!Context.getLangOpts().RTTI) return false;
2720
2721 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2722 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2723 if (!RD->hasDefinition())
2724 return false;
2725
2726 if (!RD->isDynamicClass())
2727 return false;
2728
2729 // FIXME: this may need to be reconsidered if the key function
2730 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002731 // N.B. We must always emit the RTTI data ourselves if there exists a key
2732 // function.
2733 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002734 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002735 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2736 ? false
2737 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002738
David Majnemerbe9022c2015-08-06 20:56:55 +00002739 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002740 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002741 }
2742
2743 return false;
2744}
2745
2746/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2747static bool IsIncompleteClassType(const RecordType *RecordTy) {
2748 return !RecordTy->getDecl()->isCompleteDefinition();
2749}
2750
2751/// ContainsIncompleteClassType - Returns whether the given type contains an
2752/// incomplete class type. This is true if
2753///
2754/// * The given type is an incomplete class type.
2755/// * The given type is a pointer type whose pointee type contains an
2756/// incomplete class type.
2757/// * The given type is a member pointer type whose class is an incomplete
2758/// class type.
2759/// * The given type is a member pointer type whoise pointee type contains an
2760/// incomplete class type.
2761/// is an indirect or direct pointer to an incomplete class type.
2762static bool ContainsIncompleteClassType(QualType Ty) {
2763 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2764 if (IsIncompleteClassType(RecordTy))
2765 return true;
2766 }
2767
2768 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2769 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2770
2771 if (const MemberPointerType *MemberPointerTy =
2772 dyn_cast<MemberPointerType>(Ty)) {
2773 // Check if the class type is incomplete.
2774 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2775 if (IsIncompleteClassType(ClassType))
2776 return true;
2777
2778 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2779 }
2780
2781 return false;
2782}
2783
2784// CanUseSingleInheritance - Return whether the given record decl has a "single,
2785// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2786// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2787static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2788 // Check the number of bases.
2789 if (RD->getNumBases() != 1)
2790 return false;
2791
2792 // Get the base.
2793 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2794
2795 // Check that the base is not virtual.
2796 if (Base->isVirtual())
2797 return false;
2798
2799 // Check that the base is public.
2800 if (Base->getAccessSpecifier() != AS_public)
2801 return false;
2802
2803 // Check that the class is dynamic iff the base is.
2804 const CXXRecordDecl *BaseDecl =
2805 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2806 if (!BaseDecl->isEmpty() &&
2807 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2808 return false;
2809
2810 return true;
2811}
2812
2813void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2814 // abi::__class_type_info.
2815 static const char * const ClassTypeInfo =
2816 "_ZTVN10__cxxabiv117__class_type_infoE";
2817 // abi::__si_class_type_info.
2818 static const char * const SIClassTypeInfo =
2819 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2820 // abi::__vmi_class_type_info.
2821 static const char * const VMIClassTypeInfo =
2822 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2823
2824 const char *VTableName = nullptr;
2825
2826 switch (Ty->getTypeClass()) {
2827#define TYPE(Class, Base)
2828#define ABSTRACT_TYPE(Class, Base)
2829#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2830#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2831#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2832#include "clang/AST/TypeNodes.def"
2833 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2834
2835 case Type::LValueReference:
2836 case Type::RValueReference:
2837 llvm_unreachable("References shouldn't get here");
2838
2839 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002840 case Type::DeducedTemplateSpecialization:
2841 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002842
Xiuli Pan9c14e282016-01-09 12:53:17 +00002843 case Type::Pipe:
2844 llvm_unreachable("Pipe types shouldn't get here");
2845
David Majnemere2cb8d12014-07-07 06:20:47 +00002846 case Type::Builtin:
2847 // GCC treats vector and complex types as fundamental types.
2848 case Type::Vector:
2849 case Type::ExtVector:
2850 case Type::Complex:
2851 case Type::Atomic:
2852 // FIXME: GCC treats block pointers as fundamental types?!
2853 case Type::BlockPointer:
2854 // abi::__fundamental_type_info.
2855 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2856 break;
2857
2858 case Type::ConstantArray:
2859 case Type::IncompleteArray:
2860 case Type::VariableArray:
2861 // abi::__array_type_info.
2862 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2863 break;
2864
2865 case Type::FunctionNoProto:
2866 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002867 // abi::__function_type_info.
2868 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002869 break;
2870
2871 case Type::Enum:
2872 // abi::__enum_type_info.
2873 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2874 break;
2875
2876 case Type::Record: {
2877 const CXXRecordDecl *RD =
2878 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2879
2880 if (!RD->hasDefinition() || !RD->getNumBases()) {
2881 VTableName = ClassTypeInfo;
2882 } else if (CanUseSingleInheritance(RD)) {
2883 VTableName = SIClassTypeInfo;
2884 } else {
2885 VTableName = VMIClassTypeInfo;
2886 }
2887
2888 break;
2889 }
2890
2891 case Type::ObjCObject:
2892 // Ignore protocol qualifiers.
2893 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2894
2895 // Handle id and Class.
2896 if (isa<BuiltinType>(Ty)) {
2897 VTableName = ClassTypeInfo;
2898 break;
2899 }
2900
2901 assert(isa<ObjCInterfaceType>(Ty));
2902 // Fall through.
2903
2904 case Type::ObjCInterface:
2905 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2906 VTableName = SIClassTypeInfo;
2907 } else {
2908 VTableName = ClassTypeInfo;
2909 }
2910 break;
2911
2912 case Type::ObjCObjectPointer:
2913 case Type::Pointer:
2914 // abi::__pointer_type_info.
2915 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2916 break;
2917
2918 case Type::MemberPointer:
2919 // abi::__pointer_to_member_type_info.
2920 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2921 break;
2922 }
2923
2924 llvm::Constant *VTable =
2925 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2926
2927 llvm::Type *PtrDiffTy =
2928 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2929
2930 // The vtable address point is 2.
2931 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002932 VTable =
2933 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002934 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2935
2936 Fields.push_back(VTable);
2937}
2938
2939/// \brief Return the linkage that the type info and type info name constants
2940/// should have for the given type.
2941static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2942 QualType Ty) {
2943 // Itanium C++ ABI 2.9.5p7:
2944 // In addition, it and all of the intermediate abi::__pointer_type_info
2945 // structs in the chain down to the abi::__class_type_info for the
2946 // incomplete class type must be prevented from resolving to the
2947 // corresponding type_info structs for the complete class type, possibly
2948 // by making them local static objects. Finally, a dummy class RTTI is
2949 // generated for the incomplete type that will not resolve to the final
2950 // complete class RTTI (because the latter need not exist), possibly by
2951 // making it a local static object.
2952 if (ContainsIncompleteClassType(Ty))
2953 return llvm::GlobalValue::InternalLinkage;
2954
2955 switch (Ty->getLinkage()) {
2956 case NoLinkage:
2957 case InternalLinkage:
2958 case UniqueExternalLinkage:
2959 return llvm::GlobalValue::InternalLinkage;
2960
2961 case VisibleNoLinkage:
2962 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002963 // RTTI is not enabled, which means that this type info struct is going
2964 // to be used for exception handling. Give it linkonce_odr linkage.
2965 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002966 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002967
2968 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2969 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2970 if (RD->hasAttr<WeakAttr>())
2971 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002972 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00002973 if (RD->hasAttr<DLLImportAttr>() &&
2974 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002975 return llvm::GlobalValue::ExternalLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002976 if (RD->isDynamicClass()) {
2977 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2978 // MinGW won't export the RTTI information when there is a key function.
2979 // Make sure we emit our own copy instead of attempting to dllimport it.
2980 if (RD->hasAttr<DLLImportAttr>() &&
2981 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2982 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2983 return LT;
2984 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002985 }
2986
2987 return llvm::GlobalValue::LinkOnceODRLinkage;
2988 }
2989
2990 llvm_unreachable("Invalid linkage!");
2991}
2992
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002993llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
2994 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002995 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002996 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002997
2998 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002999 SmallString<256> Name;
3000 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003001 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003002
3003 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3004 if (OldGV && !OldGV->isDeclaration()) {
3005 assert(!OldGV->hasAvailableExternallyLinkage() &&
3006 "available_externally typeinfos not yet implemented");
3007
3008 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3009 }
3010
3011 // Check if there is already an external RTTI descriptor for this type.
3012 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3013 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3014 return GetAddrOfExternalRTTIDescriptor(Ty);
3015
3016 // Emit the standard library with external linkage.
3017 llvm::GlobalVariable::LinkageTypes Linkage;
3018 if (IsStdLib)
3019 Linkage = llvm::GlobalValue::ExternalLinkage;
3020 else
3021 Linkage = getTypeInfoLinkage(CGM, Ty);
3022
3023 // Add the vtable pointer.
3024 BuildVTablePointer(cast<Type>(Ty));
3025
3026 // And the name.
3027 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3028 llvm::Constant *TypeNameField;
3029
3030 // If we're supposed to demote the visibility, be sure to set a flag
3031 // to use a string comparison for type_info comparisons.
3032 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3033 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3034 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3035 // The flag is the sign bit, which on ARM64 is defined to be clear
3036 // for global pointers. This is very ARM64-specific.
3037 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3038 llvm::Constant *flag =
3039 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3040 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3041 TypeNameField =
3042 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3043 } else {
3044 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3045 }
3046 Fields.push_back(TypeNameField);
3047
3048 switch (Ty->getTypeClass()) {
3049#define TYPE(Class, Base)
3050#define ABSTRACT_TYPE(Class, Base)
3051#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3052#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3053#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3054#include "clang/AST/TypeNodes.def"
3055 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3056
3057 // GCC treats vector types as fundamental types.
3058 case Type::Builtin:
3059 case Type::Vector:
3060 case Type::ExtVector:
3061 case Type::Complex:
3062 case Type::BlockPointer:
3063 // Itanium C++ ABI 2.9.5p4:
3064 // abi::__fundamental_type_info adds no data members to std::type_info.
3065 break;
3066
3067 case Type::LValueReference:
3068 case Type::RValueReference:
3069 llvm_unreachable("References shouldn't get here");
3070
3071 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003072 case Type::DeducedTemplateSpecialization:
3073 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003074
Xiuli Pan9c14e282016-01-09 12:53:17 +00003075 case Type::Pipe:
3076 llvm_unreachable("Pipe type shouldn't get here");
3077
David Majnemere2cb8d12014-07-07 06:20:47 +00003078 case Type::ConstantArray:
3079 case Type::IncompleteArray:
3080 case Type::VariableArray:
3081 // Itanium C++ ABI 2.9.5p5:
3082 // abi::__array_type_info adds no data members to std::type_info.
3083 break;
3084
3085 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003086 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003087 // Itanium C++ ABI 2.9.5p5:
3088 // abi::__function_type_info adds no data members to std::type_info.
3089 break;
3090
3091 case Type::Enum:
3092 // Itanium C++ ABI 2.9.5p5:
3093 // abi::__enum_type_info adds no data members to std::type_info.
3094 break;
3095
3096 case Type::Record: {
3097 const CXXRecordDecl *RD =
3098 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3099 if (!RD->hasDefinition() || !RD->getNumBases()) {
3100 // We don't need to emit any fields.
3101 break;
3102 }
3103
3104 if (CanUseSingleInheritance(RD))
3105 BuildSIClassTypeInfo(RD);
3106 else
3107 BuildVMIClassTypeInfo(RD);
3108
3109 break;
3110 }
3111
3112 case Type::ObjCObject:
3113 case Type::ObjCInterface:
3114 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3115 break;
3116
3117 case Type::ObjCObjectPointer:
3118 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3119 break;
3120
3121 case Type::Pointer:
3122 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3123 break;
3124
3125 case Type::MemberPointer:
3126 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3127 break;
3128
3129 case Type::Atomic:
3130 // No fields, at least for the moment.
3131 break;
3132 }
3133
3134 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3135
Rafael Espindolacb92c192015-01-15 23:18:01 +00003136 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003137 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003138 new llvm::GlobalVariable(M, Init->getType(),
3139 /*Constant=*/true, Linkage, Init, Name);
3140
David Majnemere2cb8d12014-07-07 06:20:47 +00003141 // If there's already an old global variable, replace it with the new one.
3142 if (OldGV) {
3143 GV->takeName(OldGV);
3144 llvm::Constant *NewPtr =
3145 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3146 OldGV->replaceAllUsesWith(NewPtr);
3147 OldGV->eraseFromParent();
3148 }
3149
Yaron Keren04da2382015-07-29 15:42:28 +00003150 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3151 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3152
David Majnemere2cb8d12014-07-07 06:20:47 +00003153 // The Itanium ABI specifies that type_info objects must be globally
3154 // unique, with one exception: if the type is an incomplete class
3155 // type or a (possibly indirect) pointer to one. That exception
3156 // affects the general case of comparing type_info objects produced
3157 // by the typeid operator, which is why the comparison operators on
3158 // std::type_info generally use the type_info name pointers instead
3159 // of the object addresses. However, the language's built-in uses
3160 // of RTTI generally require class types to be complete, even when
3161 // manipulating pointers to those class types. This allows the
3162 // implementation of dynamic_cast to rely on address equality tests,
3163 // which is much faster.
3164
3165 // All of this is to say that it's important that both the type_info
3166 // object and the type_info name be uniqued when weakly emitted.
3167
3168 // Give the type_info object and name the formal visibility of the
3169 // type itself.
3170 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3171 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3172 // If the linkage is local, only default visibility makes sense.
3173 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3174 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3175 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3176 else
3177 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003178
David Majnemere2cb8d12014-07-07 06:20:47 +00003179 TypeName->setVisibility(llvmVisibility);
3180 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003181
3182 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3183 auto RD = Ty->getAsCXXRecordDecl();
3184 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3185 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3186 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003187 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3188 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003189 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3190 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3191
3192 // Because the typename and the typeinfo are DLL import, convert them to
3193 // declarations rather than definitions. The initializers still need to
3194 // be constructed to calculate the type for the declarations.
3195 TypeName->setInitializer(nullptr);
3196 GV->setInitializer(nullptr);
3197 }
3198 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003199
3200 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3201}
3202
David Majnemere2cb8d12014-07-07 06:20:47 +00003203/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3204/// for the given Objective-C object type.
3205void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3206 // Drop qualifiers.
3207 const Type *T = OT->getBaseType().getTypePtr();
3208 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3209
3210 // The builtin types are abi::__class_type_infos and don't require
3211 // extra fields.
3212 if (isa<BuiltinType>(T)) return;
3213
3214 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3215 ObjCInterfaceDecl *Super = Class->getSuperClass();
3216
3217 // Root classes are also __class_type_info.
3218 if (!Super) return;
3219
3220 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3221
3222 // Everything else is single inheritance.
3223 llvm::Constant *BaseTypeInfo =
3224 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3225 Fields.push_back(BaseTypeInfo);
3226}
3227
3228/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3229/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3230void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3231 // Itanium C++ ABI 2.9.5p6b:
3232 // It adds to abi::__class_type_info a single member pointing to the
3233 // type_info structure for the base type,
3234 llvm::Constant *BaseTypeInfo =
3235 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3236 Fields.push_back(BaseTypeInfo);
3237}
3238
3239namespace {
3240 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3241 /// a class hierarchy.
3242 struct SeenBases {
3243 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3244 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3245 };
3246}
3247
3248/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3249/// abi::__vmi_class_type_info.
3250///
3251static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3252 SeenBases &Bases) {
3253
3254 unsigned Flags = 0;
3255
3256 const CXXRecordDecl *BaseDecl =
3257 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3258
3259 if (Base->isVirtual()) {
3260 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003261 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003262 // If this virtual base has been seen before, then the class is diamond
3263 // shaped.
3264 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3265 } else {
3266 if (Bases.NonVirtualBases.count(BaseDecl))
3267 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3268 }
3269 } else {
3270 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003271 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003272 // If this non-virtual base has been seen before, then the class has non-
3273 // diamond shaped repeated inheritance.
3274 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3275 } else {
3276 if (Bases.VirtualBases.count(BaseDecl))
3277 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3278 }
3279 }
3280
3281 // Walk all bases.
3282 for (const auto &I : BaseDecl->bases())
3283 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3284
3285 return Flags;
3286}
3287
3288static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3289 unsigned Flags = 0;
3290 SeenBases Bases;
3291
3292 // Walk all bases.
3293 for (const auto &I : RD->bases())
3294 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3295
3296 return Flags;
3297}
3298
3299/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3300/// classes with bases that do not satisfy the abi::__si_class_type_info
3301/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3302void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3303 llvm::Type *UnsignedIntLTy =
3304 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3305
3306 // Itanium C++ ABI 2.9.5p6c:
3307 // __flags is a word with flags describing details about the class
3308 // structure, which may be referenced by using the __flags_masks
3309 // enumeration. These flags refer to both direct and indirect bases.
3310 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3311 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3312
3313 // Itanium C++ ABI 2.9.5p6c:
3314 // __base_count is a word with the number of direct proper base class
3315 // descriptions that follow.
3316 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3317
3318 if (!RD->getNumBases())
3319 return;
3320
David Majnemere2cb8d12014-07-07 06:20:47 +00003321 // Now add the base class descriptions.
3322
3323 // Itanium C++ ABI 2.9.5p6c:
3324 // __base_info[] is an array of base class descriptions -- one for every
3325 // direct proper base. Each description is of the type:
3326 //
3327 // struct abi::__base_class_type_info {
3328 // public:
3329 // const __class_type_info *__base_type;
3330 // long __offset_flags;
3331 //
3332 // enum __offset_flags_masks {
3333 // __virtual_mask = 0x1,
3334 // __public_mask = 0x2,
3335 // __offset_shift = 8
3336 // };
3337 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003338
3339 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3340 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3341 // LLP64 platforms.
3342 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3343 // LLP64 platforms.
3344 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3345 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3346 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3347 OffsetFlagsTy = CGM.getContext().LongLongTy;
3348 llvm::Type *OffsetFlagsLTy =
3349 CGM.getTypes().ConvertType(OffsetFlagsTy);
3350
David Majnemere2cb8d12014-07-07 06:20:47 +00003351 for (const auto &Base : RD->bases()) {
3352 // The __base_type member points to the RTTI for the base type.
3353 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3354
3355 const CXXRecordDecl *BaseDecl =
3356 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3357
3358 int64_t OffsetFlags = 0;
3359
3360 // All but the lower 8 bits of __offset_flags are a signed offset.
3361 // For a non-virtual base, this is the offset in the object of the base
3362 // subobject. For a virtual base, this is the offset in the virtual table of
3363 // the virtual base offset for the virtual base referenced (negative).
3364 CharUnits Offset;
3365 if (Base.isVirtual())
3366 Offset =
3367 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3368 else {
3369 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3370 Offset = Layout.getBaseClassOffset(BaseDecl);
3371 };
3372
3373 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3374
3375 // The low-order byte of __offset_flags contains flags, as given by the
3376 // masks from the enumeration __offset_flags_masks.
3377 if (Base.isVirtual())
3378 OffsetFlags |= BCTI_Virtual;
3379 if (Base.getAccessSpecifier() == AS_public)
3380 OffsetFlags |= BCTI_Public;
3381
Reid Klecknerd8b04662016-08-25 22:16:30 +00003382 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003383 }
3384}
3385
Richard Smitha7d93782016-12-01 03:32:42 +00003386/// Compute the flags for a __pbase_type_info, and remove the corresponding
3387/// pieces from \p Type.
3388static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3389 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003390
Richard Smitha7d93782016-12-01 03:32:42 +00003391 if (Type.isConstQualified())
3392 Flags |= ItaniumRTTIBuilder::PTI_Const;
3393 if (Type.isVolatileQualified())
3394 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3395 if (Type.isRestrictQualified())
3396 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3397 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003398
3399 // Itanium C++ ABI 2.9.5p7:
3400 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3401 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003402 if (ContainsIncompleteClassType(Type))
3403 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3404
3405 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3406 if (Proto->isNothrow(Ctx)) {
3407 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3408 Type = Ctx.getFunctionType(
3409 Proto->getReturnType(), Proto->getParamTypes(),
3410 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3411 }
3412 }
3413
3414 return Flags;
3415}
3416
3417/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3418/// used for pointer types.
3419void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3420 // Itanium C++ ABI 2.9.5p7:
3421 // __flags is a flag word describing the cv-qualification and other
3422 // attributes of the type pointed to
3423 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003424
3425 llvm::Type *UnsignedIntLTy =
3426 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3427 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3428
3429 // Itanium C++ ABI 2.9.5p7:
3430 // __pointee is a pointer to the std::type_info derivation for the
3431 // unqualified type being pointed to.
3432 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003433 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003434 Fields.push_back(PointeeTypeInfo);
3435}
3436
3437/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3438/// struct, used for member pointer types.
3439void
3440ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3441 QualType PointeeTy = Ty->getPointeeType();
3442
David Majnemere2cb8d12014-07-07 06:20:47 +00003443 // Itanium C++ ABI 2.9.5p7:
3444 // __flags is a flag word describing the cv-qualification and other
3445 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003446 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003447
3448 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003449 if (IsIncompleteClassType(ClassType))
3450 Flags |= PTI_ContainingClassIncomplete;
3451
3452 llvm::Type *UnsignedIntLTy =
3453 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3454 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3455
3456 // Itanium C++ ABI 2.9.5p7:
3457 // __pointee is a pointer to the std::type_info derivation for the
3458 // unqualified type being pointed to.
3459 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003460 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003461 Fields.push_back(PointeeTypeInfo);
3462
3463 // Itanium C++ ABI 2.9.5p9:
3464 // __context is a pointer to an abi::__class_type_info corresponding to the
3465 // class type containing the member pointed to
3466 // (e.g., the "A" in "int A::*").
3467 Fields.push_back(
3468 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3469}
3470
David Majnemer443250f2015-03-17 20:35:00 +00003471llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003472 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3473}
3474
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003475void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3476 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003477 QualType PointerType = getContext().getPointerType(Type);
3478 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003479 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3480 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3481 DLLExport);
3482 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3483 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003484}
3485
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003486void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003487 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003488 QualType FundamentalTypes[] = {
3489 getContext().VoidTy, getContext().NullPtrTy,
3490 getContext().BoolTy, getContext().WCharTy,
3491 getContext().CharTy, getContext().UnsignedCharTy,
3492 getContext().SignedCharTy, getContext().ShortTy,
3493 getContext().UnsignedShortTy, getContext().IntTy,
3494 getContext().UnsignedIntTy, getContext().LongTy,
3495 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003496 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3497 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003498 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003499 getContext().LongDoubleTy, getContext().Float128Ty,
3500 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003501 };
3502 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003503 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003504}
3505
3506/// What sort of uniqueness rules should we use for the RTTI for the
3507/// given type?
3508ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3509 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3510 if (shouldRTTIBeUnique())
3511 return RUK_Unique;
3512
3513 // It's only necessary for linkonce_odr or weak_odr linkage.
3514 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3515 Linkage != llvm::GlobalValue::WeakODRLinkage)
3516 return RUK_Unique;
3517
3518 // It's only necessary with default visibility.
3519 if (CanTy->getVisibility() != DefaultVisibility)
3520 return RUK_Unique;
3521
3522 // If we're not required to publish this symbol, hide it.
3523 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3524 return RUK_NonUniqueHidden;
3525
3526 // If we're required to publish this symbol, as we might be under an
3527 // explicit instantiation, leave it with default visibility but
3528 // enable string-comparisons.
3529 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3530 return RUK_NonUniqueVisible;
3531}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003532
Rafael Espindola1e4df922014-09-16 15:18:21 +00003533// Find out how to codegen the complete destructor and constructor
3534namespace {
3535enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3536}
3537static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3538 const CXXMethodDecl *MD) {
3539 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3540 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003541
Rafael Espindola1e4df922014-09-16 15:18:21 +00003542 // The complete and base structors are not equivalent if there are any virtual
3543 // bases, so emit separate functions.
3544 if (MD->getParent()->getNumVBases())
3545 return StructorCodegen::Emit;
3546
3547 GlobalDecl AliasDecl;
3548 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3549 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3550 } else {
3551 const auto *CD = cast<CXXConstructorDecl>(MD);
3552 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3553 }
3554 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3555
3556 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3557 return StructorCodegen::RAUW;
3558
3559 // FIXME: Should we allow available_externally aliases?
3560 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3561 return StructorCodegen::RAUW;
3562
Rafael Espindola0806f982014-09-16 20:19:43 +00003563 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003564 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3565 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3566 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003567 return StructorCodegen::COMDAT;
3568 return StructorCodegen::Emit;
3569 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003570
3571 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003572}
3573
Rafael Espindola1e4df922014-09-16 15:18:21 +00003574static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3575 GlobalDecl AliasDecl,
3576 GlobalDecl TargetDecl) {
3577 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3578
3579 StringRef MangledName = CGM.getMangledName(AliasDecl);
3580 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3581 if (Entry && !Entry->isDeclaration())
3582 return;
3583
3584 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003585
3586 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003587 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003588
3589 // Switch any previous uses to the alias.
3590 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003591 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003592 "declaration exists with different type");
3593 Alias->takeName(Entry);
3594 Entry->replaceAllUsesWith(Alias);
3595 Entry->eraseFromParent();
3596 } else {
3597 Alias->setName(MangledName);
3598 }
3599
3600 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003601 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003602}
3603
3604void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3605 StructorType Type) {
3606 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3607 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3608
3609 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3610
3611 if (Type == StructorType::Complete) {
3612 GlobalDecl CompleteDecl;
3613 GlobalDecl BaseDecl;
3614 if (CD) {
3615 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3616 BaseDecl = GlobalDecl(CD, Ctor_Base);
3617 } else {
3618 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3619 BaseDecl = GlobalDecl(DD, Dtor_Base);
3620 }
3621
3622 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3623 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3624 return;
3625 }
3626
3627 if (CGType == StructorCodegen::RAUW) {
3628 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003629 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003630 CGM.addReplacement(MangledName, Aliasee);
3631 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003632 }
3633 }
3634
3635 // The base destructor is equivalent to the base destructor of its
3636 // base class if there is exactly one non-virtual base class with a
3637 // non-trivial destructor, there are no fields with a non-trivial
3638 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003639 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3640 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003641 return;
3642
Rafael Espindola1e4df922014-09-16 15:18:21 +00003643 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003644
Rafael Espindola1e4df922014-09-16 15:18:21 +00003645 if (CGType == StructorCodegen::COMDAT) {
3646 SmallString<256> Buffer;
3647 llvm::raw_svector_ostream Out(Buffer);
3648 if (DD)
3649 getMangleContext().mangleCXXDtorComdat(DD, Out);
3650 else
3651 getMangleContext().mangleCXXCtorComdat(CD, Out);
3652 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3653 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003654 } else {
3655 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003656 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003657}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003658
3659static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3660 // void *__cxa_begin_catch(void*);
3661 llvm::FunctionType *FTy = llvm::FunctionType::get(
3662 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3663
3664 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3665}
3666
3667static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3668 // void __cxa_end_catch();
3669 llvm::FunctionType *FTy =
3670 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3671
3672 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3673}
3674
3675static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3676 // void *__cxa_get_exception_ptr(void*);
3677 llvm::FunctionType *FTy = llvm::FunctionType::get(
3678 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3679
3680 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3681}
3682
3683namespace {
3684 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3685 /// exception type lets us state definitively that the thrown exception
3686 /// type does not have a destructor. In particular:
3687 /// - Catch-alls tell us nothing, so we have to conservatively
3688 /// assume that the thrown exception might have a destructor.
3689 /// - Catches by reference behave according to their base types.
3690 /// - Catches of non-record types will only trigger for exceptions
3691 /// of non-record types, which never have destructors.
3692 /// - Catches of record types can trigger for arbitrary subclasses
3693 /// of the caught type, so we have to assume the actual thrown
3694 /// exception type might have a throwing destructor, even if the
3695 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003696 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003697 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3698 bool MightThrow;
3699
3700 void Emit(CodeGenFunction &CGF, Flags flags) override {
3701 if (!MightThrow) {
3702 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3703 return;
3704 }
3705
3706 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3707 }
3708 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003709}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003710
3711/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3712/// __cxa_end_catch.
3713///
3714/// \param EndMightThrow - true if __cxa_end_catch might throw
3715static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3716 llvm::Value *Exn,
3717 bool EndMightThrow) {
3718 llvm::CallInst *call =
3719 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3720
3721 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3722
3723 return call;
3724}
3725
3726/// A "special initializer" callback for initializing a catch
3727/// parameter during catch initialization.
3728static void InitCatchParam(CodeGenFunction &CGF,
3729 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003730 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003731 SourceLocation Loc) {
3732 // Load the exception from where the landing pad saved it.
3733 llvm::Value *Exn = CGF.getExceptionFromSlot();
3734
3735 CanQualType CatchType =
3736 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3737 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3738
3739 // If we're catching by reference, we can just cast the object
3740 // pointer to the appropriate pointer.
3741 if (isa<ReferenceType>(CatchType)) {
3742 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3743 bool EndCatchMightThrow = CaughtType->isRecordType();
3744
3745 // __cxa_begin_catch returns the adjusted object pointer.
3746 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3747
3748 // We have no way to tell the personality function that we're
3749 // catching by reference, so if we're catching a pointer,
3750 // __cxa_begin_catch will actually return that pointer by value.
3751 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3752 QualType PointeeType = PT->getPointeeType();
3753
3754 // When catching by reference, generally we should just ignore
3755 // this by-value pointer and use the exception object instead.
3756 if (!PointeeType->isRecordType()) {
3757
3758 // Exn points to the struct _Unwind_Exception header, which
3759 // we have to skip past in order to reach the exception data.
3760 unsigned HeaderSize =
3761 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3762 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3763
3764 // However, if we're catching a pointer-to-record type that won't
3765 // work, because the personality function might have adjusted
3766 // the pointer. There's actually no way for us to fully satisfy
3767 // the language/ABI contract here: we can't use Exn because it
3768 // might have the wrong adjustment, but we can't use the by-value
3769 // pointer because it's off by a level of abstraction.
3770 //
3771 // The current solution is to dump the adjusted pointer into an
3772 // alloca, which breaks language semantics (because changing the
3773 // pointer doesn't change the exception) but at least works.
3774 // The better solution would be to filter out non-exact matches
3775 // and rethrow them, but this is tricky because the rethrow
3776 // really needs to be catchable by other sites at this landing
3777 // pad. The best solution is to fix the personality function.
3778 } else {
3779 // Pull the pointer for the reference type off.
3780 llvm::Type *PtrTy =
3781 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3782
3783 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003784 Address ExnPtrTmp =
3785 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003786 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3787 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3788
3789 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003790 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003791 }
3792 }
3793
3794 llvm::Value *ExnCast =
3795 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3796 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3797 return;
3798 }
3799
3800 // Scalars and complexes.
3801 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3802 if (TEK != TEK_Aggregate) {
3803 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3804
3805 // If the catch type is a pointer type, __cxa_begin_catch returns
3806 // the pointer by value.
3807 if (CatchType->hasPointerRepresentation()) {
3808 llvm::Value *CastExn =
3809 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3810
3811 switch (CatchType.getQualifiers().getObjCLifetime()) {
3812 case Qualifiers::OCL_Strong:
3813 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3814 // fallthrough
3815
3816 case Qualifiers::OCL_None:
3817 case Qualifiers::OCL_ExplicitNone:
3818 case Qualifiers::OCL_Autoreleasing:
3819 CGF.Builder.CreateStore(CastExn, ParamAddr);
3820 return;
3821
3822 case Qualifiers::OCL_Weak:
3823 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3824 return;
3825 }
3826 llvm_unreachable("bad ownership qualifier!");
3827 }
3828
3829 // Otherwise, it returns a pointer into the exception object.
3830
3831 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3832 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3833
3834 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003835 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003836 switch (TEK) {
3837 case TEK_Complex:
3838 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3839 /*init*/ true);
3840 return;
3841 case TEK_Scalar: {
3842 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3843 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3844 return;
3845 }
3846 case TEK_Aggregate:
3847 llvm_unreachable("evaluation kind filtered out!");
3848 }
3849 llvm_unreachable("bad evaluation kind");
3850 }
3851
3852 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003853 auto catchRD = CatchType->getAsCXXRecordDecl();
3854 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003855
3856 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3857
3858 // Check for a copy expression. If we don't have a copy expression,
3859 // that means a trivial copy is okay.
3860 const Expr *copyExpr = CatchParam.getInit();
3861 if (!copyExpr) {
3862 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003863 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3864 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003865 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3866 return;
3867 }
3868
3869 // We have to call __cxa_get_exception_ptr to get the adjusted
3870 // pointer before copying.
3871 llvm::CallInst *rawAdjustedExn =
3872 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3873
3874 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003875 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3876 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003877
3878 // The copy expression is defined in terms of an OpaqueValueExpr.
3879 // Find it and map it to the adjusted expression.
3880 CodeGenFunction::OpaqueValueMapping
3881 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3882 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3883
3884 // Call the copy ctor in a terminate scope.
3885 CGF.EHStack.pushTerminate();
3886
3887 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003888 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003889 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003890 AggValueSlot::IsNotDestructed,
3891 AggValueSlot::DoesNotNeedGCBarriers,
3892 AggValueSlot::IsNotAliased));
3893
3894 // Leave the terminate scope.
3895 CGF.EHStack.popTerminate();
3896
3897 // Undo the opaque value mapping.
3898 opaque.pop();
3899
3900 // Finally we can call __cxa_begin_catch.
3901 CallBeginCatch(CGF, Exn, true);
3902}
3903
3904/// Begins a catch statement by initializing the catch variable and
3905/// calling __cxa_begin_catch.
3906void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3907 const CXXCatchStmt *S) {
3908 // We have to be very careful with the ordering of cleanups here:
3909 // C++ [except.throw]p4:
3910 // The destruction [of the exception temporary] occurs
3911 // immediately after the destruction of the object declared in
3912 // the exception-declaration in the handler.
3913 //
3914 // So the precise ordering is:
3915 // 1. Construct catch variable.
3916 // 2. __cxa_begin_catch
3917 // 3. Enter __cxa_end_catch cleanup
3918 // 4. Enter dtor cleanup
3919 //
3920 // We do this by using a slightly abnormal initialization process.
3921 // Delegation sequence:
3922 // - ExitCXXTryStmt opens a RunCleanupsScope
3923 // - EmitAutoVarAlloca creates the variable and debug info
3924 // - InitCatchParam initializes the variable from the exception
3925 // - CallBeginCatch calls __cxa_begin_catch
3926 // - CallBeginCatch enters the __cxa_end_catch cleanup
3927 // - EmitAutoVarCleanups enters the variable destructor cleanup
3928 // - EmitCXXTryStmt emits the code for the catch body
3929 // - EmitCXXTryStmt close the RunCleanupsScope
3930
3931 VarDecl *CatchParam = S->getExceptionDecl();
3932 if (!CatchParam) {
3933 llvm::Value *Exn = CGF.getExceptionFromSlot();
3934 CallBeginCatch(CGF, Exn, true);
3935 return;
3936 }
3937
3938 // Emit the local.
3939 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3940 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3941 CGF.EmitAutoVarCleanups(var);
3942}
3943
3944/// Get or define the following function:
3945/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3946/// This code is used only in C++.
3947static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3948 llvm::FunctionType *fnTy =
3949 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003950 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3951 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003952
3953 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3954 if (fn && fn->empty()) {
3955 fn->setDoesNotThrow();
3956 fn->setDoesNotReturn();
3957
3958 // What we really want is to massively penalize inlining without
3959 // forbidding it completely. The difference between that and
3960 // 'noinline' is negligible.
3961 fn->addFnAttr(llvm::Attribute::NoInline);
3962
3963 // Allow this function to be shared across translation units, but
3964 // we don't want it to turn into an exported symbol.
3965 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3966 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003967 if (CGM.supportsCOMDAT())
3968 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003969
3970 // Set up the function.
3971 llvm::BasicBlock *entry =
3972 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003973 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003974
3975 // Pull the exception pointer out of the parameter list.
3976 llvm::Value *exn = &*fn->arg_begin();
3977
3978 // Call __cxa_begin_catch(exn).
3979 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3980 catchCall->setDoesNotThrow();
3981 catchCall->setCallingConv(CGM.getRuntimeCC());
3982
3983 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003984 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003985 termCall->setDoesNotThrow();
3986 termCall->setDoesNotReturn();
3987 termCall->setCallingConv(CGM.getRuntimeCC());
3988
3989 // std::terminate cannot return.
3990 builder.CreateUnreachable();
3991 }
3992
3993 return fnRef;
3994}
3995
3996llvm::CallInst *
3997ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3998 llvm::Value *Exn) {
3999 // In C++, we want to call __cxa_begin_catch() before terminating.
4000 if (Exn) {
4001 assert(CGF.CGM.getLangOpts().CPlusPlus);
4002 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4003 }
4004 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4005}