blob: 6a5fd1916b9ecaeaf185a8600fff7c330699fe1c [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"
John McCall9c6cb762016-11-28 22:18:33 +000027#include "ConstantBuilder.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000028#include "TargetInfo.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
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000210 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
211 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000212
Reid Klecknere7de47e2013-07-22 13:51:44 +0000213 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000214 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000215 // Itanium does not emit any destructor variant as an inline thunk.
216 // Delegating may occur as an optimization, but all variants are either
217 // emitted with external linkage or as linkonce if they are inline and used.
218 return false;
219 }
220
Craig Topper4f12f102014-03-12 06:41:41 +0000221 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000222
Reid Kleckner89077a12013-12-17 19:46:40 +0000223 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000224 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000225
Craig Topper4f12f102014-03-12 06:41:41 +0000226 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000227
Reid Kleckner89077a12013-12-17 19:46:40 +0000228 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
229 const CXXConstructorDecl *D,
230 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000231 bool Delegating,
232 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 Padlewskia587ca52016-12-28 18:26:08 +0000369 bool hasAnyVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000370 const auto &VtableLayout =
371 CGM.getItaniumVTableContext().getVTableLayout(RD);
372
373 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewskia587ca52016-12-28 18:26:08 +0000374 // Skip empty slot.
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000375 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000376 continue;
377
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000378 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000379 if (Method->getCanonicalDecl()->isInlined())
380 return true;
381 }
382 return false;
383 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000384
385 bool isVTableHidden(const CXXRecordDecl *RD) const {
386 const auto &VtableLayout =
387 CGM.getItaniumVTableContext().getVTableLayout(RD);
388
389 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
390 if (VtableComponent.isRTTIKind()) {
391 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
392 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
393 return true;
394 } else if (VtableComponent.isUsedFunctionPointerKind()) {
395 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
396 if (Method->getVisibility() == Visibility::HiddenVisibility &&
397 !Method->isDefined())
398 return true;
399 }
400 }
401 return false;
402 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000403};
John McCall86353412010-08-21 22:46:04 +0000404
405class ARMCXXABI : public ItaniumCXXABI {
406public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000407 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
408 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
409 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000410
Craig Topper4f12f102014-03-12 06:41:41 +0000411 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000412 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
413 isa<CXXDestructorDecl>(GD.getDecl()) &&
414 GD.getDtorType() != Dtor_Deleting));
415 }
John McCall5d865c322010-08-31 07:33:07 +0000416
Craig Topper4f12f102014-03-12 06:41:41 +0000417 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
418 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000419
Craig Topper4f12f102014-03-12 06:41:41 +0000420 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000421 Address InitializeArrayCookie(CodeGenFunction &CGF,
422 Address NewPtr,
423 llvm::Value *NumElements,
424 const CXXNewExpr *expr,
425 QualType ElementType) override;
426 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000427 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000428};
Tim Northovera2ee4332014-03-29 15:09:45 +0000429
430class iOS64CXXABI : public ARMCXXABI {
431public:
John McCalld23b27e2016-09-16 02:40:45 +0000432 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
433 Use32BitVTableOffsetABI = true;
434 }
Tim Northover65f582f2014-03-30 17:32:48 +0000435
436 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000437 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000438};
Dan Gohmanc2853072015-09-03 22:51:53 +0000439
440class WebAssemblyCXXABI final : public ItaniumCXXABI {
441public:
442 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
443 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
444 /*UseARMGuardVarABI=*/true) {}
445
446private:
447 bool HasThisReturn(GlobalDecl GD) const override {
448 return isa<CXXConstructorDecl>(GD.getDecl()) ||
449 (isa<CXXDestructorDecl>(GD.getDecl()) &&
450 GD.getDtorType() != Dtor_Deleting);
451 }
Derek Schuff8179be42016-05-10 17:44:55 +0000452 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000453};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000454}
Charles Davis4e786dd2010-05-25 19:52:27 +0000455
Charles Davis53c59df2010-08-16 03:33:14 +0000456CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000457 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000458 // For IR-generation purposes, there's no significant difference
459 // between the ARM and iOS ABIs.
460 case TargetCXXABI::GenericARM:
461 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000462 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000463 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000464
Tim Northovera2ee4332014-03-29 15:09:45 +0000465 case TargetCXXABI::iOS64:
466 return new iOS64CXXABI(CGM);
467
Tim Northover9bb857a2013-01-31 12:13:10 +0000468 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
469 // include the other 32-bit ARM oddities: constructor/destructor return values
470 // and array cookies.
471 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000472 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
473 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000474
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000475 case TargetCXXABI::GenericMIPS:
476 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
477
Dan Gohmanc2853072015-09-03 22:51:53 +0000478 case TargetCXXABI::WebAssembly:
479 return new WebAssemblyCXXABI(CGM);
480
John McCall57625922013-01-25 23:36:14 +0000481 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000482 if (CGM.getContext().getTargetInfo().getTriple().getArch()
483 == llvm::Triple::le32) {
484 // For PNaCl, use ARM-style method pointers so that PNaCl code
485 // does not assume anything about the alignment of function
486 // pointers.
487 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
488 /* UseARMGuardVarABI = */ false);
489 }
John McCall57625922013-01-25 23:36:14 +0000490 return new ItaniumCXXABI(CGM);
491
492 case TargetCXXABI::Microsoft:
493 llvm_unreachable("Microsoft ABI is not Itanium-based");
494 }
495 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000496}
497
Chris Lattnera5f58b02011-07-09 17:41:47 +0000498llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000499ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
500 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000501 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000502 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000503}
504
John McCalld9c6c0b2010-08-22 00:59:17 +0000505/// In the Itanium and ARM ABIs, method pointers have the form:
506/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
507///
508/// In the Itanium ABI:
509/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
510/// - the this-adjustment is (memptr.adj)
511/// - the virtual offset is (memptr.ptr - 1)
512///
513/// In the ARM ABI:
514/// - method pointers are virtual if (memptr.adj & 1) is nonzero
515/// - the this-adjustment is (memptr.adj >> 1)
516/// - the virtual offset is (memptr.ptr)
517/// ARM uses 'adj' for the virtual flag because Thumb functions
518/// may be only single-byte aligned.
519///
520/// If the member is virtual, the adjusted 'this' pointer points
521/// to a vtable pointer from which the virtual offset is applied.
522///
523/// If the member is non-virtual, memptr.ptr is the address of
524/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000525CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000526 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
527 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000528 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000529 CGBuilderTy &Builder = CGF.Builder;
530
531 const FunctionProtoType *FPT =
532 MPT->getPointeeType()->getAs<FunctionProtoType>();
533 const CXXRecordDecl *RD =
534 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
535
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000536 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
537 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000538
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000539 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000540
John McCalld9c6c0b2010-08-22 00:59:17 +0000541 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
542 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
543 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
544
John McCalla1dee5302010-08-22 10:59:02 +0000545 // Extract memptr.adj, which is in the second field.
546 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000547
548 // Compute the true adjustment.
549 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000550 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000551 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000552
553 // Apply the adjustment and cast back to the original struct type
554 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000555 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000556 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
557 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
558 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000559 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000560
561 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000562 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000563
564 // If the LSB in the function pointer is 1, the function pointer points to
565 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000566 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000567 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000568 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
569 else
570 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
571 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000572 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
573
574 // In the virtual path, the adjustment left 'This' pointing to the
575 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000576 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000577 CGF.EmitBlock(FnVirtual);
578
579 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000580 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000581 CharUnits VTablePtrAlign =
582 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
583 CGF.getPointerAlign());
584 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000585 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000586
587 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000588 // On ARM64, to reserve extra space in virtual member function pointers,
589 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000590 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000591 if (!UseARMMethodPtrABI)
592 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000593 if (Use32BitVTableOffsetABI) {
594 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
595 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
596 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000597 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000598
599 // Load the virtual function to call.
600 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000601 llvm::Value *VirtualFn =
602 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
603 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000604 CGF.EmitBranch(FnEnd);
605
606 // In the non-virtual path, the function pointer is actually a
607 // function pointer.
608 CGF.EmitBlock(FnNonVirtual);
609 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000610 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000611
612 // We're done.
613 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000614 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
615 CalleePtr->addIncoming(VirtualFn, FnVirtual);
616 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
617
618 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000619 return Callee;
620}
John McCalla8bbb822010-08-22 03:04:22 +0000621
John McCallc134eb52010-08-31 21:07:20 +0000622/// Compute an l-value by applying the given pointer-to-member to a
623/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000624llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000625 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000626 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000627 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000628
629 CGBuilderTy &Builder = CGF.Builder;
630
John McCallc134eb52010-08-31 21:07:20 +0000631 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000632 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000633
634 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000635 llvm::Value *Addr =
636 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000637
638 // Cast the address to the appropriate pointer type, adopting the
639 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000640 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
641 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000642 return Builder.CreateBitCast(Addr, PType);
643}
644
John McCallc62bb392012-02-15 01:22:51 +0000645/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
646/// conversion.
647///
648/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000649///
650/// Obligatory offset/adjustment diagram:
651/// <-- offset --> <-- adjustment -->
652/// |--------------------------|----------------------|--------------------|
653/// ^Derived address point ^Base address point ^Member address point
654///
655/// So when converting a base member pointer to a derived member pointer,
656/// we add the offset to the adjustment because the address point has
657/// decreased; and conversely, when converting a derived MP to a base MP
658/// we subtract the offset from the adjustment because the address point
659/// has increased.
660///
661/// The standard forbids (at compile time) conversion to and from
662/// virtual bases, which is why we don't have to consider them here.
663///
664/// The standard forbids (at run time) casting a derived MP to a base
665/// MP when the derived MP does not point to a member of the base.
666/// This is why -1 is a reasonable choice for null data member
667/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000668llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000669ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
670 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000671 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000672 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000673 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
674 E->getCastKind() == CK_ReinterpretMemberPointer);
675
676 // Under Itanium, reinterprets don't require any additional processing.
677 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
678
679 // Use constant emission if we can.
680 if (isa<llvm::Constant>(src))
681 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
682
683 llvm::Constant *adj = getMemberPointerAdjustment(E);
684 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000685
686 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000687 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000688
John McCallc62bb392012-02-15 01:22:51 +0000689 const MemberPointerType *destTy =
690 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000691
John McCall7a9aac22010-08-23 01:21:21 +0000692 // For member data pointers, this is just a matter of adding the
693 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000694 if (destTy->isMemberDataPointer()) {
695 llvm::Value *dst;
696 if (isDerivedToBase)
697 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000698 else
John McCallc62bb392012-02-15 01:22:51 +0000699 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000700
701 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000702 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
703 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
704 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000705 }
706
John McCalla1dee5302010-08-22 10:59:02 +0000707 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000708 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000709 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
710 offset <<= 1;
711 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000712 }
713
John McCallc62bb392012-02-15 01:22:51 +0000714 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
715 llvm::Value *dstAdj;
716 if (isDerivedToBase)
717 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000718 else
John McCallc62bb392012-02-15 01:22:51 +0000719 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000720
John McCallc62bb392012-02-15 01:22:51 +0000721 return Builder.CreateInsertValue(src, dstAdj, 1);
722}
723
724llvm::Constant *
725ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
726 llvm::Constant *src) {
727 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
728 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
729 E->getCastKind() == CK_ReinterpretMemberPointer);
730
731 // Under Itanium, reinterprets don't require any additional processing.
732 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
733
734 // If the adjustment is trivial, we don't need to do anything.
735 llvm::Constant *adj = getMemberPointerAdjustment(E);
736 if (!adj) return src;
737
738 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
739
740 const MemberPointerType *destTy =
741 E->getType()->castAs<MemberPointerType>();
742
743 // For member data pointers, this is just a matter of adding the
744 // offset if the source is non-null.
745 if (destTy->isMemberDataPointer()) {
746 // null maps to null.
747 if (src->isAllOnesValue()) return src;
748
749 if (isDerivedToBase)
750 return llvm::ConstantExpr::getNSWSub(src, adj);
751 else
752 return llvm::ConstantExpr::getNSWAdd(src, adj);
753 }
754
755 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000756 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000757 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
758 offset <<= 1;
759 adj = llvm::ConstantInt::get(adj->getType(), offset);
760 }
761
762 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
763 llvm::Constant *dstAdj;
764 if (isDerivedToBase)
765 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
766 else
767 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
768
769 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000770}
John McCall84fa5102010-08-22 04:16:24 +0000771
772llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000773ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000774 // Itanium C++ ABI 2.3:
775 // A NULL pointer is represented as -1.
776 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000777 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000778
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000779 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000780 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000781 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000782}
783
John McCallf3a88602011-02-03 08:15:49 +0000784llvm::Constant *
785ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
786 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000787 // Itanium C++ ABI 2.3:
788 // A pointer to data member is an offset from the base address of
789 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000790 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000791}
792
David Majnemere2be95b2015-06-23 07:31:01 +0000793llvm::Constant *
794ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000795 return BuildMemberPointer(MD, CharUnits::Zero());
796}
797
798llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
799 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000800 assert(MD->isInstance() && "Member function must not be static!");
801 MD = MD->getCanonicalDecl();
802
803 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000804
805 // Get the function pointer (or index if this is a virtual function).
806 llvm::Constant *MemPtr[2];
807 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000808 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000809
Ken Dyckdf016282011-04-09 01:30:02 +0000810 const ASTContext &Context = getContext();
811 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000812 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000813 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000814
Mark Seabornedf0d382013-07-24 16:25:13 +0000815 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000816 // ARM C++ ABI 3.2.1:
817 // This ABI specifies that adj contains twice the this
818 // adjustment, plus 1 if the member function is virtual. The
819 // least significant bit of adj then makes exactly the same
820 // discrimination as the least significant bit of ptr does for
821 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000822 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
823 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000824 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000825 } else {
826 // Itanium C++ ABI 2.3:
827 // For a virtual function, [the pointer field] is 1 plus the
828 // virtual table offset (in bytes) of the function,
829 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000830 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
831 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000832 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000833 }
834 } else {
John McCall2979fe02011-04-12 00:42:48 +0000835 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000836 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000837 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000838 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000839 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000840 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000841 } else {
John McCall2979fe02011-04-12 00:42:48 +0000842 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
843 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000844 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000845 }
John McCall2979fe02011-04-12 00:42:48 +0000846 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000847
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000848 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000849 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
850 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000851 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000852 }
John McCall1c456c82010-08-22 06:43:33 +0000853
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000854 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000855}
856
Richard Smithdafff942012-01-14 04:30:29 +0000857llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
858 QualType MPType) {
859 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
860 const ValueDecl *MPD = MP.getMemberPointerDecl();
861 if (!MPD)
862 return EmitNullMemberPointer(MPT);
863
Reid Kleckner452abac2013-05-09 21:01:17 +0000864 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000865
866 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
867 return BuildMemberPointer(MD, ThisAdjustment);
868
869 CharUnits FieldOffset =
870 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
871 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
872}
873
John McCall131d97d2010-08-22 08:30:07 +0000874/// The comparison algorithm is pretty easy: the member pointers are
875/// the same if they're either bitwise identical *or* both null.
876///
877/// ARM is different here only because null-ness is more complicated.
878llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000879ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
880 llvm::Value *L,
881 llvm::Value *R,
882 const MemberPointerType *MPT,
883 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000884 CGBuilderTy &Builder = CGF.Builder;
885
John McCall131d97d2010-08-22 08:30:07 +0000886 llvm::ICmpInst::Predicate Eq;
887 llvm::Instruction::BinaryOps And, Or;
888 if (Inequality) {
889 Eq = llvm::ICmpInst::ICMP_NE;
890 And = llvm::Instruction::Or;
891 Or = llvm::Instruction::And;
892 } else {
893 Eq = llvm::ICmpInst::ICMP_EQ;
894 And = llvm::Instruction::And;
895 Or = llvm::Instruction::Or;
896 }
897
John McCall7a9aac22010-08-23 01:21:21 +0000898 // Member data pointers are easy because there's a unique null
899 // value, so it just comes down to bitwise equality.
900 if (MPT->isMemberDataPointer())
901 return Builder.CreateICmp(Eq, L, R);
902
903 // For member function pointers, the tautologies are more complex.
904 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000905 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000906 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000907 // (L == R) <==> (L.ptr == R.ptr &&
908 // (L.adj == R.adj ||
909 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000910 // The inequality tautologies have exactly the same structure, except
911 // applying De Morgan's laws.
912
913 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
914 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
915
John McCall131d97d2010-08-22 08:30:07 +0000916 // This condition tests whether L.ptr == R.ptr. This must always be
917 // true for equality to hold.
918 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
919
920 // This condition, together with the assumption that L.ptr == R.ptr,
921 // tests whether the pointers are both null. ARM imposes an extra
922 // condition.
923 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
924 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
925
926 // This condition tests whether L.adj == R.adj. If this isn't
927 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000928 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
929 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000930 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
931
932 // Null member function pointers on ARM clear the low bit of Adj,
933 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000934 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000935 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
936
937 // Compute (l.adj | r.adj) & 1 and test it against zero.
938 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
939 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
940 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
941 "cmp.or.adj");
942 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
943 }
944
945 // Tie together all our conditions.
946 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
947 Result = Builder.CreateBinOp(And, PtrEq, Result,
948 Inequality ? "memptr.ne" : "memptr.eq");
949 return Result;
950}
951
952llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000953ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
954 llvm::Value *MemPtr,
955 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000956 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000957
958 /// For member data pointers, this is just a check against -1.
959 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000960 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000961 llvm::Value *NegativeOne =
962 llvm::Constant::getAllOnesValue(MemPtr->getType());
963 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
964 }
John McCall131d97d2010-08-22 08:30:07 +0000965
Daniel Dunbar914bc412011-04-19 23:10:47 +0000966 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000967 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000968
969 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
970 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
971
Daniel Dunbar914bc412011-04-19 23:10:47 +0000972 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
973 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000974 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000975 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000976 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000977 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000978 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
979 "memptr.isvirtual");
980 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000981 }
982
983 return Result;
984}
John McCall1c456c82010-08-22 06:43:33 +0000985
Reid Kleckner40ca9132014-05-13 22:05:45 +0000986bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
987 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
988 if (!RD)
989 return false;
990
Reid Klecknerd355ca72014-05-15 01:26:32 +0000991 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
992 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
993 // special members.
994 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000995 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
996 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000997 return true;
998 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000999 return false;
1000}
1001
John McCall614dbdc2010-08-22 21:01:12 +00001002/// The Itanium ABI requires non-zero initialization only for data
1003/// member pointers, for which '0' is a valid offset.
1004bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001005 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001006}
John McCall5d865c322010-08-31 07:33:07 +00001007
John McCall82fb8922012-09-25 10:10:39 +00001008/// The Itanium ABI always places an offset to the complete object
1009/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001010void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1011 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001012 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001013 QualType ElementType,
1014 const CXXDestructorDecl *Dtor) {
1015 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001016 if (UseGlobalDelete) {
1017 // Derive the complete-object pointer, which is what we need
1018 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001019
David Majnemer0c0b6d92014-10-31 20:09:12 +00001020 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001021 auto *ClassDecl =
1022 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1023 llvm::Value *VTable =
1024 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001025
David Majnemer0c0b6d92014-10-31 20:09:12 +00001026 // Track back to entry -2 and pull out the offset there.
1027 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1028 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001029 llvm::Value *Offset =
1030 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001031
1032 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001033 llvm::Value *CompletePtr =
1034 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001035 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1036
1037 // If we're supposed to call the global delete, make sure we do so
1038 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001039 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1040 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001041 }
1042
1043 // FIXME: Provide a source location here even though there's no
1044 // CXXMemberCallExpr for dtor call.
1045 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1046 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1047
1048 if (UseGlobalDelete)
1049 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001050}
1051
David Majnemer442d0a22014-11-25 07:20:20 +00001052void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1053 // void __cxa_rethrow();
1054
1055 llvm::FunctionType *FTy =
1056 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1057
1058 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1059
1060 if (isNoReturn)
1061 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1062 else
1063 CGF.EmitRuntimeCallOrInvoke(Fn);
1064}
1065
David Majnemer7c237072015-03-05 00:46:22 +00001066static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1067 // void *__cxa_allocate_exception(size_t thrown_size);
1068
1069 llvm::FunctionType *FTy =
1070 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1071
1072 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1073}
1074
1075static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1076 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1077 // void (*dest) (void *));
1078
1079 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1080 llvm::FunctionType *FTy =
1081 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1082
1083 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1084}
1085
1086void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1087 QualType ThrowType = E->getSubExpr()->getType();
1088 // Now allocate the exception object.
1089 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1090 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1091
1092 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1093 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1094 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1095
John McCall7f416cc2015-09-08 08:05:57 +00001096 CharUnits ExnAlign = getAlignmentOfExnObject();
1097 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001098
1099 // Now throw the exception.
1100 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1101 /*ForEH=*/true);
1102
1103 // The address of the destructor. If the exception type has a
1104 // trivial destructor (or isn't a record), we just pass null.
1105 llvm::Constant *Dtor = nullptr;
1106 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1107 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1108 if (!Record->hasTrivialDestructor()) {
1109 CXXDestructorDecl *DtorD = Record->getDestructor();
1110 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1111 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1112 }
1113 }
1114 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1115
1116 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1117 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1118}
1119
David Majnemer1162d252014-06-22 19:05:33 +00001120static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1121 // void *__dynamic_cast(const void *sub,
1122 // const abi::__class_type_info *src,
1123 // const abi::__class_type_info *dst,
1124 // std::ptrdiff_t src2dst_offset);
1125
1126 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1127 llvm::Type *PtrDiffTy =
1128 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1129
1130 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1131
1132 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1133
1134 // Mark the function as nounwind readonly.
1135 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1136 llvm::Attribute::ReadOnly };
1137 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1138 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1139
1140 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1141}
1142
1143static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1144 // void __cxa_bad_cast();
1145 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1146 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1147}
1148
1149/// \brief Compute the src2dst_offset hint as described in the
1150/// Itanium C++ ABI [2.9.7]
1151static CharUnits computeOffsetHint(ASTContext &Context,
1152 const CXXRecordDecl *Src,
1153 const CXXRecordDecl *Dst) {
1154 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1155 /*DetectVirtual=*/false);
1156
1157 // If Dst is not derived from Src we can skip the whole computation below and
1158 // return that Src is not a public base of Dst. Record all inheritance paths.
1159 if (!Dst->isDerivedFrom(Src, Paths))
1160 return CharUnits::fromQuantity(-2ULL);
1161
1162 unsigned NumPublicPaths = 0;
1163 CharUnits Offset;
1164
1165 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001166 for (const CXXBasePath &Path : Paths) {
1167 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001168 continue;
1169
1170 ++NumPublicPaths;
1171
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001172 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001173 // If the path contains a virtual base class we can't give any hint.
1174 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001175 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001176 return CharUnits::fromQuantity(-1ULL);
1177
1178 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1179 continue;
1180
1181 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001182 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1183 Offset += L.getBaseClassOffset(
1184 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001185 }
1186 }
1187
1188 // -2: Src is not a public base of Dst.
1189 if (NumPublicPaths == 0)
1190 return CharUnits::fromQuantity(-2ULL);
1191
1192 // -3: Src is a multiple public base type but never a virtual base type.
1193 if (NumPublicPaths > 1)
1194 return CharUnits::fromQuantity(-3ULL);
1195
1196 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1197 // Return the offset of Src from the origin of Dst.
1198 return Offset;
1199}
1200
1201static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1202 // void __cxa_bad_typeid();
1203 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1204
1205 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1206}
1207
1208bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1209 QualType SrcRecordTy) {
1210 return IsDeref;
1211}
1212
1213void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1214 llvm::Value *Fn = getBadTypeidFn(CGF);
1215 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1216 CGF.Builder.CreateUnreachable();
1217}
1218
1219llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1220 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001221 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001222 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001223 auto *ClassDecl =
1224 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001225 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001226 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001227
1228 // Load the type info.
1229 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001230 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001231}
1232
1233bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1234 QualType SrcRecordTy) {
1235 return SrcIsPtr;
1236}
1237
1238llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001239 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001240 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1241 llvm::Type *PtrDiffLTy =
1242 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1243 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1244
1245 llvm::Value *SrcRTTI =
1246 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1247 llvm::Value *DestRTTI =
1248 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1249
1250 // Compute the offset hint.
1251 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1252 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1253 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1254 PtrDiffLTy,
1255 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1256
1257 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001258 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001259 Value = CGF.EmitCastToVoidPtr(Value);
1260
1261 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1262 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1263 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1264
1265 /// C++ [expr.dynamic.cast]p9:
1266 /// A failed cast to reference type throws std::bad_cast
1267 if (DestTy->isReferenceType()) {
1268 llvm::BasicBlock *BadCastBlock =
1269 CGF.createBasicBlock("dynamic_cast.bad_cast");
1270
1271 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1272 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1273
1274 CGF.EmitBlock(BadCastBlock);
1275 EmitBadCastCall(CGF);
1276 }
1277
1278 return Value;
1279}
1280
1281llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001282 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001283 QualType SrcRecordTy,
1284 QualType DestTy) {
1285 llvm::Type *PtrDiffLTy =
1286 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1287 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1288
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001289 auto *ClassDecl =
1290 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001291 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001292 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1293 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001294
1295 // Get the offset-to-top from the vtable.
1296 llvm::Value *OffsetToTop =
1297 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001298 OffsetToTop =
1299 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1300 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001301
1302 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001303 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001304 Value = CGF.EmitCastToVoidPtr(Value);
1305 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1306
1307 return CGF.Builder.CreateBitCast(Value, DestLTy);
1308}
1309
1310bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1311 llvm::Value *Fn = getBadCastFn(CGF);
1312 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1313 CGF.Builder.CreateUnreachable();
1314 return true;
1315}
1316
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001317llvm::Value *
1318ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001319 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001320 const CXXRecordDecl *ClassDecl,
1321 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001322 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001323 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001324 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1325 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001326
1327 llvm::Value *VBaseOffsetPtr =
1328 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1329 "vbase.offset.ptr");
1330 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1331 CGM.PtrDiffTy->getPointerTo());
1332
1333 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001334 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1335 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001336
1337 return VBaseOffset;
1338}
1339
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001340void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1341 // Just make sure we're in sync with TargetCXXABI.
1342 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1343
Rafael Espindolac3cde362013-12-09 14:51:17 +00001344 // The constructor used for constructing this as a base class;
1345 // ignores virtual bases.
1346 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1347
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001348 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001349 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001350 if (!D->getParent()->isAbstract()) {
1351 // We don't need to emit the complete ctor if the class is abstract.
1352 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1353 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001354}
1355
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001356void
1357ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1358 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001359 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001360
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001361 // All parameters are already in place except VTT, which goes after 'this'.
1362 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001363
1364 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001365 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1366 ArgTys.insert(ArgTys.begin() + 1,
1367 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001368}
1369
Reid Klecknere7de47e2013-07-22 13:51:44 +00001370void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001371 // The destructor used for destructing this as a base class; ignores
1372 // virtual bases.
1373 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001374
1375 // The destructor used for destructing this as a most-derived class;
1376 // call the base destructor and then destructs any virtual bases.
1377 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1378
Rafael Espindolac3cde362013-12-09 14:51:17 +00001379 // The destructor in a virtual table is always a 'deleting'
1380 // destructor, which calls the complete destructor and then uses the
1381 // appropriate operator delete.
1382 if (D->isVirtual())
1383 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001384}
1385
Reid Kleckner89077a12013-12-17 19:46:40 +00001386void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1387 QualType &ResTy,
1388 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001389 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001390 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001391
1392 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001393 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001394 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001395
1396 // FIXME: avoid the fake decl
1397 QualType T = Context.getPointerType(Context.VoidPtrTy);
1398 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001399 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001400 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001401 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001402 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001403 }
1404}
1405
John McCall5d865c322010-08-31 07:33:07 +00001406void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001407 // Naked functions have no prolog.
1408 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1409 return;
1410
John McCall5d865c322010-08-31 07:33:07 +00001411 /// Initialize the 'this' slot.
1412 EmitThisParam(CGF);
1413
1414 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001415 if (getStructorImplicitParamDecl(CGF)) {
1416 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1417 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001418 }
John McCall5d865c322010-08-31 07:33:07 +00001419
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001420 /// If this is a function that the ABI specifies returns 'this', initialize
1421 /// the return slot to 'this' at the start of the function.
1422 ///
1423 /// Unlike the setting of return types, this is done within the ABI
1424 /// implementation instead of by clients of CGCXXABI because:
1425 /// 1) getThisValue is currently protected
1426 /// 2) in theory, an ABI could implement 'this' returns some other way;
1427 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001428 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001429 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001430}
1431
Reid Kleckner89077a12013-12-17 19:46:40 +00001432unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1433 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1434 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1435 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1436 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001437
Reid Kleckner89077a12013-12-17 19:46:40 +00001438 // Insert the implicit 'vtt' argument as the second argument.
1439 llvm::Value *VTT =
1440 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1441 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1442 Args.insert(Args.begin() + 1,
1443 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1444 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001445}
1446
1447void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1448 const CXXDestructorDecl *DD,
1449 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001450 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001451 GlobalDecl GD(DD, Type);
1452 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1453 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1454
John McCallb92ab1a2016-10-26 23:46:34 +00001455 CGCallee Callee;
1456 if (getContext().getLangOpts().AppleKext &&
1457 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001458 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001459 else
1460 Callee =
1461 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1462 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001463
John McCall7f416cc2015-09-08 08:05:57 +00001464 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001465 This.getPointer(), VTT, VTTTy,
1466 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001467}
1468
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001469void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1470 const CXXRecordDecl *RD) {
1471 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1472 if (VTable->hasInitializer())
1473 return;
1474
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001475 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001476 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1477 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001478 llvm::Constant *RTTI =
1479 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001480
1481 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001482 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001483 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001484 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1485 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001486
1487 // Set the correct linkage.
1488 VTable->setLinkage(Linkage);
1489
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001490 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1491 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001492
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001493 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001494 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001495
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001496 // Use pointer alignment for the vtable. Otherwise we would align them based
1497 // on the size of the initializer which doesn't make sense as only single
1498 // values are read.
1499 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1500 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1501
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001502 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1503 // we will emit the typeinfo for the fundamental types. This is the
1504 // same behaviour as GCC.
1505 const DeclContext *DC = RD->getDeclContext();
1506 if (RD->getIdentifier() &&
1507 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1508 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1509 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1510 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001511 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001512
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001513 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001514 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001515}
1516
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001517bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1518 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1519 if (Vptr.NearestVBase == nullptr)
1520 return false;
1521 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001522}
1523
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001524llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1525 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1526 const CXXRecordDecl *NearestVBase) {
1527
1528 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1529 NeedsVTTParameter(CGF.CurGD)) {
1530 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1531 NearestVBase);
1532 }
1533 return getVTableAddressPoint(Base, VTableClass);
1534}
1535
1536llvm::Constant *
1537ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1538 const CXXRecordDecl *VTableClass) {
1539 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001540
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001541 // Find the appropriate vtable within the vtable group, and the address point
1542 // within that vtable.
1543 VTableLayout::AddressPointLocation AddressPoint =
1544 CGM.getItaniumVTableContext()
1545 .getVTableLayout(VTableClass)
1546 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001547 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001548 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001549 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1550 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001551 };
1552
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001553 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1554 Indices, /*InBounds=*/true,
1555 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001556}
1557
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001558llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1559 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1560 const CXXRecordDecl *NearestVBase) {
1561 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1562 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1563
1564 // Get the secondary vpointer index.
1565 uint64_t VirtualPointerIndex =
1566 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1567
1568 /// Load the VTT.
1569 llvm::Value *VTT = CGF.LoadCXXVTT();
1570 if (VirtualPointerIndex)
1571 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1572
1573 // And load the address point from the VTT.
1574 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1575}
1576
1577llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1578 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1579 return getVTableAddressPoint(Base, VTableClass);
1580}
1581
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001582llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1583 CharUnits VPtrOffset) {
1584 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1585
1586 llvm::GlobalVariable *&VTable = VTables[RD];
1587 if (VTable)
1588 return VTable;
1589
Eric Christopherd160c502016-01-29 01:35:53 +00001590 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001591 CGM.addDeferredVTable(RD);
1592
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001593 SmallString<256> Name;
1594 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001595 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001596
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001597 const VTableLayout &VTLayout =
1598 CGM.getItaniumVTableContext().getVTableLayout(RD);
1599 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001600
1601 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001602 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001603 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001604
1605 if (RD->hasAttr<DLLImportAttr>())
1606 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1607 else if (RD->hasAttr<DLLExportAttr>())
1608 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1609
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001610 return VTable;
1611}
1612
John McCallb92ab1a2016-10-26 23:46:34 +00001613CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1614 GlobalDecl GD,
1615 Address This,
1616 llvm::Type *Ty,
1617 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001618 GD = GD.getCanonicalDecl();
1619 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001620 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1621 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001622
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001623 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001624 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001625 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001626 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001627 MethodDecl->getParent(), VTable,
1628 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1629 } else {
1630 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1631
1632 llvm::Value *VFuncPtr =
1633 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001634 auto *VFuncLoad =
1635 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1636
1637 // Add !invariant.load md to virtual function load to indicate that
1638 // function didn't change inside vtable.
1639 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1640 // help in devirtualization because it will only matter if we will have 2
1641 // the same virtual function loads from the same vtable load, which won't
1642 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1643 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1644 CGM.getCodeGenOpts().StrictVTablePointers)
1645 VFuncLoad->setMetadata(
1646 llvm::LLVMContext::MD_invariant_load,
1647 llvm::MDNode::get(CGM.getLLVMContext(),
1648 llvm::ArrayRef<llvm::Metadata *>()));
1649 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001650 }
John McCallb92ab1a2016-10-26 23:46:34 +00001651
1652 CGCallee Callee(MethodDecl, VFunc);
1653 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001654}
1655
David Majnemer0c0b6d92014-10-31 20:09:12 +00001656llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1657 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001658 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001659 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001660 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1661
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001662 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1663 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001664 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001665 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001666 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1667 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001668
John McCall7f416cc2015-09-08 08:05:57 +00001669 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1670 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001671 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001672 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001673}
1674
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001675void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001676 CodeGenVTables &VTables = CGM.getVTables();
1677 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001678 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001679}
1680
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001681bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001682 // We don't emit available_externally vtables if we are in -fapple-kext mode
1683 // because kext mode does not permit devirtualization.
1684 if (CGM.getLangOpts().AppleKext)
1685 return false;
1686
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001687 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001688 // then we are safe to emit available_externally copy of vtable.
1689 // FIXME we can still emit a copy of the vtable if we
1690 // can emit definition of the inline functions.
Piotr Padlewskia587ca52016-12-28 18:26:08 +00001691 return !hasAnyVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001692}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001693static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001694 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001695 int64_t NonVirtualAdjustment,
1696 int64_t VirtualAdjustment,
1697 bool IsReturnAdjustment) {
1698 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001699 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001700
John McCall7f416cc2015-09-08 08:05:57 +00001701 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001702
John McCall7f416cc2015-09-08 08:05:57 +00001703 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001704 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001705 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1706 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001707 }
1708
John McCall7f416cc2015-09-08 08:05:57 +00001709 // Perform the virtual adjustment if we have one.
1710 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001711 if (VirtualAdjustment) {
1712 llvm::Type *PtrDiffTy =
1713 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1714
John McCall7f416cc2015-09-08 08:05:57 +00001715 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001716 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1717
1718 llvm::Value *OffsetPtr =
1719 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1720
1721 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1722
1723 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001724 llvm::Value *Offset =
1725 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001726
1727 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001728 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1729 } else {
1730 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001731 }
1732
John McCall7f416cc2015-09-08 08:05:57 +00001733 // In a derived-to-base conversion, the non-virtual adjustment is
1734 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001735 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001736 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1737 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001738 }
1739
1740 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001741 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001742}
1743
1744llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001745 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001746 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001747 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1748 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001749 /*IsReturnAdjustment=*/false);
1750}
1751
1752llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001753ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001754 const ReturnAdjustment &RA) {
1755 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1756 RA.Virtual.Itanium.VBaseOffsetOffset,
1757 /*IsReturnAdjustment=*/true);
1758}
1759
John McCall5d865c322010-08-31 07:33:07 +00001760void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1761 RValue RV, QualType ResultType) {
1762 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1763 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1764
1765 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001766 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001767 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1768 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1769}
John McCall8ed55a52010-09-02 09:58:18 +00001770
1771/************************** Array allocation cookies **************************/
1772
John McCallb91cd662012-05-01 05:23:51 +00001773CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1774 // The array cookie is a size_t; pad that up to the element alignment.
1775 // The cookie is actually right-justified in that space.
1776 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1777 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001778}
1779
John McCall7f416cc2015-09-08 08:05:57 +00001780Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1781 Address NewPtr,
1782 llvm::Value *NumElements,
1783 const CXXNewExpr *expr,
1784 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001785 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001786
John McCall7f416cc2015-09-08 08:05:57 +00001787 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001788
John McCall9bca9232010-09-02 10:25:57 +00001789 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001790 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001791
1792 // The size of the cookie.
1793 CharUnits CookieSize =
1794 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001795 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001796
1797 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001798 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001799 CharUnits CookieOffset = CookieSize - SizeSize;
1800 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001801 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001802
1803 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001804 Address NumElementsPtr =
1805 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001806 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001807
1808 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001809 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001810 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001811 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001812 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1813 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001814 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001815 llvm::Constant *F =
1816 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001817 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001818 }
John McCall8ed55a52010-09-02 09:58:18 +00001819
1820 // Finally, compute a pointer to the actual data buffer by skipping
1821 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001822 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001823}
1824
John McCallb91cd662012-05-01 05:23:51 +00001825llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001826 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001827 CharUnits cookieSize) {
1828 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001829 Address numElementsPtr = allocPtr;
1830 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001831 if (!numElementsOffset.isZero())
1832 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001833 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001834
John McCall7f416cc2015-09-08 08:05:57 +00001835 unsigned AS = allocPtr.getAddressSpace();
1836 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001837 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001838 return CGF.Builder.CreateLoad(numElementsPtr);
1839 // In asan mode emit a function call instead of a regular load and let the
1840 // run-time deal with it: if the shadow is properly poisoned return the
1841 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1842 // We can't simply ignore this load using nosanitize metadata because
1843 // the metadata may be lost.
1844 llvm::FunctionType *FTy =
1845 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1846 llvm::Constant *F =
1847 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001848 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001849}
1850
John McCallb91cd662012-05-01 05:23:51 +00001851CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001852 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001853 // struct array_cookie {
1854 // std::size_t element_size; // element_size != 0
1855 // std::size_t element_count;
1856 // };
John McCallc19c7062013-01-25 23:36:19 +00001857 // But the base ABI doesn't give anything an alignment greater than
1858 // 8, so we can dismiss this as typical ABI-author blindness to
1859 // actual language complexity and round up to the element alignment.
1860 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1861 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001862}
1863
John McCall7f416cc2015-09-08 08:05:57 +00001864Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1865 Address newPtr,
1866 llvm::Value *numElements,
1867 const CXXNewExpr *expr,
1868 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001869 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001870
John McCall8ed55a52010-09-02 09:58:18 +00001871 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001872 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001873
1874 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001875 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001876 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1877 getContext().getTypeSizeInChars(elementType).getQuantity());
1878 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001879
1880 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001881 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001882 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001883
1884 // Finally, compute a pointer to the actual data buffer by skipping
1885 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001886 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001887 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001888}
1889
John McCallb91cd662012-05-01 05:23:51 +00001890llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001891 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001892 CharUnits cookieSize) {
1893 // The number of elements is at offset sizeof(size_t) relative to
1894 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001895 Address numElementsPtr
1896 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001897
John McCall7f416cc2015-09-08 08:05:57 +00001898 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001899 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001900}
1901
John McCall68ff0372010-09-08 01:44:27 +00001902/*********************** Static local initialization **************************/
1903
1904static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001905 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001906 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001907 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001908 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001909 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001910 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001911 llvm::AttributeSet::get(CGM.getLLVMContext(),
1912 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001913 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001914}
1915
1916static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001917 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001918 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001919 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001920 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001921 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001922 llvm::AttributeSet::get(CGM.getLLVMContext(),
1923 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001924 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001925}
1926
1927static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001928 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001929 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001930 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001931 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001932 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001933 llvm::AttributeSet::get(CGM.getLLVMContext(),
1934 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001935 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001936}
1937
1938namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001939 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001940 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001941 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001942
Craig Topper4f12f102014-03-12 06:41:41 +00001943 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001944 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1945 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001946 }
1947 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001948}
John McCall68ff0372010-09-08 01:44:27 +00001949
1950/// The ARM code here follows the Itanium code closely enough that we
1951/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001952void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1953 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001954 llvm::GlobalVariable *var,
1955 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001956 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001957
Richard Smith62f19e72016-06-25 00:15:56 +00001958 // Inline variables that weren't instantiated from variable templates have
1959 // partially-ordered initialization within their translation unit.
1960 bool NonTemplateInline =
1961 D.isInline() &&
1962 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1963
1964 // We only need to use thread-safe statics for local non-TLS variables and
1965 // inline variables; other global initialization is always single-threaded
1966 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001967 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001968 (D.isLocalVarDecl() || NonTemplateInline) &&
1969 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001970
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001971 // If we have a global variable with internal linkage and thread-safe statics
1972 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001973 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1974
1975 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001976 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001977 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001978 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001979 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001980 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001981 // Guard variables are 64 bits in the generic ABI and size width on ARM
1982 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001983 if (UseARMGuardVarABI) {
1984 guardTy = CGF.SizeTy;
1985 guardAlignment = CGF.getSizeAlign();
1986 } else {
1987 guardTy = CGF.Int64Ty;
1988 guardAlignment = CharUnits::fromQuantity(
1989 CGM.getDataLayout().getABITypeAlignment(guardTy));
1990 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001991 }
John McCallb88a5662012-03-30 21:00:39 +00001992 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001993
John McCallb88a5662012-03-30 21:00:39 +00001994 // Create the guard variable if we don't already have it (as we
1995 // might if we're double-emitting this function body).
1996 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1997 if (!guard) {
1998 // Mangle the name for the guard.
1999 SmallString<256> guardName;
2000 {
2001 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002002 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002003 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002004
John McCallb88a5662012-03-30 21:00:39 +00002005 // Create the guard variable with a zero-initializer.
2006 // Just absorb linkage and visibility from the guarded variable.
2007 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2008 false, var->getLinkage(),
2009 llvm::ConstantInt::get(guardTy, 0),
2010 guardName.str());
2011 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002012 // If the variable is thread-local, so is its guard variable.
2013 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002014 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002015
Yaron Keren5bfa1082015-09-03 20:33:29 +00002016 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2017 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002018 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002019 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002020 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002021 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2022 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002023 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002024 // An inline variable's guard function is run from the per-TU
2025 // initialization function, not via a dedicated global ctor function, so
2026 // we can't put it in a comdat.
2027 if (!NonTemplateInline)
2028 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002029 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2030 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002031 }
2032
John McCallb88a5662012-03-30 21:00:39 +00002033 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2034 }
John McCall87590e62012-03-30 07:09:50 +00002035
John McCall7f416cc2015-09-08 08:05:57 +00002036 Address guardAddr = Address(guard, guardAlignment);
2037
John McCall68ff0372010-09-08 01:44:27 +00002038 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002039 //
John McCall68ff0372010-09-08 01:44:27 +00002040 // Itanium C++ ABI 3.3.2:
2041 // The following is pseudo-code showing how these functions can be used:
2042 // if (obj_guard.first_byte == 0) {
2043 // if ( __cxa_guard_acquire (&obj_guard) ) {
2044 // try {
2045 // ... initialize the object ...;
2046 // } catch (...) {
2047 // __cxa_guard_abort (&obj_guard);
2048 // throw;
2049 // }
2050 // ... queue object destructor with __cxa_atexit() ...;
2051 // __cxa_guard_release (&obj_guard);
2052 // }
2053 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002054
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002055 // Load the first byte of the guard variable.
2056 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002057 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002058
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002059 // Itanium ABI:
2060 // An implementation supporting thread-safety on multiprocessor
2061 // systems must also guarantee that references to the initialized
2062 // object do not occur before the load of the initialization flag.
2063 //
2064 // In LLVM, we do this by marking the load Acquire.
2065 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002066 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002067
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002068 // For ARM, we should only check the first bit, rather than the entire byte:
2069 //
2070 // ARM C++ ABI 3.2.3.1:
2071 // To support the potential use of initialization guard variables
2072 // as semaphores that are the target of ARM SWP and LDREX/STREX
2073 // synchronizing instructions we define a static initialization
2074 // guard variable to be a 4-byte aligned, 4-byte word with the
2075 // following inline access protocol.
2076 // #define INITIALIZED 1
2077 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2078 // if (__cxa_guard_acquire(&obj_guard))
2079 // ...
2080 // }
2081 //
2082 // and similarly for ARM64:
2083 //
2084 // ARM64 C++ ABI 3.2.2:
2085 // This ABI instead only specifies the value bit 0 of the static guard
2086 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2087 // variable is not initialized and 1 when it is.
2088 llvm::Value *V =
2089 (UseARMGuardVarABI && !useInt8GuardVariable)
2090 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2091 : LI;
2092 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002093
2094 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2095 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2096
2097 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002098 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002099
2100 CGF.EmitBlock(InitCheckBlock);
2101
2102 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002103 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002104 // Call __cxa_guard_acquire.
2105 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002106 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002107
2108 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2109
2110 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2111 InitBlock, EndBlock);
2112
2113 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002114 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002115
2116 CGF.EmitBlock(InitBlock);
2117 }
2118
2119 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002120 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002121
John McCall5aa52592011-06-17 07:33:57 +00002122 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002123 // Pop the guard-abort cleanup if we pushed one.
2124 CGF.PopCleanupBlock();
2125
2126 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002127 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2128 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002129 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002130 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002131 }
2132
2133 CGF.EmitBlock(EndBlock);
2134}
John McCallc84ed6a2012-05-01 06:13:13 +00002135
2136/// Register a global destructor using __cxa_atexit.
2137static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2138 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002139 llvm::Constant *addr,
2140 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002141 const char *Name = "__cxa_atexit";
2142 if (TLS) {
2143 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002144 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002145 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002146
John McCallc84ed6a2012-05-01 06:13:13 +00002147 // We're assuming that the destructor function is something we can
2148 // reasonably call with the default CC. Go ahead and cast it to the
2149 // right prototype.
2150 llvm::Type *dtorTy =
2151 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2152
2153 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2154 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2155 llvm::FunctionType *atexitTy =
2156 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2157
2158 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002159 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002160 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2161 fn->setDoesNotThrow();
2162
2163 // Create a variable that binds the atexit to this shared object.
2164 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002165 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2166 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2167 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002168
2169 llvm::Value *args[] = {
2170 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2171 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2172 handle
2173 };
John McCall882987f2013-02-28 19:01:20 +00002174 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002175}
2176
2177/// Register a global destructor as best as we know how.
2178void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002179 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002180 llvm::Constant *dtor,
2181 llvm::Constant *addr) {
2182 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002183 if (CGM.getCodeGenOpts().CXAAtExit)
2184 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2185
2186 if (D.getTLSKind())
2187 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002188
2189 // In Apple kexts, we want to add a global destructor entry.
2190 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002191 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002192 // Generate a global destructor entry.
2193 return CGM.AddCXXDtorEntry(dtor, addr);
2194 }
2195
David Blaikieebe87e12013-08-27 23:57:18 +00002196 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002197}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002198
David Majnemer9b21c332014-07-11 20:28:10 +00002199static bool isThreadWrapperReplaceable(const VarDecl *VD,
2200 CodeGen::CodeGenModule &CGM) {
2201 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002202 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002203 // the thread wrapper instead of directly referencing the backing variable.
2204 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002205 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002206}
2207
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002208/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002209/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002210/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002211static llvm::GlobalValue::LinkageTypes
2212getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2213 llvm::GlobalValue::LinkageTypes VarLinkage =
2214 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2215
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002216 // For internal linkage variables, we don't need an external or weak wrapper.
2217 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2218 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002219
David Majnemer9b21c332014-07-11 20:28:10 +00002220 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002221 if (isThreadWrapperReplaceable(VD, CGM))
2222 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2223 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2224 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002225 return llvm::GlobalValue::WeakODRLinkage;
2226}
2227
2228llvm::Function *
2229ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002230 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002231 // Mangle the name for the thread_local wrapper function.
2232 SmallString<256> WrapperName;
2233 {
2234 llvm::raw_svector_ostream Out(WrapperName);
2235 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002236 }
2237
Akira Hatanaka26907f92016-01-15 03:34:06 +00002238 // FIXME: If VD is a definition, we should regenerate the function attributes
2239 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002240 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002241 return cast<llvm::Function>(V);
2242
Akira Hatanaka26907f92016-01-15 03:34:06 +00002243 QualType RetQT = VD->getType();
2244 if (RetQT->isReferenceType())
2245 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002246
John McCallc56a8b32016-03-11 04:30:31 +00002247 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2248 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002249
2250 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002251 llvm::Function *Wrapper =
2252 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2253 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002254
2255 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2256
2257 if (VD->hasDefinition())
2258 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2259
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002260 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002261 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2262 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2263 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002264 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002265
2266 if (isThreadWrapperReplaceable(VD, CGM)) {
2267 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2268 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2269 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002270 return Wrapper;
2271}
2272
2273void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002274 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2275 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2276 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002277 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002278
2279 // Separate initializers into those with ordered (or partially-ordered)
2280 // initialization and those with unordered initialization.
2281 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2282 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2283 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2284 if (isTemplateInstantiation(
2285 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2286 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2287 CXXThreadLocalInits[I];
2288 else
2289 OrderedInits.push_back(CXXThreadLocalInits[I]);
2290 }
2291
2292 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002293 // Generate a guarded initialization function.
2294 llvm::FunctionType *FTy =
2295 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002296 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2297 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002298 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002299 /*TLS=*/true);
2300 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2301 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2302 llvm::GlobalVariable::InternalLinkage,
2303 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2304 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002305
2306 CharUnits GuardAlign = CharUnits::One();
2307 Guard->setAlignment(GuardAlign.getQuantity());
2308
Richard Smithfbe23692017-01-13 00:43:31 +00002309 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2310 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002311 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2312 if (CGM.getTarget().getTriple().isOSDarwin()) {
2313 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2314 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2315 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002316 }
Richard Smithfbe23692017-01-13 00:43:31 +00002317
2318 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002319 for (const VarDecl *VD : CXXThreadLocals) {
2320 llvm::GlobalVariable *Var =
2321 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002322 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002323
David Majnemer9b21c332014-07-11 20:28:10 +00002324 // Some targets require that all access to thread local variables go through
2325 // the thread wrapper. This means that we cannot attempt to create a thread
2326 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002327 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2328 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002329 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002330 }
David Majnemer9b21c332014-07-11 20:28:10 +00002331
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002332 // Mangle the name for the thread_local initialization function.
2333 SmallString<256> InitFnName;
2334 {
2335 llvm::raw_svector_ostream Out(InitFnName);
2336 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002337 }
2338
2339 // If we have a definition for the variable, emit the initialization
2340 // function as an alias to the global Init function (if any). Otherwise,
2341 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002342 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002343 bool InitIsInitFunc = false;
2344 if (VD->hasDefinition()) {
2345 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002346 llvm::Function *InitFuncToUse = InitFunc;
2347 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2348 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2349 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002350 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002351 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002352 } else {
2353 // Emit a weak global function referring to the initialization function.
2354 // This function will not exist if the TU defining the thread_local
2355 // variable in question does not need any dynamic initialization for
2356 // its thread_local variables.
2357 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002358 Init = llvm::Function::Create(FnTy,
2359 llvm::GlobalVariable::ExternalWeakLinkage,
2360 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002361 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002362 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002363 }
2364
2365 if (Init)
2366 Init->setVisibility(Var->getVisibility());
2367
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002368 llvm::LLVMContext &Context = CGM.getModule().getContext();
2369 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002370 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002371 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002372 if (Init) {
2373 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2374 if (isThreadWrapperReplaceable(VD, CGM))
2375 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2376 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002377 } else {
2378 // Don't know whether we have an init function. Call it if it exists.
2379 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2380 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2381 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2382 Builder.CreateCondBr(Have, InitBB, ExitBB);
2383
2384 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002385 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002386 Builder.CreateBr(ExitBB);
2387
2388 Builder.SetInsertPoint(ExitBB);
2389 }
2390
2391 // For a reference, the result of the wrapper function is a pointer to
2392 // the referenced object.
2393 llvm::Value *Val = Var;
2394 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002395 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2396 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002397 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002398 if (Val->getType() != Wrapper->getReturnType())
2399 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2400 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002401 Builder.CreateRet(Val);
2402 }
2403}
2404
Richard Smith0f383742014-03-26 22:48:22 +00002405LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2406 const VarDecl *VD,
2407 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002408 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002409 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002410
Manman Renb0b3af72015-12-17 00:42:36 +00002411 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002412 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002413
2414 LValue LV;
2415 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002416 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002417 else
Manman Renb0b3af72015-12-17 00:42:36 +00002418 LV = CGF.MakeAddrLValue(CallVal, LValType,
2419 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002420 // FIXME: need setObjCGCLValueClass?
2421 return LV;
2422}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002423
2424/// Return whether the given global decl needs a VTT parameter, which it does
2425/// if it's a base constructor or destructor with virtual bases.
2426bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2427 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2428
2429 // We don't have any virtual bases, just return early.
2430 if (!MD->getParent()->getNumVBases())
2431 return false;
2432
2433 // Check if we have a base constructor.
2434 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2435 return true;
2436
2437 // Check if we have a base destructor.
2438 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2439 return true;
2440
2441 return false;
2442}
David Majnemere2cb8d12014-07-07 06:20:47 +00002443
2444namespace {
2445class ItaniumRTTIBuilder {
2446 CodeGenModule &CGM; // Per-module state.
2447 llvm::LLVMContext &VMContext;
2448 const ItaniumCXXABI &CXXABI; // Per-module state.
2449
2450 /// Fields - The fields of the RTTI descriptor currently being built.
2451 SmallVector<llvm::Constant *, 16> Fields;
2452
2453 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2454 llvm::GlobalVariable *
2455 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2456
2457 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2458 /// descriptor of the given type.
2459 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2460
2461 /// BuildVTablePointer - Build the vtable pointer for the given type.
2462 void BuildVTablePointer(const Type *Ty);
2463
2464 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2465 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2466 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2467
2468 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2469 /// classes with bases that do not satisfy the abi::__si_class_type_info
2470 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2471 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2472
2473 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2474 /// for pointer types.
2475 void BuildPointerTypeInfo(QualType PointeeTy);
2476
2477 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2478 /// type_info for an object type.
2479 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2480
2481 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2482 /// struct, used for member pointer types.
2483 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2484
2485public:
2486 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2487 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2488
2489 // Pointer type info flags.
2490 enum {
2491 /// PTI_Const - Type has const qualifier.
2492 PTI_Const = 0x1,
2493
2494 /// PTI_Volatile - Type has volatile qualifier.
2495 PTI_Volatile = 0x2,
2496
2497 /// PTI_Restrict - Type has restrict qualifier.
2498 PTI_Restrict = 0x4,
2499
2500 /// PTI_Incomplete - Type is incomplete.
2501 PTI_Incomplete = 0x8,
2502
2503 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2504 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002505 PTI_ContainingClassIncomplete = 0x10,
2506
2507 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2508 //PTI_TransactionSafe = 0x20,
2509
2510 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2511 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002512 };
2513
2514 // VMI type info flags.
2515 enum {
2516 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2517 VMI_NonDiamondRepeat = 0x1,
2518
2519 /// VMI_DiamondShaped - Class is diamond shaped.
2520 VMI_DiamondShaped = 0x2
2521 };
2522
2523 // Base class type info flags.
2524 enum {
2525 /// BCTI_Virtual - Base class is virtual.
2526 BCTI_Virtual = 0x1,
2527
2528 /// BCTI_Public - Base class is public.
2529 BCTI_Public = 0x2
2530 };
2531
2532 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2533 ///
2534 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002535 /// \param DLLExport - true to mark the RTTI value as DLLExport
2536 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2537 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002538};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002539}
David Majnemere2cb8d12014-07-07 06:20:47 +00002540
2541llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2542 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002543 SmallString<256> Name;
2544 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002545 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002546
2547 // We know that the mangled name of the type starts at index 4 of the
2548 // mangled name of the typename, so we can just index into it in order to
2549 // get the mangled name of the type.
2550 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2551 Name.substr(4));
2552
2553 llvm::GlobalVariable *GV =
2554 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2555
2556 GV->setInitializer(Init);
2557
2558 return GV;
2559}
2560
2561llvm::Constant *
2562ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2563 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002564 SmallString<256> Name;
2565 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002566 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002567
2568 // Look for an existing global.
2569 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2570
2571 if (!GV) {
2572 // Create a new global variable.
2573 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2574 /*Constant=*/true,
2575 llvm::GlobalValue::ExternalLinkage, nullptr,
2576 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002577 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2578 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2579 if (RD->hasAttr<DLLImportAttr>())
2580 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2581 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002582 }
2583
2584 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2585}
2586
2587/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2588/// info for that type is defined in the standard library.
2589static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2590 // Itanium C++ ABI 2.9.2:
2591 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2592 // the run-time support library. Specifically, the run-time support
2593 // library should contain type_info objects for the types X, X* and
2594 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2595 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2596 // long, unsigned long, long long, unsigned long long, float, double,
2597 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2598 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002599 //
2600 // GCC also emits RTTI for __int128.
2601 // FIXME: We do not emit RTTI information for decimal types here.
2602
2603 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002604 switch (Ty->getKind()) {
2605 case BuiltinType::Void:
2606 case BuiltinType::NullPtr:
2607 case BuiltinType::Bool:
2608 case BuiltinType::WChar_S:
2609 case BuiltinType::WChar_U:
2610 case BuiltinType::Char_U:
2611 case BuiltinType::Char_S:
2612 case BuiltinType::UChar:
2613 case BuiltinType::SChar:
2614 case BuiltinType::Short:
2615 case BuiltinType::UShort:
2616 case BuiltinType::Int:
2617 case BuiltinType::UInt:
2618 case BuiltinType::Long:
2619 case BuiltinType::ULong:
2620 case BuiltinType::LongLong:
2621 case BuiltinType::ULongLong:
2622 case BuiltinType::Half:
2623 case BuiltinType::Float:
2624 case BuiltinType::Double:
2625 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002626 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002627 case BuiltinType::Char16:
2628 case BuiltinType::Char32:
2629 case BuiltinType::Int128:
2630 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002631 return true;
2632
Alexey Bader954ba212016-04-08 13:40:33 +00002633#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2634 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002635#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002636 case BuiltinType::OCLSampler:
2637 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002638 case BuiltinType::OCLClkEvent:
2639 case BuiltinType::OCLQueue:
2640 case BuiltinType::OCLNDRange:
2641 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002642 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002643
2644 case BuiltinType::Dependent:
2645#define BUILTIN_TYPE(Id, SingletonId)
2646#define PLACEHOLDER_TYPE(Id, SingletonId) \
2647 case BuiltinType::Id:
2648#include "clang/AST/BuiltinTypes.def"
2649 llvm_unreachable("asking for RRTI for a placeholder type!");
2650
2651 case BuiltinType::ObjCId:
2652 case BuiltinType::ObjCClass:
2653 case BuiltinType::ObjCSel:
2654 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2655 }
2656
2657 llvm_unreachable("Invalid BuiltinType Kind!");
2658}
2659
2660static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2661 QualType PointeeTy = PointerTy->getPointeeType();
2662 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2663 if (!BuiltinTy)
2664 return false;
2665
2666 // Check the qualifiers.
2667 Qualifiers Quals = PointeeTy.getQualifiers();
2668 Quals.removeConst();
2669
2670 if (!Quals.empty())
2671 return false;
2672
2673 return TypeInfoIsInStandardLibrary(BuiltinTy);
2674}
2675
2676/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2677/// information for the given type exists in the standard library.
2678static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2679 // Type info for builtin types is defined in the standard library.
2680 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2681 return TypeInfoIsInStandardLibrary(BuiltinTy);
2682
2683 // Type info for some pointer types to builtin types is defined in the
2684 // standard library.
2685 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2686 return TypeInfoIsInStandardLibrary(PointerTy);
2687
2688 return false;
2689}
2690
2691/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2692/// the given type exists somewhere else, and that we should not emit the type
2693/// information in this translation unit. Assumes that it is not a
2694/// standard-library type.
2695static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2696 QualType Ty) {
2697 ASTContext &Context = CGM.getContext();
2698
2699 // If RTTI is disabled, assume it might be disabled in the
2700 // translation unit that defines any potential key function, too.
2701 if (!Context.getLangOpts().RTTI) return false;
2702
2703 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2704 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2705 if (!RD->hasDefinition())
2706 return false;
2707
2708 if (!RD->isDynamicClass())
2709 return false;
2710
2711 // FIXME: this may need to be reconsidered if the key function
2712 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002713 // N.B. We must always emit the RTTI data ourselves if there exists a key
2714 // function.
2715 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002716 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002717 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002718
David Majnemerbe9022c2015-08-06 20:56:55 +00002719 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002720 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002721 }
2722
2723 return false;
2724}
2725
2726/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2727static bool IsIncompleteClassType(const RecordType *RecordTy) {
2728 return !RecordTy->getDecl()->isCompleteDefinition();
2729}
2730
2731/// ContainsIncompleteClassType - Returns whether the given type contains an
2732/// incomplete class type. This is true if
2733///
2734/// * The given type is an incomplete class type.
2735/// * The given type is a pointer type whose pointee type contains an
2736/// incomplete class type.
2737/// * The given type is a member pointer type whose class is an incomplete
2738/// class type.
2739/// * The given type is a member pointer type whoise pointee type contains an
2740/// incomplete class type.
2741/// is an indirect or direct pointer to an incomplete class type.
2742static bool ContainsIncompleteClassType(QualType Ty) {
2743 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2744 if (IsIncompleteClassType(RecordTy))
2745 return true;
2746 }
2747
2748 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2749 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2750
2751 if (const MemberPointerType *MemberPointerTy =
2752 dyn_cast<MemberPointerType>(Ty)) {
2753 // Check if the class type is incomplete.
2754 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2755 if (IsIncompleteClassType(ClassType))
2756 return true;
2757
2758 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2759 }
2760
2761 return false;
2762}
2763
2764// CanUseSingleInheritance - Return whether the given record decl has a "single,
2765// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2766// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2767static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2768 // Check the number of bases.
2769 if (RD->getNumBases() != 1)
2770 return false;
2771
2772 // Get the base.
2773 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2774
2775 // Check that the base is not virtual.
2776 if (Base->isVirtual())
2777 return false;
2778
2779 // Check that the base is public.
2780 if (Base->getAccessSpecifier() != AS_public)
2781 return false;
2782
2783 // Check that the class is dynamic iff the base is.
2784 const CXXRecordDecl *BaseDecl =
2785 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2786 if (!BaseDecl->isEmpty() &&
2787 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2788 return false;
2789
2790 return true;
2791}
2792
2793void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2794 // abi::__class_type_info.
2795 static const char * const ClassTypeInfo =
2796 "_ZTVN10__cxxabiv117__class_type_infoE";
2797 // abi::__si_class_type_info.
2798 static const char * const SIClassTypeInfo =
2799 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2800 // abi::__vmi_class_type_info.
2801 static const char * const VMIClassTypeInfo =
2802 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2803
2804 const char *VTableName = nullptr;
2805
2806 switch (Ty->getTypeClass()) {
2807#define TYPE(Class, Base)
2808#define ABSTRACT_TYPE(Class, Base)
2809#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2810#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2811#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2812#include "clang/AST/TypeNodes.def"
2813 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2814
2815 case Type::LValueReference:
2816 case Type::RValueReference:
2817 llvm_unreachable("References shouldn't get here");
2818
2819 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002820 case Type::DeducedTemplateSpecialization:
2821 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002822
Xiuli Pan9c14e282016-01-09 12:53:17 +00002823 case Type::Pipe:
2824 llvm_unreachable("Pipe types shouldn't get here");
2825
David Majnemere2cb8d12014-07-07 06:20:47 +00002826 case Type::Builtin:
2827 // GCC treats vector and complex types as fundamental types.
2828 case Type::Vector:
2829 case Type::ExtVector:
2830 case Type::Complex:
2831 case Type::Atomic:
2832 // FIXME: GCC treats block pointers as fundamental types?!
2833 case Type::BlockPointer:
2834 // abi::__fundamental_type_info.
2835 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2836 break;
2837
2838 case Type::ConstantArray:
2839 case Type::IncompleteArray:
2840 case Type::VariableArray:
2841 // abi::__array_type_info.
2842 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2843 break;
2844
2845 case Type::FunctionNoProto:
2846 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002847 // abi::__function_type_info.
2848 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002849 break;
2850
2851 case Type::Enum:
2852 // abi::__enum_type_info.
2853 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2854 break;
2855
2856 case Type::Record: {
2857 const CXXRecordDecl *RD =
2858 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2859
2860 if (!RD->hasDefinition() || !RD->getNumBases()) {
2861 VTableName = ClassTypeInfo;
2862 } else if (CanUseSingleInheritance(RD)) {
2863 VTableName = SIClassTypeInfo;
2864 } else {
2865 VTableName = VMIClassTypeInfo;
2866 }
2867
2868 break;
2869 }
2870
2871 case Type::ObjCObject:
2872 // Ignore protocol qualifiers.
2873 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2874
2875 // Handle id and Class.
2876 if (isa<BuiltinType>(Ty)) {
2877 VTableName = ClassTypeInfo;
2878 break;
2879 }
2880
2881 assert(isa<ObjCInterfaceType>(Ty));
2882 // Fall through.
2883
2884 case Type::ObjCInterface:
2885 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2886 VTableName = SIClassTypeInfo;
2887 } else {
2888 VTableName = ClassTypeInfo;
2889 }
2890 break;
2891
2892 case Type::ObjCObjectPointer:
2893 case Type::Pointer:
2894 // abi::__pointer_type_info.
2895 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2896 break;
2897
2898 case Type::MemberPointer:
2899 // abi::__pointer_to_member_type_info.
2900 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2901 break;
2902 }
2903
2904 llvm::Constant *VTable =
2905 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2906
2907 llvm::Type *PtrDiffTy =
2908 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2909
2910 // The vtable address point is 2.
2911 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002912 VTable =
2913 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002914 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2915
2916 Fields.push_back(VTable);
2917}
2918
2919/// \brief Return the linkage that the type info and type info name constants
2920/// should have for the given type.
2921static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2922 QualType Ty) {
2923 // Itanium C++ ABI 2.9.5p7:
2924 // In addition, it and all of the intermediate abi::__pointer_type_info
2925 // structs in the chain down to the abi::__class_type_info for the
2926 // incomplete class type must be prevented from resolving to the
2927 // corresponding type_info structs for the complete class type, possibly
2928 // by making them local static objects. Finally, a dummy class RTTI is
2929 // generated for the incomplete type that will not resolve to the final
2930 // complete class RTTI (because the latter need not exist), possibly by
2931 // making it a local static object.
2932 if (ContainsIncompleteClassType(Ty))
2933 return llvm::GlobalValue::InternalLinkage;
2934
2935 switch (Ty->getLinkage()) {
2936 case NoLinkage:
2937 case InternalLinkage:
2938 case UniqueExternalLinkage:
2939 return llvm::GlobalValue::InternalLinkage;
2940
2941 case VisibleNoLinkage:
2942 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002943 // RTTI is not enabled, which means that this type info struct is going
2944 // to be used for exception handling. Give it linkonce_odr linkage.
2945 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002946 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002947
2948 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2949 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2950 if (RD->hasAttr<WeakAttr>())
2951 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002952 if (CGM.getTriple().isWindowsItaniumEnvironment())
2953 if (RD->hasAttr<DLLImportAttr>())
2954 return llvm::GlobalValue::ExternalLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002955 if (RD->isDynamicClass()) {
2956 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2957 // MinGW won't export the RTTI information when there is a key function.
2958 // Make sure we emit our own copy instead of attempting to dllimport it.
2959 if (RD->hasAttr<DLLImportAttr>() &&
2960 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2961 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2962 return LT;
2963 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002964 }
2965
2966 return llvm::GlobalValue::LinkOnceODRLinkage;
2967 }
2968
2969 llvm_unreachable("Invalid linkage!");
2970}
2971
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002972llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
2973 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002974 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002975 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002976
2977 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002978 SmallString<256> Name;
2979 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002980 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002981
2982 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2983 if (OldGV && !OldGV->isDeclaration()) {
2984 assert(!OldGV->hasAvailableExternallyLinkage() &&
2985 "available_externally typeinfos not yet implemented");
2986
2987 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2988 }
2989
2990 // Check if there is already an external RTTI descriptor for this type.
2991 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2992 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2993 return GetAddrOfExternalRTTIDescriptor(Ty);
2994
2995 // Emit the standard library with external linkage.
2996 llvm::GlobalVariable::LinkageTypes Linkage;
2997 if (IsStdLib)
2998 Linkage = llvm::GlobalValue::ExternalLinkage;
2999 else
3000 Linkage = getTypeInfoLinkage(CGM, Ty);
3001
3002 // Add the vtable pointer.
3003 BuildVTablePointer(cast<Type>(Ty));
3004
3005 // And the name.
3006 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3007 llvm::Constant *TypeNameField;
3008
3009 // If we're supposed to demote the visibility, be sure to set a flag
3010 // to use a string comparison for type_info comparisons.
3011 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3012 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3013 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3014 // The flag is the sign bit, which on ARM64 is defined to be clear
3015 // for global pointers. This is very ARM64-specific.
3016 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3017 llvm::Constant *flag =
3018 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3019 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3020 TypeNameField =
3021 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3022 } else {
3023 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3024 }
3025 Fields.push_back(TypeNameField);
3026
3027 switch (Ty->getTypeClass()) {
3028#define TYPE(Class, Base)
3029#define ABSTRACT_TYPE(Class, Base)
3030#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3031#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3032#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3033#include "clang/AST/TypeNodes.def"
3034 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3035
3036 // GCC treats vector types as fundamental types.
3037 case Type::Builtin:
3038 case Type::Vector:
3039 case Type::ExtVector:
3040 case Type::Complex:
3041 case Type::BlockPointer:
3042 // Itanium C++ ABI 2.9.5p4:
3043 // abi::__fundamental_type_info adds no data members to std::type_info.
3044 break;
3045
3046 case Type::LValueReference:
3047 case Type::RValueReference:
3048 llvm_unreachable("References shouldn't get here");
3049
3050 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003051 case Type::DeducedTemplateSpecialization:
3052 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003053
Xiuli Pan9c14e282016-01-09 12:53:17 +00003054 case Type::Pipe:
3055 llvm_unreachable("Pipe type shouldn't get here");
3056
David Majnemere2cb8d12014-07-07 06:20:47 +00003057 case Type::ConstantArray:
3058 case Type::IncompleteArray:
3059 case Type::VariableArray:
3060 // Itanium C++ ABI 2.9.5p5:
3061 // abi::__array_type_info adds no data members to std::type_info.
3062 break;
3063
3064 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003065 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003066 // Itanium C++ ABI 2.9.5p5:
3067 // abi::__function_type_info adds no data members to std::type_info.
3068 break;
3069
3070 case Type::Enum:
3071 // Itanium C++ ABI 2.9.5p5:
3072 // abi::__enum_type_info adds no data members to std::type_info.
3073 break;
3074
3075 case Type::Record: {
3076 const CXXRecordDecl *RD =
3077 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3078 if (!RD->hasDefinition() || !RD->getNumBases()) {
3079 // We don't need to emit any fields.
3080 break;
3081 }
3082
3083 if (CanUseSingleInheritance(RD))
3084 BuildSIClassTypeInfo(RD);
3085 else
3086 BuildVMIClassTypeInfo(RD);
3087
3088 break;
3089 }
3090
3091 case Type::ObjCObject:
3092 case Type::ObjCInterface:
3093 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3094 break;
3095
3096 case Type::ObjCObjectPointer:
3097 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3098 break;
3099
3100 case Type::Pointer:
3101 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3102 break;
3103
3104 case Type::MemberPointer:
3105 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3106 break;
3107
3108 case Type::Atomic:
3109 // No fields, at least for the moment.
3110 break;
3111 }
3112
3113 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3114
Rafael Espindolacb92c192015-01-15 23:18:01 +00003115 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003116 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003117 new llvm::GlobalVariable(M, Init->getType(),
3118 /*Constant=*/true, Linkage, Init, Name);
3119
David Majnemere2cb8d12014-07-07 06:20:47 +00003120 // If there's already an old global variable, replace it with the new one.
3121 if (OldGV) {
3122 GV->takeName(OldGV);
3123 llvm::Constant *NewPtr =
3124 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3125 OldGV->replaceAllUsesWith(NewPtr);
3126 OldGV->eraseFromParent();
3127 }
3128
Yaron Keren04da2382015-07-29 15:42:28 +00003129 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3130 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3131
David Majnemere2cb8d12014-07-07 06:20:47 +00003132 // The Itanium ABI specifies that type_info objects must be globally
3133 // unique, with one exception: if the type is an incomplete class
3134 // type or a (possibly indirect) pointer to one. That exception
3135 // affects the general case of comparing type_info objects produced
3136 // by the typeid operator, which is why the comparison operators on
3137 // std::type_info generally use the type_info name pointers instead
3138 // of the object addresses. However, the language's built-in uses
3139 // of RTTI generally require class types to be complete, even when
3140 // manipulating pointers to those class types. This allows the
3141 // implementation of dynamic_cast to rely on address equality tests,
3142 // which is much faster.
3143
3144 // All of this is to say that it's important that both the type_info
3145 // object and the type_info name be uniqued when weakly emitted.
3146
3147 // Give the type_info object and name the formal visibility of the
3148 // type itself.
3149 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3150 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3151 // If the linkage is local, only default visibility makes sense.
3152 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3153 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3154 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3155 else
3156 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003157
David Majnemere2cb8d12014-07-07 06:20:47 +00003158 TypeName->setVisibility(llvmVisibility);
3159 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003160
3161 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3162 auto RD = Ty->getAsCXXRecordDecl();
3163 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3164 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3165 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Saleem Abdulrasool317dcc32016-12-05 22:40:20 +00003166 } else if (CGM.getLangOpts().RTTI && RD && RD->hasAttr<DLLImportAttr>()) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003167 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3168 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3169
3170 // Because the typename and the typeinfo are DLL import, convert them to
3171 // declarations rather than definitions. The initializers still need to
3172 // be constructed to calculate the type for the declarations.
3173 TypeName->setInitializer(nullptr);
3174 GV->setInitializer(nullptr);
3175 }
3176 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003177
3178 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3179}
3180
David Majnemere2cb8d12014-07-07 06:20:47 +00003181/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3182/// for the given Objective-C object type.
3183void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3184 // Drop qualifiers.
3185 const Type *T = OT->getBaseType().getTypePtr();
3186 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3187
3188 // The builtin types are abi::__class_type_infos and don't require
3189 // extra fields.
3190 if (isa<BuiltinType>(T)) return;
3191
3192 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3193 ObjCInterfaceDecl *Super = Class->getSuperClass();
3194
3195 // Root classes are also __class_type_info.
3196 if (!Super) return;
3197
3198 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3199
3200 // Everything else is single inheritance.
3201 llvm::Constant *BaseTypeInfo =
3202 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3203 Fields.push_back(BaseTypeInfo);
3204}
3205
3206/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3207/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3208void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3209 // Itanium C++ ABI 2.9.5p6b:
3210 // It adds to abi::__class_type_info a single member pointing to the
3211 // type_info structure for the base type,
3212 llvm::Constant *BaseTypeInfo =
3213 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3214 Fields.push_back(BaseTypeInfo);
3215}
3216
3217namespace {
3218 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3219 /// a class hierarchy.
3220 struct SeenBases {
3221 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3222 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3223 };
3224}
3225
3226/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3227/// abi::__vmi_class_type_info.
3228///
3229static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3230 SeenBases &Bases) {
3231
3232 unsigned Flags = 0;
3233
3234 const CXXRecordDecl *BaseDecl =
3235 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3236
3237 if (Base->isVirtual()) {
3238 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003239 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003240 // If this virtual base has been seen before, then the class is diamond
3241 // shaped.
3242 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3243 } else {
3244 if (Bases.NonVirtualBases.count(BaseDecl))
3245 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3246 }
3247 } else {
3248 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003249 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003250 // If this non-virtual base has been seen before, then the class has non-
3251 // diamond shaped repeated inheritance.
3252 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3253 } else {
3254 if (Bases.VirtualBases.count(BaseDecl))
3255 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3256 }
3257 }
3258
3259 // Walk all bases.
3260 for (const auto &I : BaseDecl->bases())
3261 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3262
3263 return Flags;
3264}
3265
3266static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3267 unsigned Flags = 0;
3268 SeenBases Bases;
3269
3270 // Walk all bases.
3271 for (const auto &I : RD->bases())
3272 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3273
3274 return Flags;
3275}
3276
3277/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3278/// classes with bases that do not satisfy the abi::__si_class_type_info
3279/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3280void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3281 llvm::Type *UnsignedIntLTy =
3282 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3283
3284 // Itanium C++ ABI 2.9.5p6c:
3285 // __flags is a word with flags describing details about the class
3286 // structure, which may be referenced by using the __flags_masks
3287 // enumeration. These flags refer to both direct and indirect bases.
3288 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3289 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3290
3291 // Itanium C++ ABI 2.9.5p6c:
3292 // __base_count is a word with the number of direct proper base class
3293 // descriptions that follow.
3294 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3295
3296 if (!RD->getNumBases())
3297 return;
3298
David Majnemere2cb8d12014-07-07 06:20:47 +00003299 // Now add the base class descriptions.
3300
3301 // Itanium C++ ABI 2.9.5p6c:
3302 // __base_info[] is an array of base class descriptions -- one for every
3303 // direct proper base. Each description is of the type:
3304 //
3305 // struct abi::__base_class_type_info {
3306 // public:
3307 // const __class_type_info *__base_type;
3308 // long __offset_flags;
3309 //
3310 // enum __offset_flags_masks {
3311 // __virtual_mask = 0x1,
3312 // __public_mask = 0x2,
3313 // __offset_shift = 8
3314 // };
3315 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003316
3317 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3318 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3319 // LLP64 platforms.
3320 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3321 // LLP64 platforms.
3322 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3323 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3324 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3325 OffsetFlagsTy = CGM.getContext().LongLongTy;
3326 llvm::Type *OffsetFlagsLTy =
3327 CGM.getTypes().ConvertType(OffsetFlagsTy);
3328
David Majnemere2cb8d12014-07-07 06:20:47 +00003329 for (const auto &Base : RD->bases()) {
3330 // The __base_type member points to the RTTI for the base type.
3331 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3332
3333 const CXXRecordDecl *BaseDecl =
3334 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3335
3336 int64_t OffsetFlags = 0;
3337
3338 // All but the lower 8 bits of __offset_flags are a signed offset.
3339 // For a non-virtual base, this is the offset in the object of the base
3340 // subobject. For a virtual base, this is the offset in the virtual table of
3341 // the virtual base offset for the virtual base referenced (negative).
3342 CharUnits Offset;
3343 if (Base.isVirtual())
3344 Offset =
3345 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3346 else {
3347 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3348 Offset = Layout.getBaseClassOffset(BaseDecl);
3349 };
3350
3351 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3352
3353 // The low-order byte of __offset_flags contains flags, as given by the
3354 // masks from the enumeration __offset_flags_masks.
3355 if (Base.isVirtual())
3356 OffsetFlags |= BCTI_Virtual;
3357 if (Base.getAccessSpecifier() == AS_public)
3358 OffsetFlags |= BCTI_Public;
3359
Reid Klecknerd8b04662016-08-25 22:16:30 +00003360 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003361 }
3362}
3363
Richard Smitha7d93782016-12-01 03:32:42 +00003364/// Compute the flags for a __pbase_type_info, and remove the corresponding
3365/// pieces from \p Type.
3366static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3367 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003368
Richard Smitha7d93782016-12-01 03:32:42 +00003369 if (Type.isConstQualified())
3370 Flags |= ItaniumRTTIBuilder::PTI_Const;
3371 if (Type.isVolatileQualified())
3372 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3373 if (Type.isRestrictQualified())
3374 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3375 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003376
3377 // Itanium C++ ABI 2.9.5p7:
3378 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3379 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003380 if (ContainsIncompleteClassType(Type))
3381 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3382
3383 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3384 if (Proto->isNothrow(Ctx)) {
3385 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3386 Type = Ctx.getFunctionType(
3387 Proto->getReturnType(), Proto->getParamTypes(),
3388 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3389 }
3390 }
3391
3392 return Flags;
3393}
3394
3395/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3396/// used for pointer types.
3397void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3398 // Itanium C++ ABI 2.9.5p7:
3399 // __flags is a flag word describing the cv-qualification and other
3400 // attributes of the type pointed to
3401 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003402
3403 llvm::Type *UnsignedIntLTy =
3404 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3405 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3406
3407 // Itanium C++ ABI 2.9.5p7:
3408 // __pointee is a pointer to the std::type_info derivation for the
3409 // unqualified type being pointed to.
3410 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003411 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003412 Fields.push_back(PointeeTypeInfo);
3413}
3414
3415/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3416/// struct, used for member pointer types.
3417void
3418ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3419 QualType PointeeTy = Ty->getPointeeType();
3420
David Majnemere2cb8d12014-07-07 06:20:47 +00003421 // Itanium C++ ABI 2.9.5p7:
3422 // __flags is a flag word describing the cv-qualification and other
3423 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003424 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003425
3426 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003427 if (IsIncompleteClassType(ClassType))
3428 Flags |= PTI_ContainingClassIncomplete;
3429
3430 llvm::Type *UnsignedIntLTy =
3431 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3432 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3433
3434 // Itanium C++ ABI 2.9.5p7:
3435 // __pointee is a pointer to the std::type_info derivation for the
3436 // unqualified type being pointed to.
3437 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003438 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003439 Fields.push_back(PointeeTypeInfo);
3440
3441 // Itanium C++ ABI 2.9.5p9:
3442 // __context is a pointer to an abi::__class_type_info corresponding to the
3443 // class type containing the member pointed to
3444 // (e.g., the "A" in "int A::*").
3445 Fields.push_back(
3446 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3447}
3448
David Majnemer443250f2015-03-17 20:35:00 +00003449llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003450 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3451}
3452
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003453void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3454 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003455 QualType PointerType = getContext().getPointerType(Type);
3456 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003457 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3458 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3459 DLLExport);
3460 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3461 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003462}
3463
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003464void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003465 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003466 QualType FundamentalTypes[] = {
3467 getContext().VoidTy, getContext().NullPtrTy,
3468 getContext().BoolTy, getContext().WCharTy,
3469 getContext().CharTy, getContext().UnsignedCharTy,
3470 getContext().SignedCharTy, getContext().ShortTy,
3471 getContext().UnsignedShortTy, getContext().IntTy,
3472 getContext().UnsignedIntTy, getContext().LongTy,
3473 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003474 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3475 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003476 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003477 getContext().LongDoubleTy, getContext().Float128Ty,
3478 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003479 };
3480 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003481 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003482}
3483
3484/// What sort of uniqueness rules should we use for the RTTI for the
3485/// given type?
3486ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3487 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3488 if (shouldRTTIBeUnique())
3489 return RUK_Unique;
3490
3491 // It's only necessary for linkonce_odr or weak_odr linkage.
3492 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3493 Linkage != llvm::GlobalValue::WeakODRLinkage)
3494 return RUK_Unique;
3495
3496 // It's only necessary with default visibility.
3497 if (CanTy->getVisibility() != DefaultVisibility)
3498 return RUK_Unique;
3499
3500 // If we're not required to publish this symbol, hide it.
3501 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3502 return RUK_NonUniqueHidden;
3503
3504 // If we're required to publish this symbol, as we might be under an
3505 // explicit instantiation, leave it with default visibility but
3506 // enable string-comparisons.
3507 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3508 return RUK_NonUniqueVisible;
3509}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003510
Rafael Espindola1e4df922014-09-16 15:18:21 +00003511// Find out how to codegen the complete destructor and constructor
3512namespace {
3513enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3514}
3515static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3516 const CXXMethodDecl *MD) {
3517 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3518 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003519
Rafael Espindola1e4df922014-09-16 15:18:21 +00003520 // The complete and base structors are not equivalent if there are any virtual
3521 // bases, so emit separate functions.
3522 if (MD->getParent()->getNumVBases())
3523 return StructorCodegen::Emit;
3524
3525 GlobalDecl AliasDecl;
3526 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3527 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3528 } else {
3529 const auto *CD = cast<CXXConstructorDecl>(MD);
3530 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3531 }
3532 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3533
3534 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3535 return StructorCodegen::RAUW;
3536
3537 // FIXME: Should we allow available_externally aliases?
3538 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3539 return StructorCodegen::RAUW;
3540
Rafael Espindola0806f982014-09-16 20:19:43 +00003541 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003542 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3543 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3544 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003545 return StructorCodegen::COMDAT;
3546 return StructorCodegen::Emit;
3547 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003548
3549 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003550}
3551
Rafael Espindola1e4df922014-09-16 15:18:21 +00003552static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3553 GlobalDecl AliasDecl,
3554 GlobalDecl TargetDecl) {
3555 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3556
3557 StringRef MangledName = CGM.getMangledName(AliasDecl);
3558 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3559 if (Entry && !Entry->isDeclaration())
3560 return;
3561
3562 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003563
3564 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003565 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003566
3567 // Switch any previous uses to the alias.
3568 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003569 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003570 "declaration exists with different type");
3571 Alias->takeName(Entry);
3572 Entry->replaceAllUsesWith(Alias);
3573 Entry->eraseFromParent();
3574 } else {
3575 Alias->setName(MangledName);
3576 }
3577
3578 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003579 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003580}
3581
3582void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3583 StructorType Type) {
3584 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3585 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3586
3587 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3588
3589 if (Type == StructorType::Complete) {
3590 GlobalDecl CompleteDecl;
3591 GlobalDecl BaseDecl;
3592 if (CD) {
3593 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3594 BaseDecl = GlobalDecl(CD, Ctor_Base);
3595 } else {
3596 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3597 BaseDecl = GlobalDecl(DD, Dtor_Base);
3598 }
3599
3600 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3601 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3602 return;
3603 }
3604
3605 if (CGType == StructorCodegen::RAUW) {
3606 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003607 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003608 CGM.addReplacement(MangledName, Aliasee);
3609 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003610 }
3611 }
3612
3613 // The base destructor is equivalent to the base destructor of its
3614 // base class if there is exactly one non-virtual base class with a
3615 // non-trivial destructor, there are no fields with a non-trivial
3616 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003617 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3618 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003619 return;
3620
Rafael Espindola1e4df922014-09-16 15:18:21 +00003621 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003622
Rafael Espindola1e4df922014-09-16 15:18:21 +00003623 if (CGType == StructorCodegen::COMDAT) {
3624 SmallString<256> Buffer;
3625 llvm::raw_svector_ostream Out(Buffer);
3626 if (DD)
3627 getMangleContext().mangleCXXDtorComdat(DD, Out);
3628 else
3629 getMangleContext().mangleCXXCtorComdat(CD, Out);
3630 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3631 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003632 } else {
3633 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003634 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003635}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003636
3637static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3638 // void *__cxa_begin_catch(void*);
3639 llvm::FunctionType *FTy = llvm::FunctionType::get(
3640 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3641
3642 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3643}
3644
3645static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3646 // void __cxa_end_catch();
3647 llvm::FunctionType *FTy =
3648 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3649
3650 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3651}
3652
3653static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3654 // void *__cxa_get_exception_ptr(void*);
3655 llvm::FunctionType *FTy = llvm::FunctionType::get(
3656 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3657
3658 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3659}
3660
3661namespace {
3662 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3663 /// exception type lets us state definitively that the thrown exception
3664 /// type does not have a destructor. In particular:
3665 /// - Catch-alls tell us nothing, so we have to conservatively
3666 /// assume that the thrown exception might have a destructor.
3667 /// - Catches by reference behave according to their base types.
3668 /// - Catches of non-record types will only trigger for exceptions
3669 /// of non-record types, which never have destructors.
3670 /// - Catches of record types can trigger for arbitrary subclasses
3671 /// of the caught type, so we have to assume the actual thrown
3672 /// exception type might have a throwing destructor, even if the
3673 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003674 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003675 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3676 bool MightThrow;
3677
3678 void Emit(CodeGenFunction &CGF, Flags flags) override {
3679 if (!MightThrow) {
3680 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3681 return;
3682 }
3683
3684 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3685 }
3686 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003687}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003688
3689/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3690/// __cxa_end_catch.
3691///
3692/// \param EndMightThrow - true if __cxa_end_catch might throw
3693static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3694 llvm::Value *Exn,
3695 bool EndMightThrow) {
3696 llvm::CallInst *call =
3697 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3698
3699 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3700
3701 return call;
3702}
3703
3704/// A "special initializer" callback for initializing a catch
3705/// parameter during catch initialization.
3706static void InitCatchParam(CodeGenFunction &CGF,
3707 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003708 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003709 SourceLocation Loc) {
3710 // Load the exception from where the landing pad saved it.
3711 llvm::Value *Exn = CGF.getExceptionFromSlot();
3712
3713 CanQualType CatchType =
3714 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3715 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3716
3717 // If we're catching by reference, we can just cast the object
3718 // pointer to the appropriate pointer.
3719 if (isa<ReferenceType>(CatchType)) {
3720 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3721 bool EndCatchMightThrow = CaughtType->isRecordType();
3722
3723 // __cxa_begin_catch returns the adjusted object pointer.
3724 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3725
3726 // We have no way to tell the personality function that we're
3727 // catching by reference, so if we're catching a pointer,
3728 // __cxa_begin_catch will actually return that pointer by value.
3729 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3730 QualType PointeeType = PT->getPointeeType();
3731
3732 // When catching by reference, generally we should just ignore
3733 // this by-value pointer and use the exception object instead.
3734 if (!PointeeType->isRecordType()) {
3735
3736 // Exn points to the struct _Unwind_Exception header, which
3737 // we have to skip past in order to reach the exception data.
3738 unsigned HeaderSize =
3739 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3740 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3741
3742 // However, if we're catching a pointer-to-record type that won't
3743 // work, because the personality function might have adjusted
3744 // the pointer. There's actually no way for us to fully satisfy
3745 // the language/ABI contract here: we can't use Exn because it
3746 // might have the wrong adjustment, but we can't use the by-value
3747 // pointer because it's off by a level of abstraction.
3748 //
3749 // The current solution is to dump the adjusted pointer into an
3750 // alloca, which breaks language semantics (because changing the
3751 // pointer doesn't change the exception) but at least works.
3752 // The better solution would be to filter out non-exact matches
3753 // and rethrow them, but this is tricky because the rethrow
3754 // really needs to be catchable by other sites at this landing
3755 // pad. The best solution is to fix the personality function.
3756 } else {
3757 // Pull the pointer for the reference type off.
3758 llvm::Type *PtrTy =
3759 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3760
3761 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003762 Address ExnPtrTmp =
3763 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003764 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3765 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3766
3767 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003768 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003769 }
3770 }
3771
3772 llvm::Value *ExnCast =
3773 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3774 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3775 return;
3776 }
3777
3778 // Scalars and complexes.
3779 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3780 if (TEK != TEK_Aggregate) {
3781 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3782
3783 // If the catch type is a pointer type, __cxa_begin_catch returns
3784 // the pointer by value.
3785 if (CatchType->hasPointerRepresentation()) {
3786 llvm::Value *CastExn =
3787 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3788
3789 switch (CatchType.getQualifiers().getObjCLifetime()) {
3790 case Qualifiers::OCL_Strong:
3791 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3792 // fallthrough
3793
3794 case Qualifiers::OCL_None:
3795 case Qualifiers::OCL_ExplicitNone:
3796 case Qualifiers::OCL_Autoreleasing:
3797 CGF.Builder.CreateStore(CastExn, ParamAddr);
3798 return;
3799
3800 case Qualifiers::OCL_Weak:
3801 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3802 return;
3803 }
3804 llvm_unreachable("bad ownership qualifier!");
3805 }
3806
3807 // Otherwise, it returns a pointer into the exception object.
3808
3809 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3810 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3811
3812 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003813 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003814 switch (TEK) {
3815 case TEK_Complex:
3816 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3817 /*init*/ true);
3818 return;
3819 case TEK_Scalar: {
3820 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3821 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3822 return;
3823 }
3824 case TEK_Aggregate:
3825 llvm_unreachable("evaluation kind filtered out!");
3826 }
3827 llvm_unreachable("bad evaluation kind");
3828 }
3829
3830 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003831 auto catchRD = CatchType->getAsCXXRecordDecl();
3832 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003833
3834 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3835
3836 // Check for a copy expression. If we don't have a copy expression,
3837 // that means a trivial copy is okay.
3838 const Expr *copyExpr = CatchParam.getInit();
3839 if (!copyExpr) {
3840 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003841 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3842 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003843 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3844 return;
3845 }
3846
3847 // We have to call __cxa_get_exception_ptr to get the adjusted
3848 // pointer before copying.
3849 llvm::CallInst *rawAdjustedExn =
3850 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3851
3852 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003853 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3854 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003855
3856 // The copy expression is defined in terms of an OpaqueValueExpr.
3857 // Find it and map it to the adjusted expression.
3858 CodeGenFunction::OpaqueValueMapping
3859 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3860 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3861
3862 // Call the copy ctor in a terminate scope.
3863 CGF.EHStack.pushTerminate();
3864
3865 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003866 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003867 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003868 AggValueSlot::IsNotDestructed,
3869 AggValueSlot::DoesNotNeedGCBarriers,
3870 AggValueSlot::IsNotAliased));
3871
3872 // Leave the terminate scope.
3873 CGF.EHStack.popTerminate();
3874
3875 // Undo the opaque value mapping.
3876 opaque.pop();
3877
3878 // Finally we can call __cxa_begin_catch.
3879 CallBeginCatch(CGF, Exn, true);
3880}
3881
3882/// Begins a catch statement by initializing the catch variable and
3883/// calling __cxa_begin_catch.
3884void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3885 const CXXCatchStmt *S) {
3886 // We have to be very careful with the ordering of cleanups here:
3887 // C++ [except.throw]p4:
3888 // The destruction [of the exception temporary] occurs
3889 // immediately after the destruction of the object declared in
3890 // the exception-declaration in the handler.
3891 //
3892 // So the precise ordering is:
3893 // 1. Construct catch variable.
3894 // 2. __cxa_begin_catch
3895 // 3. Enter __cxa_end_catch cleanup
3896 // 4. Enter dtor cleanup
3897 //
3898 // We do this by using a slightly abnormal initialization process.
3899 // Delegation sequence:
3900 // - ExitCXXTryStmt opens a RunCleanupsScope
3901 // - EmitAutoVarAlloca creates the variable and debug info
3902 // - InitCatchParam initializes the variable from the exception
3903 // - CallBeginCatch calls __cxa_begin_catch
3904 // - CallBeginCatch enters the __cxa_end_catch cleanup
3905 // - EmitAutoVarCleanups enters the variable destructor cleanup
3906 // - EmitCXXTryStmt emits the code for the catch body
3907 // - EmitCXXTryStmt close the RunCleanupsScope
3908
3909 VarDecl *CatchParam = S->getExceptionDecl();
3910 if (!CatchParam) {
3911 llvm::Value *Exn = CGF.getExceptionFromSlot();
3912 CallBeginCatch(CGF, Exn, true);
3913 return;
3914 }
3915
3916 // Emit the local.
3917 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3918 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3919 CGF.EmitAutoVarCleanups(var);
3920}
3921
3922/// Get or define the following function:
3923/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3924/// This code is used only in C++.
3925static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3926 llvm::FunctionType *fnTy =
3927 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3928 llvm::Constant *fnRef =
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003929 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate",
3930 llvm::AttributeSet(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003931
3932 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3933 if (fn && fn->empty()) {
3934 fn->setDoesNotThrow();
3935 fn->setDoesNotReturn();
3936
3937 // What we really want is to massively penalize inlining without
3938 // forbidding it completely. The difference between that and
3939 // 'noinline' is negligible.
3940 fn->addFnAttr(llvm::Attribute::NoInline);
3941
3942 // Allow this function to be shared across translation units, but
3943 // we don't want it to turn into an exported symbol.
3944 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3945 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003946 if (CGM.supportsCOMDAT())
3947 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003948
3949 // Set up the function.
3950 llvm::BasicBlock *entry =
3951 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003952 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003953
3954 // Pull the exception pointer out of the parameter list.
3955 llvm::Value *exn = &*fn->arg_begin();
3956
3957 // Call __cxa_begin_catch(exn).
3958 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3959 catchCall->setDoesNotThrow();
3960 catchCall->setCallingConv(CGM.getRuntimeCC());
3961
3962 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003963 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003964 termCall->setDoesNotThrow();
3965 termCall->setDoesNotReturn();
3966 termCall->setCallingConv(CGM.getRuntimeCC());
3967
3968 // std::terminate cannot return.
3969 builder.CreateUnreachable();
3970 }
3971
3972 return fnRef;
3973}
3974
3975llvm::CallInst *
3976ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3977 llvm::Value *Exn) {
3978 // In C++, we want to call __cxa_begin_catch() before terminating.
3979 if (Exn) {
3980 assert(CGF.CGM.getLangOpts().CPlusPlus);
3981 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3982 }
3983 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3984}